jimp.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675
  1. /*
  2. Jimp v0.10.2
  3. https://github.com/oliver-moran/jimp
  4. Ported for the Web by Phil Seaton
  5. MIT License
  6. Copyright (c) 2018 Oliver Moran
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all
  14. copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. */
  23. if ((typeof(window)=='undefined' || !window) && (typeof(self)!='undefined')) var window = self;
  24. (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.jimp = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  25. function _arrayWithHoles(arr) {
  26. if (Array.isArray(arr)) return arr;
  27. }
  28. module.exports = _arrayWithHoles;
  29. },{}],2:[function(require,module,exports){
  30. function _arrayWithoutHoles(arr) {
  31. if (Array.isArray(arr)) {
  32. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  33. arr2[i] = arr[i];
  34. }
  35. return arr2;
  36. }
  37. }
  38. module.exports = _arrayWithoutHoles;
  39. },{}],3:[function(require,module,exports){
  40. function _assertThisInitialized(self) {
  41. if (self === void 0) {
  42. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  43. }
  44. return self;
  45. }
  46. module.exports = _assertThisInitialized;
  47. },{}],4:[function(require,module,exports){
  48. function _classCallCheck(instance, Constructor) {
  49. if (!(instance instanceof Constructor)) {
  50. throw new TypeError("Cannot call a class as a function");
  51. }
  52. }
  53. module.exports = _classCallCheck;
  54. },{}],5:[function(require,module,exports){
  55. var setPrototypeOf = require("./setPrototypeOf");
  56. function isNativeReflectConstruct() {
  57. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  58. if (Reflect.construct.sham) return false;
  59. if (typeof Proxy === "function") return true;
  60. try {
  61. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  62. return true;
  63. } catch (e) {
  64. return false;
  65. }
  66. }
  67. function _construct(Parent, args, Class) {
  68. if (isNativeReflectConstruct()) {
  69. module.exports = _construct = Reflect.construct;
  70. } else {
  71. module.exports = _construct = function _construct(Parent, args, Class) {
  72. var a = [null];
  73. a.push.apply(a, args);
  74. var Constructor = Function.bind.apply(Parent, a);
  75. var instance = new Constructor();
  76. if (Class) setPrototypeOf(instance, Class.prototype);
  77. return instance;
  78. };
  79. }
  80. return _construct.apply(null, arguments);
  81. }
  82. module.exports = _construct;
  83. },{"./setPrototypeOf":17}],6:[function(require,module,exports){
  84. function _defineProperties(target, props) {
  85. for (var i = 0; i < props.length; i++) {
  86. var descriptor = props[i];
  87. descriptor.enumerable = descriptor.enumerable || false;
  88. descriptor.configurable = true;
  89. if ("value" in descriptor) descriptor.writable = true;
  90. Object.defineProperty(target, descriptor.key, descriptor);
  91. }
  92. }
  93. function _createClass(Constructor, protoProps, staticProps) {
  94. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  95. if (staticProps) _defineProperties(Constructor, staticProps);
  96. return Constructor;
  97. }
  98. module.exports = _createClass;
  99. },{}],7:[function(require,module,exports){
  100. function _defineProperty(obj, key, value) {
  101. if (key in obj) {
  102. Object.defineProperty(obj, key, {
  103. value: value,
  104. enumerable: true,
  105. configurable: true,
  106. writable: true
  107. });
  108. } else {
  109. obj[key] = value;
  110. }
  111. return obj;
  112. }
  113. module.exports = _defineProperty;
  114. },{}],8:[function(require,module,exports){
  115. function _getPrototypeOf(o) {
  116. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  117. return o.__proto__ || Object.getPrototypeOf(o);
  118. };
  119. return _getPrototypeOf(o);
  120. }
  121. module.exports = _getPrototypeOf;
  122. },{}],9:[function(require,module,exports){
  123. var setPrototypeOf = require("./setPrototypeOf");
  124. function _inherits(subClass, superClass) {
  125. if (typeof superClass !== "function" && superClass !== null) {
  126. throw new TypeError("Super expression must either be null or a function");
  127. }
  128. subClass.prototype = Object.create(superClass && superClass.prototype, {
  129. constructor: {
  130. value: subClass,
  131. writable: true,
  132. configurable: true
  133. }
  134. });
  135. if (superClass) setPrototypeOf(subClass, superClass);
  136. }
  137. module.exports = _inherits;
  138. },{"./setPrototypeOf":17}],10:[function(require,module,exports){
  139. function _interopRequireDefault(obj) {
  140. return obj && obj.__esModule ? obj : {
  141. "default": obj
  142. };
  143. }
  144. module.exports = _interopRequireDefault;
  145. },{}],11:[function(require,module,exports){
  146. var _typeof = require("../helpers/typeof");
  147. function _getRequireWildcardCache() {
  148. if (typeof WeakMap !== "function") return null;
  149. var cache = new WeakMap();
  150. _getRequireWildcardCache = function _getRequireWildcardCache() {
  151. return cache;
  152. };
  153. return cache;
  154. }
  155. function _interopRequireWildcard(obj) {
  156. if (obj && obj.__esModule) {
  157. return obj;
  158. }
  159. if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
  160. return {
  161. "default": obj
  162. };
  163. }
  164. var cache = _getRequireWildcardCache();
  165. if (cache && cache.has(obj)) {
  166. return cache.get(obj);
  167. }
  168. var newObj = {};
  169. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  170. for (var key in obj) {
  171. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  172. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  173. if (desc && (desc.get || desc.set)) {
  174. Object.defineProperty(newObj, key, desc);
  175. } else {
  176. newObj[key] = obj[key];
  177. }
  178. }
  179. }
  180. newObj["default"] = obj;
  181. if (cache) {
  182. cache.set(obj, newObj);
  183. }
  184. return newObj;
  185. }
  186. module.exports = _interopRequireWildcard;
  187. },{"../helpers/typeof":20}],12:[function(require,module,exports){
  188. function _iterableToArray(iter) {
  189. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  190. }
  191. module.exports = _iterableToArray;
  192. },{}],13:[function(require,module,exports){
  193. function _iterableToArrayLimit(arr, i) {
  194. if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
  195. return;
  196. }
  197. var _arr = [];
  198. var _n = true;
  199. var _d = false;
  200. var _e = undefined;
  201. try {
  202. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  203. _arr.push(_s.value);
  204. if (i && _arr.length === i) break;
  205. }
  206. } catch (err) {
  207. _d = true;
  208. _e = err;
  209. } finally {
  210. try {
  211. if (!_n && _i["return"] != null) _i["return"]();
  212. } finally {
  213. if (_d) throw _e;
  214. }
  215. }
  216. return _arr;
  217. }
  218. module.exports = _iterableToArrayLimit;
  219. },{}],14:[function(require,module,exports){
  220. function _nonIterableRest() {
  221. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  222. }
  223. module.exports = _nonIterableRest;
  224. },{}],15:[function(require,module,exports){
  225. function _nonIterableSpread() {
  226. throw new TypeError("Invalid attempt to spread non-iterable instance");
  227. }
  228. module.exports = _nonIterableSpread;
  229. },{}],16:[function(require,module,exports){
  230. var _typeof = require("../helpers/typeof");
  231. var assertThisInitialized = require("./assertThisInitialized");
  232. function _possibleConstructorReturn(self, call) {
  233. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  234. return call;
  235. }
  236. return assertThisInitialized(self);
  237. }
  238. module.exports = _possibleConstructorReturn;
  239. },{"../helpers/typeof":20,"./assertThisInitialized":3}],17:[function(require,module,exports){
  240. function _setPrototypeOf(o, p) {
  241. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  242. o.__proto__ = p;
  243. return o;
  244. };
  245. return _setPrototypeOf(o, p);
  246. }
  247. module.exports = _setPrototypeOf;
  248. },{}],18:[function(require,module,exports){
  249. var arrayWithHoles = require("./arrayWithHoles");
  250. var iterableToArrayLimit = require("./iterableToArrayLimit");
  251. var nonIterableRest = require("./nonIterableRest");
  252. function _slicedToArray(arr, i) {
  253. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
  254. }
  255. module.exports = _slicedToArray;
  256. },{"./arrayWithHoles":1,"./iterableToArrayLimit":13,"./nonIterableRest":14}],19:[function(require,module,exports){
  257. var arrayWithoutHoles = require("./arrayWithoutHoles");
  258. var iterableToArray = require("./iterableToArray");
  259. var nonIterableSpread = require("./nonIterableSpread");
  260. function _toConsumableArray(arr) {
  261. return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
  262. }
  263. module.exports = _toConsumableArray;
  264. },{"./arrayWithoutHoles":2,"./iterableToArray":12,"./nonIterableSpread":15}],20:[function(require,module,exports){
  265. function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
  266. function _typeof(obj) {
  267. if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
  268. module.exports = _typeof = function _typeof(obj) {
  269. return _typeof2(obj);
  270. };
  271. } else {
  272. module.exports = _typeof = function _typeof(obj) {
  273. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
  274. };
  275. }
  276. return _typeof(obj);
  277. }
  278. module.exports = _typeof;
  279. },{}],21:[function(require,module,exports){
  280. module.exports = require("regenerator-runtime");
  281. },{"regenerator-runtime":332}],22:[function(require,module,exports){
  282. var Converter = require('./src/converter');
  283. /**
  284. * Function get source and destination alphabet and return convert function
  285. *
  286. * @param {string|Array} srcAlphabet
  287. * @param {string|Array} dstAlphabet
  288. *
  289. * @returns {function(number|Array)}
  290. */
  291. function anyBase(srcAlphabet, dstAlphabet) {
  292. var converter = new Converter(srcAlphabet, dstAlphabet);
  293. /**
  294. * Convert function
  295. *
  296. * @param {string|Array} number
  297. *
  298. * @return {string|Array} number
  299. */
  300. return function (number) {
  301. return converter.convert(number);
  302. }
  303. };
  304. anyBase.BIN = '01';
  305. anyBase.OCT = '01234567';
  306. anyBase.DEC = '0123456789';
  307. anyBase.HEX = '0123456789abcdef';
  308. module.exports = anyBase;
  309. },{"./src/converter":23}],23:[function(require,module,exports){
  310. 'use strict';
  311. /**
  312. * Converter
  313. *
  314. * @param {string|Array} srcAlphabet
  315. * @param {string|Array} dstAlphabet
  316. * @constructor
  317. */
  318. function Converter(srcAlphabet, dstAlphabet) {
  319. if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {
  320. throw new Error('Bad alphabet');
  321. }
  322. this.srcAlphabet = srcAlphabet;
  323. this.dstAlphabet = dstAlphabet;
  324. }
  325. /**
  326. * Convert number from source alphabet to destination alphabet
  327. *
  328. * @param {string|Array} number - number represented as a string or array of points
  329. *
  330. * @returns {string|Array}
  331. */
  332. Converter.prototype.convert = function(number) {
  333. var i, divide, newlen,
  334. numberMap = {},
  335. fromBase = this.srcAlphabet.length,
  336. toBase = this.dstAlphabet.length,
  337. length = number.length,
  338. result = typeof number === 'string' ? '' : [];
  339. if (!this.isValid(number)) {
  340. throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ')');
  341. }
  342. if (this.srcAlphabet === this.dstAlphabet) {
  343. return number;
  344. }
  345. for (i = 0; i < length; i++) {
  346. numberMap[i] = this.srcAlphabet.indexOf(number[i]);
  347. }
  348. do {
  349. divide = 0;
  350. newlen = 0;
  351. for (i = 0; i < length; i++) {
  352. divide = divide * fromBase + numberMap[i];
  353. if (divide >= toBase) {
  354. numberMap[newlen++] = parseInt(divide / toBase, 10);
  355. divide = divide % toBase;
  356. } else if (newlen > 0) {
  357. numberMap[newlen++] = 0;
  358. }
  359. }
  360. length = newlen;
  361. result = this.dstAlphabet.slice(divide, divide + 1).concat(result);
  362. } while (newlen !== 0);
  363. return result;
  364. };
  365. /**
  366. * Valid number with source alphabet
  367. *
  368. * @param {number} number
  369. *
  370. * @returns {boolean}
  371. */
  372. Converter.prototype.isValid = function(number) {
  373. var i = 0;
  374. for (; i < number.length; ++i) {
  375. if (this.srcAlphabet.indexOf(number[i]) === -1) {
  376. return false;
  377. }
  378. }
  379. return true;
  380. };
  381. module.exports = Converter;
  382. },{}],24:[function(require,module,exports){
  383. (function (global){
  384. 'use strict';
  385. var objectAssign = require('object-assign');
  386. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  387. // original notice:
  388. /*!
  389. * The buffer module from node.js, for the browser.
  390. *
  391. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  392. * @license MIT
  393. */
  394. function compare(a, b) {
  395. if (a === b) {
  396. return 0;
  397. }
  398. var x = a.length;
  399. var y = b.length;
  400. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  401. if (a[i] !== b[i]) {
  402. x = a[i];
  403. y = b[i];
  404. break;
  405. }
  406. }
  407. if (x < y) {
  408. return -1;
  409. }
  410. if (y < x) {
  411. return 1;
  412. }
  413. return 0;
  414. }
  415. function isBuffer(b) {
  416. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  417. return global.Buffer.isBuffer(b);
  418. }
  419. return !!(b != null && b._isBuffer);
  420. }
  421. // based on node assert, original notice:
  422. // NB: The URL to the CommonJS spec is kept just for tradition.
  423. // node-assert has evolved a lot since then, both in API and behavior.
  424. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  425. //
  426. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  427. //
  428. // Originally from narwhal.js (http://narwhaljs.org)
  429. // Copyright (c) 2009 Thomas Robinson <280north.com>
  430. //
  431. // Permission is hereby granted, free of charge, to any person obtaining a copy
  432. // of this software and associated documentation files (the 'Software'), to
  433. // deal in the Software without restriction, including without limitation the
  434. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  435. // sell copies of the Software, and to permit persons to whom the Software is
  436. // furnished to do so, subject to the following conditions:
  437. //
  438. // The above copyright notice and this permission notice shall be included in
  439. // all copies or substantial portions of the Software.
  440. //
  441. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  442. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  443. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  444. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  445. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  446. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  447. var util = require('util/');
  448. var hasOwn = Object.prototype.hasOwnProperty;
  449. var pSlice = Array.prototype.slice;
  450. var functionsHaveNames = (function () {
  451. return function foo() {}.name === 'foo';
  452. }());
  453. function pToString (obj) {
  454. return Object.prototype.toString.call(obj);
  455. }
  456. function isView(arrbuf) {
  457. if (isBuffer(arrbuf)) {
  458. return false;
  459. }
  460. if (typeof global.ArrayBuffer !== 'function') {
  461. return false;
  462. }
  463. if (typeof ArrayBuffer.isView === 'function') {
  464. return ArrayBuffer.isView(arrbuf);
  465. }
  466. if (!arrbuf) {
  467. return false;
  468. }
  469. if (arrbuf instanceof DataView) {
  470. return true;
  471. }
  472. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  473. return true;
  474. }
  475. return false;
  476. }
  477. // 1. The assert module provides functions that throw
  478. // AssertionError's when particular conditions are not met. The
  479. // assert module must conform to the following interface.
  480. var assert = module.exports = ok;
  481. // 2. The AssertionError is defined in assert.
  482. // new assert.AssertionError({ message: message,
  483. // actual: actual,
  484. // expected: expected })
  485. var regex = /\s*function\s+([^\(\s]*)\s*/;
  486. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  487. function getName(func) {
  488. if (!util.isFunction(func)) {
  489. return;
  490. }
  491. if (functionsHaveNames) {
  492. return func.name;
  493. }
  494. var str = func.toString();
  495. var match = str.match(regex);
  496. return match && match[1];
  497. }
  498. assert.AssertionError = function AssertionError(options) {
  499. this.name = 'AssertionError';
  500. this.actual = options.actual;
  501. this.expected = options.expected;
  502. this.operator = options.operator;
  503. if (options.message) {
  504. this.message = options.message;
  505. this.generatedMessage = false;
  506. } else {
  507. this.message = getMessage(this);
  508. this.generatedMessage = true;
  509. }
  510. var stackStartFunction = options.stackStartFunction || fail;
  511. if (Error.captureStackTrace) {
  512. Error.captureStackTrace(this, stackStartFunction);
  513. } else {
  514. // non v8 browsers so we can have a stacktrace
  515. var err = new Error();
  516. if (err.stack) {
  517. var out = err.stack;
  518. // try to strip useless frames
  519. var fn_name = getName(stackStartFunction);
  520. var idx = out.indexOf('\n' + fn_name);
  521. if (idx >= 0) {
  522. // once we have located the function frame
  523. // we need to strip out everything before it (and its line)
  524. var next_line = out.indexOf('\n', idx + 1);
  525. out = out.substring(next_line + 1);
  526. }
  527. this.stack = out;
  528. }
  529. }
  530. };
  531. // assert.AssertionError instanceof Error
  532. util.inherits(assert.AssertionError, Error);
  533. function truncate(s, n) {
  534. if (typeof s === 'string') {
  535. return s.length < n ? s : s.slice(0, n);
  536. } else {
  537. return s;
  538. }
  539. }
  540. function inspect(something) {
  541. if (functionsHaveNames || !util.isFunction(something)) {
  542. return util.inspect(something);
  543. }
  544. var rawname = getName(something);
  545. var name = rawname ? ': ' + rawname : '';
  546. return '[Function' + name + ']';
  547. }
  548. function getMessage(self) {
  549. return truncate(inspect(self.actual), 128) + ' ' +
  550. self.operator + ' ' +
  551. truncate(inspect(self.expected), 128);
  552. }
  553. // At present only the three keys mentioned above are used and
  554. // understood by the spec. Implementations or sub modules can pass
  555. // other keys to the AssertionError's constructor - they will be
  556. // ignored.
  557. // 3. All of the following functions must throw an AssertionError
  558. // when a corresponding condition is not met, with a message that
  559. // may be undefined if not provided. All assertion methods provide
  560. // both the actual and expected values to the assertion error for
  561. // display purposes.
  562. function fail(actual, expected, message, operator, stackStartFunction) {
  563. throw new assert.AssertionError({
  564. message: message,
  565. actual: actual,
  566. expected: expected,
  567. operator: operator,
  568. stackStartFunction: stackStartFunction
  569. });
  570. }
  571. // EXTENSION! allows for well behaved errors defined elsewhere.
  572. assert.fail = fail;
  573. // 4. Pure assertion tests whether a value is truthy, as determined
  574. // by !!guard.
  575. // assert.ok(guard, message_opt);
  576. // This statement is equivalent to assert.equal(true, !!guard,
  577. // message_opt);. To test strictly for the value true, use
  578. // assert.strictEqual(true, guard, message_opt);.
  579. function ok(value, message) {
  580. if (!value) fail(value, true, message, '==', assert.ok);
  581. }
  582. assert.ok = ok;
  583. // 5. The equality assertion tests shallow, coercive equality with
  584. // ==.
  585. // assert.equal(actual, expected, message_opt);
  586. assert.equal = function equal(actual, expected, message) {
  587. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  588. };
  589. // 6. The non-equality assertion tests for whether two objects are not equal
  590. // with != assert.notEqual(actual, expected, message_opt);
  591. assert.notEqual = function notEqual(actual, expected, message) {
  592. if (actual == expected) {
  593. fail(actual, expected, message, '!=', assert.notEqual);
  594. }
  595. };
  596. // 7. The equivalence assertion tests a deep equality relation.
  597. // assert.deepEqual(actual, expected, message_opt);
  598. assert.deepEqual = function deepEqual(actual, expected, message) {
  599. if (!_deepEqual(actual, expected, false)) {
  600. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  601. }
  602. };
  603. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  604. if (!_deepEqual(actual, expected, true)) {
  605. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  606. }
  607. };
  608. function _deepEqual(actual, expected, strict, memos) {
  609. // 7.1. All identical values are equivalent, as determined by ===.
  610. if (actual === expected) {
  611. return true;
  612. } else if (isBuffer(actual) && isBuffer(expected)) {
  613. return compare(actual, expected) === 0;
  614. // 7.2. If the expected value is a Date object, the actual value is
  615. // equivalent if it is also a Date object that refers to the same time.
  616. } else if (util.isDate(actual) && util.isDate(expected)) {
  617. return actual.getTime() === expected.getTime();
  618. // 7.3 If the expected value is a RegExp object, the actual value is
  619. // equivalent if it is also a RegExp object with the same source and
  620. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  621. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  622. return actual.source === expected.source &&
  623. actual.global === expected.global &&
  624. actual.multiline === expected.multiline &&
  625. actual.lastIndex === expected.lastIndex &&
  626. actual.ignoreCase === expected.ignoreCase;
  627. // 7.4. Other pairs that do not both pass typeof value == 'object',
  628. // equivalence is determined by ==.
  629. } else if ((actual === null || typeof actual !== 'object') &&
  630. (expected === null || typeof expected !== 'object')) {
  631. return strict ? actual === expected : actual == expected;
  632. // If both values are instances of typed arrays, wrap their underlying
  633. // ArrayBuffers in a Buffer each to increase performance
  634. // This optimization requires the arrays to have the same type as checked by
  635. // Object.prototype.toString (aka pToString). Never perform binary
  636. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  637. // bit patterns are not identical.
  638. } else if (isView(actual) && isView(expected) &&
  639. pToString(actual) === pToString(expected) &&
  640. !(actual instanceof Float32Array ||
  641. actual instanceof Float64Array)) {
  642. return compare(new Uint8Array(actual.buffer),
  643. new Uint8Array(expected.buffer)) === 0;
  644. // 7.5 For all other Object pairs, including Array objects, equivalence is
  645. // determined by having the same number of owned properties (as verified
  646. // with Object.prototype.hasOwnProperty.call), the same set of keys
  647. // (although not necessarily the same order), equivalent values for every
  648. // corresponding key, and an identical 'prototype' property. Note: this
  649. // accounts for both named and indexed properties on Arrays.
  650. } else if (isBuffer(actual) !== isBuffer(expected)) {
  651. return false;
  652. } else {
  653. memos = memos || {actual: [], expected: []};
  654. var actualIndex = memos.actual.indexOf(actual);
  655. if (actualIndex !== -1) {
  656. if (actualIndex === memos.expected.indexOf(expected)) {
  657. return true;
  658. }
  659. }
  660. memos.actual.push(actual);
  661. memos.expected.push(expected);
  662. return objEquiv(actual, expected, strict, memos);
  663. }
  664. }
  665. function isArguments(object) {
  666. return Object.prototype.toString.call(object) == '[object Arguments]';
  667. }
  668. function objEquiv(a, b, strict, actualVisitedObjects) {
  669. if (a === null || a === undefined || b === null || b === undefined)
  670. return false;
  671. // if one is a primitive, the other must be same
  672. if (util.isPrimitive(a) || util.isPrimitive(b))
  673. return a === b;
  674. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  675. return false;
  676. var aIsArgs = isArguments(a);
  677. var bIsArgs = isArguments(b);
  678. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  679. return false;
  680. if (aIsArgs) {
  681. a = pSlice.call(a);
  682. b = pSlice.call(b);
  683. return _deepEqual(a, b, strict);
  684. }
  685. var ka = objectKeys(a);
  686. var kb = objectKeys(b);
  687. var key, i;
  688. // having the same number of owned properties (keys incorporates
  689. // hasOwnProperty)
  690. if (ka.length !== kb.length)
  691. return false;
  692. //the same set of keys (although not necessarily the same order),
  693. ka.sort();
  694. kb.sort();
  695. //~~~cheap key test
  696. for (i = ka.length - 1; i >= 0; i--) {
  697. if (ka[i] !== kb[i])
  698. return false;
  699. }
  700. //equivalent values for every corresponding key, and
  701. //~~~possibly expensive deep test
  702. for (i = ka.length - 1; i >= 0; i--) {
  703. key = ka[i];
  704. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  705. return false;
  706. }
  707. return true;
  708. }
  709. // 8. The non-equivalence assertion tests for any deep inequality.
  710. // assert.notDeepEqual(actual, expected, message_opt);
  711. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  712. if (_deepEqual(actual, expected, false)) {
  713. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  714. }
  715. };
  716. assert.notDeepStrictEqual = notDeepStrictEqual;
  717. function notDeepStrictEqual(actual, expected, message) {
  718. if (_deepEqual(actual, expected, true)) {
  719. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  720. }
  721. }
  722. // 9. The strict equality assertion tests strict equality, as determined by ===.
  723. // assert.strictEqual(actual, expected, message_opt);
  724. assert.strictEqual = function strictEqual(actual, expected, message) {
  725. if (actual !== expected) {
  726. fail(actual, expected, message, '===', assert.strictEqual);
  727. }
  728. };
  729. // 10. The strict non-equality assertion tests for strict inequality, as
  730. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  731. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  732. if (actual === expected) {
  733. fail(actual, expected, message, '!==', assert.notStrictEqual);
  734. }
  735. };
  736. function expectedException(actual, expected) {
  737. if (!actual || !expected) {
  738. return false;
  739. }
  740. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  741. return expected.test(actual);
  742. }
  743. try {
  744. if (actual instanceof expected) {
  745. return true;
  746. }
  747. } catch (e) {
  748. // Ignore. The instanceof check doesn't work for arrow functions.
  749. }
  750. if (Error.isPrototypeOf(expected)) {
  751. return false;
  752. }
  753. return expected.call({}, actual) === true;
  754. }
  755. function _tryBlock(block) {
  756. var error;
  757. try {
  758. block();
  759. } catch (e) {
  760. error = e;
  761. }
  762. return error;
  763. }
  764. function _throws(shouldThrow, block, expected, message) {
  765. var actual;
  766. if (typeof block !== 'function') {
  767. throw new TypeError('"block" argument must be a function');
  768. }
  769. if (typeof expected === 'string') {
  770. message = expected;
  771. expected = null;
  772. }
  773. actual = _tryBlock(block);
  774. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  775. (message ? ' ' + message : '.');
  776. if (shouldThrow && !actual) {
  777. fail(actual, expected, 'Missing expected exception' + message);
  778. }
  779. var userProvidedMessage = typeof message === 'string';
  780. var isUnwantedException = !shouldThrow && util.isError(actual);
  781. var isUnexpectedException = !shouldThrow && actual && !expected;
  782. if ((isUnwantedException &&
  783. userProvidedMessage &&
  784. expectedException(actual, expected)) ||
  785. isUnexpectedException) {
  786. fail(actual, expected, 'Got unwanted exception' + message);
  787. }
  788. if ((shouldThrow && actual && expected &&
  789. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  790. throw actual;
  791. }
  792. }
  793. // 11. Expected to throw an error:
  794. // assert.throws(block, Error_opt, message_opt);
  795. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  796. _throws(true, block, error, message);
  797. };
  798. // EXTENSION! This is annoying to write outside this module.
  799. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  800. _throws(false, block, error, message);
  801. };
  802. assert.ifError = function(err) { if (err) throw err; };
  803. // Expose a strict only variant of assert
  804. function strict(value, message) {
  805. if (!value) fail(value, true, message, '==', strict);
  806. }
  807. assert.strict = objectAssign(strict, assert, {
  808. equal: assert.strictEqual,
  809. deepEqual: assert.deepStrictEqual,
  810. notEqual: assert.notStrictEqual,
  811. notDeepEqual: assert.notDeepStrictEqual
  812. });
  813. assert.strict.strict = assert.strict;
  814. var objectKeys = Object.keys || function (obj) {
  815. var keys = [];
  816. for (var key in obj) {
  817. if (hasOwn.call(obj, key)) keys.push(key);
  818. }
  819. return keys;
  820. };
  821. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  822. },{"object-assign":263,"util/":27}],25:[function(require,module,exports){
  823. if (typeof Object.create === 'function') {
  824. // implementation from standard node.js 'util' module
  825. module.exports = function inherits(ctor, superCtor) {
  826. ctor.super_ = superCtor
  827. ctor.prototype = Object.create(superCtor.prototype, {
  828. constructor: {
  829. value: ctor,
  830. enumerable: false,
  831. writable: true,
  832. configurable: true
  833. }
  834. });
  835. };
  836. } else {
  837. // old school shim for old browsers
  838. module.exports = function inherits(ctor, superCtor) {
  839. ctor.super_ = superCtor
  840. var TempCtor = function () {}
  841. TempCtor.prototype = superCtor.prototype
  842. ctor.prototype = new TempCtor()
  843. ctor.prototype.constructor = ctor
  844. }
  845. }
  846. },{}],26:[function(require,module,exports){
  847. module.exports = function isBuffer(arg) {
  848. return arg && typeof arg === 'object'
  849. && typeof arg.copy === 'function'
  850. && typeof arg.fill === 'function'
  851. && typeof arg.readUInt8 === 'function';
  852. }
  853. },{}],27:[function(require,module,exports){
  854. (function (process,global){
  855. // Copyright Joyent, Inc. and other Node contributors.
  856. //
  857. // Permission is hereby granted, free of charge, to any person obtaining a
  858. // copy of this software and associated documentation files (the
  859. // "Software"), to deal in the Software without restriction, including
  860. // without limitation the rights to use, copy, modify, merge, publish,
  861. // distribute, sublicense, and/or sell copies of the Software, and to permit
  862. // persons to whom the Software is furnished to do so, subject to the
  863. // following conditions:
  864. //
  865. // The above copyright notice and this permission notice shall be included
  866. // in all copies or substantial portions of the Software.
  867. //
  868. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  869. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  870. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  871. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  872. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  873. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  874. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  875. var formatRegExp = /%[sdj%]/g;
  876. exports.format = function(f) {
  877. if (!isString(f)) {
  878. var objects = [];
  879. for (var i = 0; i < arguments.length; i++) {
  880. objects.push(inspect(arguments[i]));
  881. }
  882. return objects.join(' ');
  883. }
  884. var i = 1;
  885. var args = arguments;
  886. var len = args.length;
  887. var str = String(f).replace(formatRegExp, function(x) {
  888. if (x === '%%') return '%';
  889. if (i >= len) return x;
  890. switch (x) {
  891. case '%s': return String(args[i++]);
  892. case '%d': return Number(args[i++]);
  893. case '%j':
  894. try {
  895. return JSON.stringify(args[i++]);
  896. } catch (_) {
  897. return '[Circular]';
  898. }
  899. default:
  900. return x;
  901. }
  902. });
  903. for (var x = args[i]; i < len; x = args[++i]) {
  904. if (isNull(x) || !isObject(x)) {
  905. str += ' ' + x;
  906. } else {
  907. str += ' ' + inspect(x);
  908. }
  909. }
  910. return str;
  911. };
  912. // Mark that a method should not be used.
  913. // Returns a modified function which warns once by default.
  914. // If --no-deprecation is set, then it is a no-op.
  915. exports.deprecate = function(fn, msg) {
  916. // Allow for deprecating things in the process of starting up.
  917. if (isUndefined(global.process)) {
  918. return function() {
  919. return exports.deprecate(fn, msg).apply(this, arguments);
  920. };
  921. }
  922. if (process.noDeprecation === true) {
  923. return fn;
  924. }
  925. var warned = false;
  926. function deprecated() {
  927. if (!warned) {
  928. if (process.throwDeprecation) {
  929. throw new Error(msg);
  930. } else if (process.traceDeprecation) {
  931. console.trace(msg);
  932. } else {
  933. console.error(msg);
  934. }
  935. warned = true;
  936. }
  937. return fn.apply(this, arguments);
  938. }
  939. return deprecated;
  940. };
  941. var debugs = {};
  942. var debugEnviron;
  943. exports.debuglog = function(set) {
  944. if (isUndefined(debugEnviron))
  945. debugEnviron = process.env.NODE_DEBUG || '';
  946. set = set.toUpperCase();
  947. if (!debugs[set]) {
  948. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  949. var pid = process.pid;
  950. debugs[set] = function() {
  951. var msg = exports.format.apply(exports, arguments);
  952. console.error('%s %d: %s', set, pid, msg);
  953. };
  954. } else {
  955. debugs[set] = function() {};
  956. }
  957. }
  958. return debugs[set];
  959. };
  960. /**
  961. * Echos the value of a value. Trys to print the value out
  962. * in the best way possible given the different types.
  963. *
  964. * @param {Object} obj The object to print out.
  965. * @param {Object} opts Optional options object that alters the output.
  966. */
  967. /* legacy: obj, showHidden, depth, colors*/
  968. function inspect(obj, opts) {
  969. // default options
  970. var ctx = {
  971. seen: [],
  972. stylize: stylizeNoColor
  973. };
  974. // legacy...
  975. if (arguments.length >= 3) ctx.depth = arguments[2];
  976. if (arguments.length >= 4) ctx.colors = arguments[3];
  977. if (isBoolean(opts)) {
  978. // legacy...
  979. ctx.showHidden = opts;
  980. } else if (opts) {
  981. // got an "options" object
  982. exports._extend(ctx, opts);
  983. }
  984. // set default options
  985. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  986. if (isUndefined(ctx.depth)) ctx.depth = 2;
  987. if (isUndefined(ctx.colors)) ctx.colors = false;
  988. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  989. if (ctx.colors) ctx.stylize = stylizeWithColor;
  990. return formatValue(ctx, obj, ctx.depth);
  991. }
  992. exports.inspect = inspect;
  993. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  994. inspect.colors = {
  995. 'bold' : [1, 22],
  996. 'italic' : [3, 23],
  997. 'underline' : [4, 24],
  998. 'inverse' : [7, 27],
  999. 'white' : [37, 39],
  1000. 'grey' : [90, 39],
  1001. 'black' : [30, 39],
  1002. 'blue' : [34, 39],
  1003. 'cyan' : [36, 39],
  1004. 'green' : [32, 39],
  1005. 'magenta' : [35, 39],
  1006. 'red' : [31, 39],
  1007. 'yellow' : [33, 39]
  1008. };
  1009. // Don't use 'blue' not visible on cmd.exe
  1010. inspect.styles = {
  1011. 'special': 'cyan',
  1012. 'number': 'yellow',
  1013. 'boolean': 'yellow',
  1014. 'undefined': 'grey',
  1015. 'null': 'bold',
  1016. 'string': 'green',
  1017. 'date': 'magenta',
  1018. // "name": intentionally not styling
  1019. 'regexp': 'red'
  1020. };
  1021. function stylizeWithColor(str, styleType) {
  1022. var style = inspect.styles[styleType];
  1023. if (style) {
  1024. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  1025. '\u001b[' + inspect.colors[style][1] + 'm';
  1026. } else {
  1027. return str;
  1028. }
  1029. }
  1030. function stylizeNoColor(str, styleType) {
  1031. return str;
  1032. }
  1033. function arrayToHash(array) {
  1034. var hash = {};
  1035. array.forEach(function(val, idx) {
  1036. hash[val] = true;
  1037. });
  1038. return hash;
  1039. }
  1040. function formatValue(ctx, value, recurseTimes) {
  1041. // Provide a hook for user-specified inspect functions.
  1042. // Check that value is an object with an inspect function on it
  1043. if (ctx.customInspect &&
  1044. value &&
  1045. isFunction(value.inspect) &&
  1046. // Filter out the util module, it's inspect function is special
  1047. value.inspect !== exports.inspect &&
  1048. // Also filter out any prototype objects using the circular check.
  1049. !(value.constructor && value.constructor.prototype === value)) {
  1050. var ret = value.inspect(recurseTimes, ctx);
  1051. if (!isString(ret)) {
  1052. ret = formatValue(ctx, ret, recurseTimes);
  1053. }
  1054. return ret;
  1055. }
  1056. // Primitive types cannot have properties
  1057. var primitive = formatPrimitive(ctx, value);
  1058. if (primitive) {
  1059. return primitive;
  1060. }
  1061. // Look up the keys of the object.
  1062. var keys = Object.keys(value);
  1063. var visibleKeys = arrayToHash(keys);
  1064. if (ctx.showHidden) {
  1065. keys = Object.getOwnPropertyNames(value);
  1066. }
  1067. // IE doesn't make error fields non-enumerable
  1068. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  1069. if (isError(value)
  1070. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  1071. return formatError(value);
  1072. }
  1073. // Some type of object without properties can be shortcutted.
  1074. if (keys.length === 0) {
  1075. if (isFunction(value)) {
  1076. var name = value.name ? ': ' + value.name : '';
  1077. return ctx.stylize('[Function' + name + ']', 'special');
  1078. }
  1079. if (isRegExp(value)) {
  1080. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  1081. }
  1082. if (isDate(value)) {
  1083. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  1084. }
  1085. if (isError(value)) {
  1086. return formatError(value);
  1087. }
  1088. }
  1089. var base = '', array = false, braces = ['{', '}'];
  1090. // Make Array say that they are Array
  1091. if (isArray(value)) {
  1092. array = true;
  1093. braces = ['[', ']'];
  1094. }
  1095. // Make functions say that they are functions
  1096. if (isFunction(value)) {
  1097. var n = value.name ? ': ' + value.name : '';
  1098. base = ' [Function' + n + ']';
  1099. }
  1100. // Make RegExps say that they are RegExps
  1101. if (isRegExp(value)) {
  1102. base = ' ' + RegExp.prototype.toString.call(value);
  1103. }
  1104. // Make dates with properties first say the date
  1105. if (isDate(value)) {
  1106. base = ' ' + Date.prototype.toUTCString.call(value);
  1107. }
  1108. // Make error with message first say the error
  1109. if (isError(value)) {
  1110. base = ' ' + formatError(value);
  1111. }
  1112. if (keys.length === 0 && (!array || value.length == 0)) {
  1113. return braces[0] + base + braces[1];
  1114. }
  1115. if (recurseTimes < 0) {
  1116. if (isRegExp(value)) {
  1117. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  1118. } else {
  1119. return ctx.stylize('[Object]', 'special');
  1120. }
  1121. }
  1122. ctx.seen.push(value);
  1123. var output;
  1124. if (array) {
  1125. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  1126. } else {
  1127. output = keys.map(function(key) {
  1128. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  1129. });
  1130. }
  1131. ctx.seen.pop();
  1132. return reduceToSingleString(output, base, braces);
  1133. }
  1134. function formatPrimitive(ctx, value) {
  1135. if (isUndefined(value))
  1136. return ctx.stylize('undefined', 'undefined');
  1137. if (isString(value)) {
  1138. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  1139. .replace(/'/g, "\\'")
  1140. .replace(/\\"/g, '"') + '\'';
  1141. return ctx.stylize(simple, 'string');
  1142. }
  1143. if (isNumber(value))
  1144. return ctx.stylize('' + value, 'number');
  1145. if (isBoolean(value))
  1146. return ctx.stylize('' + value, 'boolean');
  1147. // For some reason typeof null is "object", so special case here.
  1148. if (isNull(value))
  1149. return ctx.stylize('null', 'null');
  1150. }
  1151. function formatError(value) {
  1152. return '[' + Error.prototype.toString.call(value) + ']';
  1153. }
  1154. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  1155. var output = [];
  1156. for (var i = 0, l = value.length; i < l; ++i) {
  1157. if (hasOwnProperty(value, String(i))) {
  1158. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  1159. String(i), true));
  1160. } else {
  1161. output.push('');
  1162. }
  1163. }
  1164. keys.forEach(function(key) {
  1165. if (!key.match(/^\d+$/)) {
  1166. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  1167. key, true));
  1168. }
  1169. });
  1170. return output;
  1171. }
  1172. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  1173. var name, str, desc;
  1174. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  1175. if (desc.get) {
  1176. if (desc.set) {
  1177. str = ctx.stylize('[Getter/Setter]', 'special');
  1178. } else {
  1179. str = ctx.stylize('[Getter]', 'special');
  1180. }
  1181. } else {
  1182. if (desc.set) {
  1183. str = ctx.stylize('[Setter]', 'special');
  1184. }
  1185. }
  1186. if (!hasOwnProperty(visibleKeys, key)) {
  1187. name = '[' + key + ']';
  1188. }
  1189. if (!str) {
  1190. if (ctx.seen.indexOf(desc.value) < 0) {
  1191. if (isNull(recurseTimes)) {
  1192. str = formatValue(ctx, desc.value, null);
  1193. } else {
  1194. str = formatValue(ctx, desc.value, recurseTimes - 1);
  1195. }
  1196. if (str.indexOf('\n') > -1) {
  1197. if (array) {
  1198. str = str.split('\n').map(function(line) {
  1199. return ' ' + line;
  1200. }).join('\n').substr(2);
  1201. } else {
  1202. str = '\n' + str.split('\n').map(function(line) {
  1203. return ' ' + line;
  1204. }).join('\n');
  1205. }
  1206. }
  1207. } else {
  1208. str = ctx.stylize('[Circular]', 'special');
  1209. }
  1210. }
  1211. if (isUndefined(name)) {
  1212. if (array && key.match(/^\d+$/)) {
  1213. return str;
  1214. }
  1215. name = JSON.stringify('' + key);
  1216. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  1217. name = name.substr(1, name.length - 2);
  1218. name = ctx.stylize(name, 'name');
  1219. } else {
  1220. name = name.replace(/'/g, "\\'")
  1221. .replace(/\\"/g, '"')
  1222. .replace(/(^"|"$)/g, "'");
  1223. name = ctx.stylize(name, 'string');
  1224. }
  1225. }
  1226. return name + ': ' + str;
  1227. }
  1228. function reduceToSingleString(output, base, braces) {
  1229. var numLinesEst = 0;
  1230. var length = output.reduce(function(prev, cur) {
  1231. numLinesEst++;
  1232. if (cur.indexOf('\n') >= 0) numLinesEst++;
  1233. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  1234. }, 0);
  1235. if (length > 60) {
  1236. return braces[0] +
  1237. (base === '' ? '' : base + '\n ') +
  1238. ' ' +
  1239. output.join(',\n ') +
  1240. ' ' +
  1241. braces[1];
  1242. }
  1243. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  1244. }
  1245. // NOTE: These type checking functions intentionally don't use `instanceof`
  1246. // because it is fragile and can be easily faked with `Object.create()`.
  1247. function isArray(ar) {
  1248. return Array.isArray(ar);
  1249. }
  1250. exports.isArray = isArray;
  1251. function isBoolean(arg) {
  1252. return typeof arg === 'boolean';
  1253. }
  1254. exports.isBoolean = isBoolean;
  1255. function isNull(arg) {
  1256. return arg === null;
  1257. }
  1258. exports.isNull = isNull;
  1259. function isNullOrUndefined(arg) {
  1260. return arg == null;
  1261. }
  1262. exports.isNullOrUndefined = isNullOrUndefined;
  1263. function isNumber(arg) {
  1264. return typeof arg === 'number';
  1265. }
  1266. exports.isNumber = isNumber;
  1267. function isString(arg) {
  1268. return typeof arg === 'string';
  1269. }
  1270. exports.isString = isString;
  1271. function isSymbol(arg) {
  1272. return typeof arg === 'symbol';
  1273. }
  1274. exports.isSymbol = isSymbol;
  1275. function isUndefined(arg) {
  1276. return arg === void 0;
  1277. }
  1278. exports.isUndefined = isUndefined;
  1279. function isRegExp(re) {
  1280. return isObject(re) && objectToString(re) === '[object RegExp]';
  1281. }
  1282. exports.isRegExp = isRegExp;
  1283. function isObject(arg) {
  1284. return typeof arg === 'object' && arg !== null;
  1285. }
  1286. exports.isObject = isObject;
  1287. function isDate(d) {
  1288. return isObject(d) && objectToString(d) === '[object Date]';
  1289. }
  1290. exports.isDate = isDate;
  1291. function isError(e) {
  1292. return isObject(e) &&
  1293. (objectToString(e) === '[object Error]' || e instanceof Error);
  1294. }
  1295. exports.isError = isError;
  1296. function isFunction(arg) {
  1297. return typeof arg === 'function';
  1298. }
  1299. exports.isFunction = isFunction;
  1300. function isPrimitive(arg) {
  1301. return arg === null ||
  1302. typeof arg === 'boolean' ||
  1303. typeof arg === 'number' ||
  1304. typeof arg === 'string' ||
  1305. typeof arg === 'symbol' || // ES6 symbol
  1306. typeof arg === 'undefined';
  1307. }
  1308. exports.isPrimitive = isPrimitive;
  1309. exports.isBuffer = require('./support/isBuffer');
  1310. function objectToString(o) {
  1311. return Object.prototype.toString.call(o);
  1312. }
  1313. function pad(n) {
  1314. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  1315. }
  1316. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  1317. 'Oct', 'Nov', 'Dec'];
  1318. // 26 Feb 16:19:34
  1319. function timestamp() {
  1320. var d = new Date();
  1321. var time = [pad(d.getHours()),
  1322. pad(d.getMinutes()),
  1323. pad(d.getSeconds())].join(':');
  1324. return [d.getDate(), months[d.getMonth()], time].join(' ');
  1325. }
  1326. // log is just a thin wrapper to console.log that prepends a timestamp
  1327. exports.log = function() {
  1328. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  1329. };
  1330. /**
  1331. * Inherit the prototype methods from one constructor into another.
  1332. *
  1333. * The Function.prototype.inherits from lang.js rewritten as a standalone
  1334. * function (not on Function.prototype). NOTE: If this file is to be loaded
  1335. * during bootstrapping this function needs to be rewritten using some native
  1336. * functions as prototype setup using normal JavaScript does not work as
  1337. * expected during bootstrapping (see mirror.js in r114903).
  1338. *
  1339. * @param {function} ctor Constructor function which needs to inherit the
  1340. * prototype.
  1341. * @param {function} superCtor Constructor function to inherit prototype from.
  1342. */
  1343. exports.inherits = require('inherits');
  1344. exports._extend = function(origin, add) {
  1345. // Don't do anything if add isn't an object
  1346. if (!add || !isObject(add)) return origin;
  1347. var keys = Object.keys(add);
  1348. var i = keys.length;
  1349. while (i--) {
  1350. origin[keys[i]] = add[keys[i]];
  1351. }
  1352. return origin;
  1353. };
  1354. function hasOwnProperty(obj, prop) {
  1355. return Object.prototype.hasOwnProperty.call(obj, prop);
  1356. }
  1357. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1358. },{"./support/isBuffer":26,"_process":312,"inherits":25}],28:[function(require,module,exports){
  1359. 'use strict'
  1360. exports.byteLength = byteLength
  1361. exports.toByteArray = toByteArray
  1362. exports.fromByteArray = fromByteArray
  1363. var lookup = []
  1364. var revLookup = []
  1365. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1366. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1367. for (var i = 0, len = code.length; i < len; ++i) {
  1368. lookup[i] = code[i]
  1369. revLookup[code.charCodeAt(i)] = i
  1370. }
  1371. // Support decoding URL-safe base64 strings, as Node.js does.
  1372. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  1373. revLookup['-'.charCodeAt(0)] = 62
  1374. revLookup['_'.charCodeAt(0)] = 63
  1375. function getLens (b64) {
  1376. var len = b64.length
  1377. if (len % 4 > 0) {
  1378. throw new Error('Invalid string. Length must be a multiple of 4')
  1379. }
  1380. // Trim off extra bytes after placeholder bytes are found
  1381. // See: https://github.com/beatgammit/base64-js/issues/42
  1382. var validLen = b64.indexOf('=')
  1383. if (validLen === -1) validLen = len
  1384. var placeHoldersLen = validLen === len
  1385. ? 0
  1386. : 4 - (validLen % 4)
  1387. return [validLen, placeHoldersLen]
  1388. }
  1389. // base64 is 4/3 + up to two characters of the original data
  1390. function byteLength (b64) {
  1391. var lens = getLens(b64)
  1392. var validLen = lens[0]
  1393. var placeHoldersLen = lens[1]
  1394. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1395. }
  1396. function _byteLength (b64, validLen, placeHoldersLen) {
  1397. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1398. }
  1399. function toByteArray (b64) {
  1400. var tmp
  1401. var lens = getLens(b64)
  1402. var validLen = lens[0]
  1403. var placeHoldersLen = lens[1]
  1404. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  1405. var curByte = 0
  1406. // if there are placeholders, only get up to the last complete 4 chars
  1407. var len = placeHoldersLen > 0
  1408. ? validLen - 4
  1409. : validLen
  1410. var i
  1411. for (i = 0; i < len; i += 4) {
  1412. tmp =
  1413. (revLookup[b64.charCodeAt(i)] << 18) |
  1414. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  1415. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  1416. revLookup[b64.charCodeAt(i + 3)]
  1417. arr[curByte++] = (tmp >> 16) & 0xFF
  1418. arr[curByte++] = (tmp >> 8) & 0xFF
  1419. arr[curByte++] = tmp & 0xFF
  1420. }
  1421. if (placeHoldersLen === 2) {
  1422. tmp =
  1423. (revLookup[b64.charCodeAt(i)] << 2) |
  1424. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1425. arr[curByte++] = tmp & 0xFF
  1426. }
  1427. if (placeHoldersLen === 1) {
  1428. tmp =
  1429. (revLookup[b64.charCodeAt(i)] << 10) |
  1430. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  1431. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1432. arr[curByte++] = (tmp >> 8) & 0xFF
  1433. arr[curByte++] = tmp & 0xFF
  1434. }
  1435. return arr
  1436. }
  1437. function tripletToBase64 (num) {
  1438. return lookup[num >> 18 & 0x3F] +
  1439. lookup[num >> 12 & 0x3F] +
  1440. lookup[num >> 6 & 0x3F] +
  1441. lookup[num & 0x3F]
  1442. }
  1443. function encodeChunk (uint8, start, end) {
  1444. var tmp
  1445. var output = []
  1446. for (var i = start; i < end; i += 3) {
  1447. tmp =
  1448. ((uint8[i] << 16) & 0xFF0000) +
  1449. ((uint8[i + 1] << 8) & 0xFF00) +
  1450. (uint8[i + 2] & 0xFF)
  1451. output.push(tripletToBase64(tmp))
  1452. }
  1453. return output.join('')
  1454. }
  1455. function fromByteArray (uint8) {
  1456. var tmp
  1457. var len = uint8.length
  1458. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1459. var parts = []
  1460. var maxChunkLength = 16383 // must be multiple of 3
  1461. // go through the array every three bytes, we'll deal with trailing stuff later
  1462. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1463. parts.push(encodeChunk(
  1464. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  1465. ))
  1466. }
  1467. // pad the end with zeros, but make sure to not forget the extra bytes
  1468. if (extraBytes === 1) {
  1469. tmp = uint8[len - 1]
  1470. parts.push(
  1471. lookup[tmp >> 2] +
  1472. lookup[(tmp << 4) & 0x3F] +
  1473. '=='
  1474. )
  1475. } else if (extraBytes === 2) {
  1476. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  1477. parts.push(
  1478. lookup[tmp >> 10] +
  1479. lookup[(tmp >> 4) & 0x3F] +
  1480. lookup[(tmp << 2) & 0x3F] +
  1481. '='
  1482. )
  1483. }
  1484. return parts.join('')
  1485. }
  1486. },{}],29:[function(require,module,exports){
  1487. /**
  1488. * @author shaozilee
  1489. *
  1490. * support 1bit 4bit 8bit 24bit decode
  1491. * encode with 24bit
  1492. *
  1493. */
  1494. var encode = require('./lib/encoder'),
  1495. decode = require('./lib/decoder');
  1496. module.exports = {
  1497. encode: encode,
  1498. decode: decode
  1499. };
  1500. },{"./lib/decoder":30,"./lib/encoder":31}],30:[function(require,module,exports){
  1501. (function (Buffer){
  1502. /**
  1503. * @author shaozilee
  1504. *
  1505. * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
  1506. *
  1507. */
  1508. function BmpDecoder(buffer,is_with_alpha) {
  1509. this.pos = 0;
  1510. this.buffer = buffer;
  1511. this.is_with_alpha = !!is_with_alpha;
  1512. this.bottom_up = true;
  1513. this.flag = this.buffer.toString("utf-8", 0, this.pos += 2);
  1514. if (this.flag != "BM") throw new Error("Invalid BMP File");
  1515. this.parseHeader();
  1516. this.parseRGBA();
  1517. }
  1518. BmpDecoder.prototype.parseHeader = function() {
  1519. this.fileSize = this.buffer.readUInt32LE(this.pos);
  1520. this.pos += 4;
  1521. this.reserved = this.buffer.readUInt32LE(this.pos);
  1522. this.pos += 4;
  1523. this.offset = this.buffer.readUInt32LE(this.pos);
  1524. this.pos += 4;
  1525. this.headerSize = this.buffer.readUInt32LE(this.pos);
  1526. this.pos += 4;
  1527. this.width = this.buffer.readUInt32LE(this.pos);
  1528. this.pos += 4;
  1529. this.height = this.buffer.readInt32LE(this.pos);
  1530. this.pos += 4;
  1531. this.planes = this.buffer.readUInt16LE(this.pos);
  1532. this.pos += 2;
  1533. this.bitPP = this.buffer.readUInt16LE(this.pos);
  1534. this.pos += 2;
  1535. this.compress = this.buffer.readUInt32LE(this.pos);
  1536. this.pos += 4;
  1537. this.rawSize = this.buffer.readUInt32LE(this.pos);
  1538. this.pos += 4;
  1539. this.hr = this.buffer.readUInt32LE(this.pos);
  1540. this.pos += 4;
  1541. this.vr = this.buffer.readUInt32LE(this.pos);
  1542. this.pos += 4;
  1543. this.colors = this.buffer.readUInt32LE(this.pos);
  1544. this.pos += 4;
  1545. this.importantColors = this.buffer.readUInt32LE(this.pos);
  1546. this.pos += 4;
  1547. if(this.bitPP === 16 && this.is_with_alpha){
  1548. this.bitPP = 15
  1549. }
  1550. if (this.bitPP < 15) {
  1551. var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
  1552. this.palette = new Array(len);
  1553. for (var i = 0; i < len; i++) {
  1554. var blue = this.buffer.readUInt8(this.pos++);
  1555. var green = this.buffer.readUInt8(this.pos++);
  1556. var red = this.buffer.readUInt8(this.pos++);
  1557. var quad = this.buffer.readUInt8(this.pos++);
  1558. this.palette[i] = {
  1559. red: red,
  1560. green: green,
  1561. blue: blue,
  1562. quad: quad
  1563. };
  1564. }
  1565. }
  1566. if(this.height < 0) {
  1567. this.height *= -1;
  1568. this.bottom_up = false;
  1569. }
  1570. }
  1571. BmpDecoder.prototype.parseRGBA = function() {
  1572. var bitn = "bit" + this.bitPP;
  1573. var len = this.width * this.height * 4;
  1574. this.data = new Buffer(len);
  1575. this[bitn]();
  1576. };
  1577. BmpDecoder.prototype.bit1 = function() {
  1578. var xlen = Math.ceil(this.width / 8);
  1579. var mode = xlen%4;
  1580. var y = this.height >= 0 ? this.height - 1 : -this.height
  1581. for (var y = this.height - 1; y >= 0; y--) {
  1582. var line = this.bottom_up ? y : this.height - 1 - y
  1583. for (var x = 0; x < xlen; x++) {
  1584. var b = this.buffer.readUInt8(this.pos++);
  1585. var location = line * this.width * 4 + x*8*4;
  1586. for (var i = 0; i < 8; i++) {
  1587. if(x*8+i<this.width){
  1588. var rgb = this.palette[((b>>(7-i))&0x1)];
  1589. this.data[location+i*4] = 0;
  1590. this.data[location+i*4 + 1] = rgb.blue;
  1591. this.data[location+i*4 + 2] = rgb.green;
  1592. this.data[location+i*4 + 3] = rgb.red;
  1593. }else{
  1594. break;
  1595. }
  1596. }
  1597. }
  1598. if (mode != 0){
  1599. this.pos+=(4 - mode);
  1600. }
  1601. }
  1602. };
  1603. BmpDecoder.prototype.bit4 = function() {
  1604. //RLE-4
  1605. if(this.compress == 2){
  1606. this.data.fill(0xff);
  1607. var location = 0;
  1608. var lines = this.bottom_up?this.height-1:0;
  1609. var low_nibble = false;//for all count of pixel
  1610. while(location<this.data.length){
  1611. var a = this.buffer.readUInt8(this.pos++);
  1612. var b = this.buffer.readUInt8(this.pos++);
  1613. //absolute mode
  1614. if(a == 0){
  1615. if(b == 0){//line end
  1616. if(this.bottom_up){
  1617. lines--;
  1618. }else{
  1619. lines++;
  1620. }
  1621. location = lines*this.width*4;
  1622. low_nibble = false;
  1623. continue;
  1624. }else if(b == 1){//image end
  1625. break;
  1626. }else if(b ==2){
  1627. //offset x,y
  1628. var x = this.buffer.readUInt8(this.pos++);
  1629. var y = this.buffer.readUInt8(this.pos++);
  1630. if(this.bottom_up){
  1631. lines-=y;
  1632. }else{
  1633. lines+=y;
  1634. }
  1635. location +=(y*this.width*4+x*4);
  1636. }else{
  1637. var c = this.buffer.readUInt8(this.pos++);
  1638. for(var i=0;i<b;i++){
  1639. if (low_nibble) {
  1640. setPixelData.call(this, (c & 0x0f));
  1641. } else {
  1642. setPixelData.call(this, (c & 0xf0)>>4);
  1643. }
  1644. if ((i & 1) && (i+1 < b)){
  1645. c = this.buffer.readUInt8(this.pos++);
  1646. }
  1647. low_nibble = !low_nibble;
  1648. }
  1649. if ((((b+1) >> 1) & 1 ) == 1){
  1650. this.pos++
  1651. }
  1652. }
  1653. }else{//encoded mode
  1654. for (var i = 0; i < a; i++) {
  1655. if (low_nibble) {
  1656. setPixelData.call(this, (b & 0x0f));
  1657. } else {
  1658. setPixelData.call(this, (b & 0xf0)>>4);
  1659. }
  1660. low_nibble = !low_nibble;
  1661. }
  1662. }
  1663. }
  1664. function setPixelData(rgbIndex){
  1665. var rgb = this.palette[rgbIndex];
  1666. this.data[location] = 0;
  1667. this.data[location + 1] = rgb.blue;
  1668. this.data[location + 2] = rgb.green;
  1669. this.data[location + 3] = rgb.red;
  1670. location+=4;
  1671. }
  1672. }else{
  1673. var xlen = Math.ceil(this.width/2);
  1674. var mode = xlen%4;
  1675. for (var y = this.height - 1; y >= 0; y--) {
  1676. var line = this.bottom_up ? y : this.height - 1 - y
  1677. for (var x = 0; x < xlen; x++) {
  1678. var b = this.buffer.readUInt8(this.pos++);
  1679. var location = line * this.width * 4 + x*2*4;
  1680. var before = b>>4;
  1681. var after = b&0x0F;
  1682. var rgb = this.palette[before];
  1683. this.data[location] = 0;
  1684. this.data[location + 1] = rgb.blue;
  1685. this.data[location + 2] = rgb.green;
  1686. this.data[location + 3] = rgb.red;
  1687. if(x*2+1>=this.width)break;
  1688. rgb = this.palette[after];
  1689. this.data[location+4] = 0;
  1690. this.data[location+4 + 1] = rgb.blue;
  1691. this.data[location+4 + 2] = rgb.green;
  1692. this.data[location+4 + 3] = rgb.red;
  1693. }
  1694. if (mode != 0){
  1695. this.pos+=(4 - mode);
  1696. }
  1697. }
  1698. }
  1699. };
  1700. BmpDecoder.prototype.bit8 = function() {
  1701. //RLE-8
  1702. if(this.compress == 1){
  1703. this.data.fill(0xff);
  1704. var location = 0;
  1705. var lines = this.bottom_up?this.height-1:0;
  1706. while(location<this.data.length){
  1707. var a = this.buffer.readUInt8(this.pos++);
  1708. var b = this.buffer.readUInt8(this.pos++);
  1709. //absolute mode
  1710. if(a == 0){
  1711. if(b == 0){//line end
  1712. if(this.bottom_up){
  1713. lines--;
  1714. }else{
  1715. lines++;
  1716. }
  1717. location = lines*this.width*4;
  1718. continue;
  1719. }else if(b == 1){//image end
  1720. break;
  1721. }else if(b ==2){
  1722. //offset x,y
  1723. var x = this.buffer.readUInt8(this.pos++);
  1724. var y = this.buffer.readUInt8(this.pos++);
  1725. if(this.bottom_up){
  1726. lines-=y;
  1727. }else{
  1728. lines+=y;
  1729. }
  1730. location +=(y*this.width*4+x*4);
  1731. }else{
  1732. for(var i=0;i<b;i++){
  1733. var c = this.buffer.readUInt8(this.pos++);
  1734. setPixelData.call(this, c);
  1735. }
  1736. if(b&1 == 1){
  1737. this.pos++;
  1738. }
  1739. }
  1740. }else{//encoded mode
  1741. for (var i = 0; i < a; i++) {
  1742. setPixelData.call(this, b);
  1743. }
  1744. }
  1745. }
  1746. function setPixelData(rgbIndex){
  1747. var rgb = this.palette[rgbIndex];
  1748. this.data[location] = 0;
  1749. this.data[location + 1] = rgb.blue;
  1750. this.data[location + 2] = rgb.green;
  1751. this.data[location + 3] = rgb.red;
  1752. location+=4;
  1753. }
  1754. }else {
  1755. var mode = this.width % 4;
  1756. for (var y = this.height - 1; y >= 0; y--) {
  1757. var line = this.bottom_up ? y : this.height - 1 - y
  1758. for (var x = 0; x < this.width; x++) {
  1759. var b = this.buffer.readUInt8(this.pos++);
  1760. var location = line * this.width * 4 + x * 4;
  1761. if (b < this.palette.length) {
  1762. var rgb = this.palette[b];
  1763. this.data[location] = 0;
  1764. this.data[location + 1] = rgb.blue;
  1765. this.data[location + 2] = rgb.green;
  1766. this.data[location + 3] = rgb.red;
  1767. } else {
  1768. this.data[location] = 0;
  1769. this.data[location + 1] = 0xFF;
  1770. this.data[location + 2] = 0xFF;
  1771. this.data[location + 3] = 0xFF;
  1772. }
  1773. }
  1774. if (mode != 0) {
  1775. this.pos += (4 - mode);
  1776. }
  1777. }
  1778. }
  1779. };
  1780. BmpDecoder.prototype.bit15 = function() {
  1781. var dif_w =this.width % 3;
  1782. var _11111 = parseInt("11111", 2),_1_5 = _11111;
  1783. for (var y = this.height - 1; y >= 0; y--) {
  1784. var line = this.bottom_up ? y : this.height - 1 - y
  1785. for (var x = 0; x < this.width; x++) {
  1786. var B = this.buffer.readUInt16LE(this.pos);
  1787. this.pos+=2;
  1788. var blue = (B & _1_5) / _1_5 * 255 | 0;
  1789. var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0;
  1790. var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
  1791. var alpha = (B>>15)?0xFF:0x00;
  1792. var location = line * this.width * 4 + x * 4;
  1793. this.data[location] = alpha;
  1794. this.data[location + 1] = blue;
  1795. this.data[location + 2] = green;
  1796. this.data[location + 3] = red;
  1797. }
  1798. //skip extra bytes
  1799. this.pos += dif_w;
  1800. }
  1801. };
  1802. BmpDecoder.prototype.bit16 = function() {
  1803. var dif_w =(this.width % 2)*2;
  1804. //default xrgb555
  1805. this.maskRed = 0x7C00;
  1806. this.maskGreen = 0x3E0;
  1807. this.maskBlue =0x1F;
  1808. this.mask0 = 0;
  1809. if(this.compress == 3){
  1810. this.maskRed = this.buffer.readUInt32LE(this.pos);
  1811. this.pos+=4;
  1812. this.maskGreen = this.buffer.readUInt32LE(this.pos);
  1813. this.pos+=4;
  1814. this.maskBlue = this.buffer.readUInt32LE(this.pos);
  1815. this.pos+=4;
  1816. this.mask0 = this.buffer.readUInt32LE(this.pos);
  1817. this.pos+=4;
  1818. }
  1819. var ns=[0,0,0];
  1820. for (var i=0;i<16;i++){
  1821. if ((this.maskRed>>i)&0x01) ns[0]++;
  1822. if ((this.maskGreen>>i)&0x01) ns[1]++;
  1823. if ((this.maskBlue>>i)&0x01) ns[2]++;
  1824. }
  1825. ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;
  1826. for (var y = this.height - 1; y >= 0; y--) {
  1827. var line = this.bottom_up ? y : this.height - 1 - y;
  1828. for (var x = 0; x < this.width; x++) {
  1829. var B = this.buffer.readUInt16LE(this.pos);
  1830. this.pos+=2;
  1831. var blue = (B&this.maskBlue)<<ns[0];
  1832. var green = (B&this.maskGreen)>>ns[1];
  1833. var red = (B&this.maskRed)>>ns[2];
  1834. var location = line * this.width * 4 + x * 4;
  1835. this.data[location] = 0;
  1836. this.data[location + 1] = blue;
  1837. this.data[location + 2] = green;
  1838. this.data[location + 3] = red;
  1839. }
  1840. //skip extra bytes
  1841. this.pos += dif_w;
  1842. }
  1843. };
  1844. BmpDecoder.prototype.bit24 = function() {
  1845. for (var y = this.height - 1; y >= 0; y--) {
  1846. var line = this.bottom_up ? y : this.height - 1 - y
  1847. for (var x = 0; x < this.width; x++) {
  1848. //Little Endian rgb
  1849. var blue = this.buffer.readUInt8(this.pos++);
  1850. var green = this.buffer.readUInt8(this.pos++);
  1851. var red = this.buffer.readUInt8(this.pos++);
  1852. var location = line * this.width * 4 + x * 4;
  1853. this.data[location] = 0;
  1854. this.data[location + 1] = blue;
  1855. this.data[location + 2] = green;
  1856. this.data[location + 3] = red;
  1857. }
  1858. //skip extra bytes
  1859. this.pos += (this.width % 4);
  1860. }
  1861. };
  1862. /**
  1863. * add 32bit decode func
  1864. * @author soubok
  1865. */
  1866. BmpDecoder.prototype.bit32 = function() {
  1867. //BI_BITFIELDS
  1868. if(this.compress == 3){
  1869. this.maskRed = this.buffer.readUInt32LE(this.pos);
  1870. this.pos+=4;
  1871. this.maskGreen = this.buffer.readUInt32LE(this.pos);
  1872. this.pos+=4;
  1873. this.maskBlue = this.buffer.readUInt32LE(this.pos);
  1874. this.pos+=4;
  1875. this.mask0 = this.buffer.readUInt32LE(this.pos);
  1876. this.pos+=4;
  1877. for (var y = this.height - 1; y >= 0; y--) {
  1878. var line = this.bottom_up ? y : this.height - 1 - y;
  1879. for (var x = 0; x < this.width; x++) {
  1880. //Little Endian rgba
  1881. var alpha = this.buffer.readUInt8(this.pos++);
  1882. var blue = this.buffer.readUInt8(this.pos++);
  1883. var green = this.buffer.readUInt8(this.pos++);
  1884. var red = this.buffer.readUInt8(this.pos++);
  1885. var location = line * this.width * 4 + x * 4;
  1886. this.data[location] = alpha;
  1887. this.data[location + 1] = blue;
  1888. this.data[location + 2] = green;
  1889. this.data[location + 3] = red;
  1890. }
  1891. }
  1892. }else{
  1893. for (var y = this.height - 1; y >= 0; y--) {
  1894. var line = this.bottom_up ? y : this.height - 1 - y;
  1895. for (var x = 0; x < this.width; x++) {
  1896. //Little Endian argb
  1897. var blue = this.buffer.readUInt8(this.pos++);
  1898. var green = this.buffer.readUInt8(this.pos++);
  1899. var red = this.buffer.readUInt8(this.pos++);
  1900. var alpha = this.buffer.readUInt8(this.pos++);
  1901. var location = line * this.width * 4 + x * 4;
  1902. this.data[location] = alpha;
  1903. this.data[location + 1] = blue;
  1904. this.data[location + 2] = green;
  1905. this.data[location + 3] = red;
  1906. }
  1907. }
  1908. }
  1909. };
  1910. BmpDecoder.prototype.getData = function() {
  1911. return this.data;
  1912. };
  1913. module.exports = function(bmpData) {
  1914. var decoder = new BmpDecoder(bmpData);
  1915. return decoder;
  1916. };
  1917. }).call(this,require("buffer").Buffer)
  1918. },{"buffer":47}],31:[function(require,module,exports){
  1919. (function (Buffer){
  1920. /**
  1921. * @author shaozilee
  1922. *
  1923. * BMP format encoder,encode 24bit BMP
  1924. * Not support quality compression
  1925. *
  1926. */
  1927. function BmpEncoder(imgData){
  1928. this.buffer = imgData.data;
  1929. this.width = imgData.width;
  1930. this.height = imgData.height;
  1931. this.extraBytes = this.width%4;
  1932. this.rgbSize = this.height*(3*this.width+this.extraBytes);
  1933. this.headerInfoSize = 40;
  1934. this.data = [];
  1935. /******************header***********************/
  1936. this.flag = "BM";
  1937. this.reserved = 0;
  1938. this.offset = 54;
  1939. this.fileSize = this.rgbSize+this.offset;
  1940. this.planes = 1;
  1941. this.bitPP = 24;
  1942. this.compress = 0;
  1943. this.hr = 0;
  1944. this.vr = 0;
  1945. this.colors = 0;
  1946. this.importantColors = 0;
  1947. }
  1948. BmpEncoder.prototype.encode = function() {
  1949. var tempBuffer = new Buffer(this.offset+this.rgbSize);
  1950. this.pos = 0;
  1951. tempBuffer.write(this.flag,this.pos,2);this.pos+=2;
  1952. tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;
  1953. tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;
  1954. tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;
  1955. tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;
  1956. tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;
  1957. tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;
  1958. tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;
  1959. tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;
  1960. tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;
  1961. tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;
  1962. tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;
  1963. tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;
  1964. tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;
  1965. tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;
  1966. var i=0;
  1967. var rowBytes = 3*this.width+this.extraBytes;
  1968. for (var y = 0; y <this.height; y++){
  1969. for (var x = 0; x < this.width; x++){
  1970. var p = this.pos+y*rowBytes+x*3;
  1971. i++;//a
  1972. tempBuffer[p]= this.buffer[i++];//b
  1973. tempBuffer[p+1] = this.buffer[i++];//g
  1974. tempBuffer[p+2] = this.buffer[i++];//r
  1975. }
  1976. if(this.extraBytes>0){
  1977. var fillOffset = this.pos+y*rowBytes+this.width*3;
  1978. tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);
  1979. }
  1980. }
  1981. return tempBuffer;
  1982. };
  1983. module.exports = function(imgData, quality) {
  1984. if (typeof quality === 'undefined') quality = 100;
  1985. var encoder = new BmpEncoder(imgData);
  1986. var data = encoder.encode();
  1987. return {
  1988. data: data,
  1989. width: imgData.width,
  1990. height: imgData.height
  1991. };
  1992. };
  1993. }).call(this,require("buffer").Buffer)
  1994. },{"buffer":47}],32:[function(require,module,exports){
  1995. },{}],33:[function(require,module,exports){
  1996. (function (process,Buffer){
  1997. 'use strict';
  1998. /* eslint camelcase: "off" */
  1999. var assert = require('assert');
  2000. var Zstream = require('pako/lib/zlib/zstream');
  2001. var zlib_deflate = require('pako/lib/zlib/deflate.js');
  2002. var zlib_inflate = require('pako/lib/zlib/inflate.js');
  2003. var constants = require('pako/lib/zlib/constants');
  2004. for (var key in constants) {
  2005. exports[key] = constants[key];
  2006. }
  2007. // zlib modes
  2008. exports.NONE = 0;
  2009. exports.DEFLATE = 1;
  2010. exports.INFLATE = 2;
  2011. exports.GZIP = 3;
  2012. exports.GUNZIP = 4;
  2013. exports.DEFLATERAW = 5;
  2014. exports.INFLATERAW = 6;
  2015. exports.UNZIP = 7;
  2016. var GZIP_HEADER_ID1 = 0x1f;
  2017. var GZIP_HEADER_ID2 = 0x8b;
  2018. /**
  2019. * Emulate Node's zlib C++ layer for use by the JS layer in index.js
  2020. */
  2021. function Zlib(mode) {
  2022. if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
  2023. throw new TypeError('Bad argument');
  2024. }
  2025. this.dictionary = null;
  2026. this.err = 0;
  2027. this.flush = 0;
  2028. this.init_done = false;
  2029. this.level = 0;
  2030. this.memLevel = 0;
  2031. this.mode = mode;
  2032. this.strategy = 0;
  2033. this.windowBits = 0;
  2034. this.write_in_progress = false;
  2035. this.pending_close = false;
  2036. this.gzip_id_bytes_read = 0;
  2037. }
  2038. Zlib.prototype.close = function () {
  2039. if (this.write_in_progress) {
  2040. this.pending_close = true;
  2041. return;
  2042. }
  2043. this.pending_close = false;
  2044. assert(this.init_done, 'close before init');
  2045. assert(this.mode <= exports.UNZIP);
  2046. if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
  2047. zlib_deflate.deflateEnd(this.strm);
  2048. } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
  2049. zlib_inflate.inflateEnd(this.strm);
  2050. }
  2051. this.mode = exports.NONE;
  2052. this.dictionary = null;
  2053. };
  2054. Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  2055. return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
  2056. };
  2057. Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  2058. return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
  2059. };
  2060. Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  2061. assert.equal(arguments.length, 8);
  2062. assert(this.init_done, 'write before init');
  2063. assert(this.mode !== exports.NONE, 'already finalized');
  2064. assert.equal(false, this.write_in_progress, 'write already in progress');
  2065. assert.equal(false, this.pending_close, 'close is pending');
  2066. this.write_in_progress = true;
  2067. assert.equal(false, flush === undefined, 'must provide flush value');
  2068. this.write_in_progress = true;
  2069. if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
  2070. throw new Error('Invalid flush value');
  2071. }
  2072. if (input == null) {
  2073. input = Buffer.alloc(0);
  2074. in_len = 0;
  2075. in_off = 0;
  2076. }
  2077. this.strm.avail_in = in_len;
  2078. this.strm.input = input;
  2079. this.strm.next_in = in_off;
  2080. this.strm.avail_out = out_len;
  2081. this.strm.output = out;
  2082. this.strm.next_out = out_off;
  2083. this.flush = flush;
  2084. if (!async) {
  2085. // sync version
  2086. this._process();
  2087. if (this._checkError()) {
  2088. return this._afterSync();
  2089. }
  2090. return;
  2091. }
  2092. // async version
  2093. var self = this;
  2094. process.nextTick(function () {
  2095. self._process();
  2096. self._after();
  2097. });
  2098. return this;
  2099. };
  2100. Zlib.prototype._afterSync = function () {
  2101. var avail_out = this.strm.avail_out;
  2102. var avail_in = this.strm.avail_in;
  2103. this.write_in_progress = false;
  2104. return [avail_in, avail_out];
  2105. };
  2106. Zlib.prototype._process = function () {
  2107. var next_expected_header_byte = null;
  2108. // If the avail_out is left at 0, then it means that it ran out
  2109. // of room. If there was avail_out left over, then it means
  2110. // that all of the input was consumed.
  2111. switch (this.mode) {
  2112. case exports.DEFLATE:
  2113. case exports.GZIP:
  2114. case exports.DEFLATERAW:
  2115. this.err = zlib_deflate.deflate(this.strm, this.flush);
  2116. break;
  2117. case exports.UNZIP:
  2118. if (this.strm.avail_in > 0) {
  2119. next_expected_header_byte = this.strm.next_in;
  2120. }
  2121. switch (this.gzip_id_bytes_read) {
  2122. case 0:
  2123. if (next_expected_header_byte === null) {
  2124. break;
  2125. }
  2126. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
  2127. this.gzip_id_bytes_read = 1;
  2128. next_expected_header_byte++;
  2129. if (this.strm.avail_in === 1) {
  2130. // The only available byte was already read.
  2131. break;
  2132. }
  2133. } else {
  2134. this.mode = exports.INFLATE;
  2135. break;
  2136. }
  2137. // fallthrough
  2138. case 1:
  2139. if (next_expected_header_byte === null) {
  2140. break;
  2141. }
  2142. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
  2143. this.gzip_id_bytes_read = 2;
  2144. this.mode = exports.GUNZIP;
  2145. } else {
  2146. // There is no actual difference between INFLATE and INFLATERAW
  2147. // (after initialization).
  2148. this.mode = exports.INFLATE;
  2149. }
  2150. break;
  2151. default:
  2152. throw new Error('invalid number of gzip magic number bytes read');
  2153. }
  2154. // fallthrough
  2155. case exports.INFLATE:
  2156. case exports.GUNZIP:
  2157. case exports.INFLATERAW:
  2158. this.err = zlib_inflate.inflate(this.strm, this.flush
  2159. // If data was encoded with dictionary
  2160. );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
  2161. // Load it
  2162. this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
  2163. if (this.err === exports.Z_OK) {
  2164. // And try to decode again
  2165. this.err = zlib_inflate.inflate(this.strm, this.flush);
  2166. } else if (this.err === exports.Z_DATA_ERROR) {
  2167. // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
  2168. // Make it possible for After() to tell a bad dictionary from bad
  2169. // input.
  2170. this.err = exports.Z_NEED_DICT;
  2171. }
  2172. }
  2173. while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
  2174. // Bytes remain in input buffer. Perhaps this is another compressed
  2175. // member in the same archive, or just trailing garbage.
  2176. // Trailing zero bytes are okay, though, since they are frequently
  2177. // used for padding.
  2178. this.reset();
  2179. this.err = zlib_inflate.inflate(this.strm, this.flush);
  2180. }
  2181. break;
  2182. default:
  2183. throw new Error('Unknown mode ' + this.mode);
  2184. }
  2185. };
  2186. Zlib.prototype._checkError = function () {
  2187. // Acceptable error states depend on the type of zlib stream.
  2188. switch (this.err) {
  2189. case exports.Z_OK:
  2190. case exports.Z_BUF_ERROR:
  2191. if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
  2192. this._error('unexpected end of file');
  2193. return false;
  2194. }
  2195. break;
  2196. case exports.Z_STREAM_END:
  2197. // normal statuses, not fatal
  2198. break;
  2199. case exports.Z_NEED_DICT:
  2200. if (this.dictionary == null) {
  2201. this._error('Missing dictionary');
  2202. } else {
  2203. this._error('Bad dictionary');
  2204. }
  2205. return false;
  2206. default:
  2207. // something else.
  2208. this._error('Zlib error');
  2209. return false;
  2210. }
  2211. return true;
  2212. };
  2213. Zlib.prototype._after = function () {
  2214. if (!this._checkError()) {
  2215. return;
  2216. }
  2217. var avail_out = this.strm.avail_out;
  2218. var avail_in = this.strm.avail_in;
  2219. this.write_in_progress = false;
  2220. // call the write() cb
  2221. this.callback(avail_in, avail_out);
  2222. if (this.pending_close) {
  2223. this.close();
  2224. }
  2225. };
  2226. Zlib.prototype._error = function (message) {
  2227. if (this.strm.msg) {
  2228. message = this.strm.msg;
  2229. }
  2230. this.onerror(message, this.err
  2231. // no hope of rescue.
  2232. );this.write_in_progress = false;
  2233. if (this.pending_close) {
  2234. this.close();
  2235. }
  2236. };
  2237. Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  2238. assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
  2239. assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  2240. assert(level >= -1 && level <= 9, 'invalid compression level');
  2241. assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
  2242. assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
  2243. this._init(level, windowBits, memLevel, strategy, dictionary);
  2244. this._setDictionary();
  2245. };
  2246. Zlib.prototype.params = function () {
  2247. throw new Error('deflateParams Not supported');
  2248. };
  2249. Zlib.prototype.reset = function () {
  2250. this._reset();
  2251. this._setDictionary();
  2252. };
  2253. Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  2254. this.level = level;
  2255. this.windowBits = windowBits;
  2256. this.memLevel = memLevel;
  2257. this.strategy = strategy;
  2258. this.flush = exports.Z_NO_FLUSH;
  2259. this.err = exports.Z_OK;
  2260. if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
  2261. this.windowBits += 16;
  2262. }
  2263. if (this.mode === exports.UNZIP) {
  2264. this.windowBits += 32;
  2265. }
  2266. if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
  2267. this.windowBits = -1 * this.windowBits;
  2268. }
  2269. this.strm = new Zstream();
  2270. switch (this.mode) {
  2271. case exports.DEFLATE:
  2272. case exports.GZIP:
  2273. case exports.DEFLATERAW:
  2274. this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
  2275. break;
  2276. case exports.INFLATE:
  2277. case exports.GUNZIP:
  2278. case exports.INFLATERAW:
  2279. case exports.UNZIP:
  2280. this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
  2281. break;
  2282. default:
  2283. throw new Error('Unknown mode ' + this.mode);
  2284. }
  2285. if (this.err !== exports.Z_OK) {
  2286. this._error('Init error');
  2287. }
  2288. this.dictionary = dictionary;
  2289. this.write_in_progress = false;
  2290. this.init_done = true;
  2291. };
  2292. Zlib.prototype._setDictionary = function () {
  2293. if (this.dictionary == null) {
  2294. return;
  2295. }
  2296. this.err = exports.Z_OK;
  2297. switch (this.mode) {
  2298. case exports.DEFLATE:
  2299. case exports.DEFLATERAW:
  2300. this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
  2301. break;
  2302. default:
  2303. break;
  2304. }
  2305. if (this.err !== exports.Z_OK) {
  2306. this._error('Failed to set dictionary');
  2307. }
  2308. };
  2309. Zlib.prototype._reset = function () {
  2310. this.err = exports.Z_OK;
  2311. switch (this.mode) {
  2312. case exports.DEFLATE:
  2313. case exports.DEFLATERAW:
  2314. case exports.GZIP:
  2315. this.err = zlib_deflate.deflateReset(this.strm);
  2316. break;
  2317. case exports.INFLATE:
  2318. case exports.INFLATERAW:
  2319. case exports.GUNZIP:
  2320. this.err = zlib_inflate.inflateReset(this.strm);
  2321. break;
  2322. default:
  2323. break;
  2324. }
  2325. if (this.err !== exports.Z_OK) {
  2326. this._error('Failed to reset stream');
  2327. }
  2328. };
  2329. exports.Zlib = Zlib;
  2330. }).call(this,require('_process'),require("buffer").Buffer)
  2331. },{"_process":312,"assert":24,"buffer":47,"pako/lib/zlib/constants":37,"pako/lib/zlib/deflate.js":39,"pako/lib/zlib/inflate.js":41,"pako/lib/zlib/zstream":45}],34:[function(require,module,exports){
  2332. (function (process){
  2333. 'use strict';
  2334. var Buffer = require('buffer').Buffer;
  2335. var Transform = require('stream').Transform;
  2336. var binding = require('./binding');
  2337. var util = require('util');
  2338. var assert = require('assert').ok;
  2339. var kMaxLength = require('buffer').kMaxLength;
  2340. var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
  2341. // zlib doesn't provide these, so kludge them in following the same
  2342. // const naming scheme zlib uses.
  2343. binding.Z_MIN_WINDOWBITS = 8;
  2344. binding.Z_MAX_WINDOWBITS = 15;
  2345. binding.Z_DEFAULT_WINDOWBITS = 15;
  2346. // fewer than 64 bytes per chunk is stupid.
  2347. // technically it could work with as few as 8, but even 64 bytes
  2348. // is absurdly low. Usually a MB or more is best.
  2349. binding.Z_MIN_CHUNK = 64;
  2350. binding.Z_MAX_CHUNK = Infinity;
  2351. binding.Z_DEFAULT_CHUNK = 16 * 1024;
  2352. binding.Z_MIN_MEMLEVEL = 1;
  2353. binding.Z_MAX_MEMLEVEL = 9;
  2354. binding.Z_DEFAULT_MEMLEVEL = 8;
  2355. binding.Z_MIN_LEVEL = -1;
  2356. binding.Z_MAX_LEVEL = 9;
  2357. binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
  2358. // expose all the zlib constants
  2359. var bkeys = Object.keys(binding);
  2360. for (var bk = 0; bk < bkeys.length; bk++) {
  2361. var bkey = bkeys[bk];
  2362. if (bkey.match(/^Z/)) {
  2363. Object.defineProperty(exports, bkey, {
  2364. enumerable: true, value: binding[bkey], writable: false
  2365. });
  2366. }
  2367. }
  2368. // translation table for return codes.
  2369. var codes = {
  2370. Z_OK: binding.Z_OK,
  2371. Z_STREAM_END: binding.Z_STREAM_END,
  2372. Z_NEED_DICT: binding.Z_NEED_DICT,
  2373. Z_ERRNO: binding.Z_ERRNO,
  2374. Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  2375. Z_DATA_ERROR: binding.Z_DATA_ERROR,
  2376. Z_MEM_ERROR: binding.Z_MEM_ERROR,
  2377. Z_BUF_ERROR: binding.Z_BUF_ERROR,
  2378. Z_VERSION_ERROR: binding.Z_VERSION_ERROR
  2379. };
  2380. var ckeys = Object.keys(codes);
  2381. for (var ck = 0; ck < ckeys.length; ck++) {
  2382. var ckey = ckeys[ck];
  2383. codes[codes[ckey]] = ckey;
  2384. }
  2385. Object.defineProperty(exports, 'codes', {
  2386. enumerable: true, value: Object.freeze(codes), writable: false
  2387. });
  2388. exports.Deflate = Deflate;
  2389. exports.Inflate = Inflate;
  2390. exports.Gzip = Gzip;
  2391. exports.Gunzip = Gunzip;
  2392. exports.DeflateRaw = DeflateRaw;
  2393. exports.InflateRaw = InflateRaw;
  2394. exports.Unzip = Unzip;
  2395. exports.createDeflate = function (o) {
  2396. return new Deflate(o);
  2397. };
  2398. exports.createInflate = function (o) {
  2399. return new Inflate(o);
  2400. };
  2401. exports.createDeflateRaw = function (o) {
  2402. return new DeflateRaw(o);
  2403. };
  2404. exports.createInflateRaw = function (o) {
  2405. return new InflateRaw(o);
  2406. };
  2407. exports.createGzip = function (o) {
  2408. return new Gzip(o);
  2409. };
  2410. exports.createGunzip = function (o) {
  2411. return new Gunzip(o);
  2412. };
  2413. exports.createUnzip = function (o) {
  2414. return new Unzip(o);
  2415. };
  2416. // Convenience methods.
  2417. // compress/decompress a string or buffer in one step.
  2418. exports.deflate = function (buffer, opts, callback) {
  2419. if (typeof opts === 'function') {
  2420. callback = opts;
  2421. opts = {};
  2422. }
  2423. return zlibBuffer(new Deflate(opts), buffer, callback);
  2424. };
  2425. exports.deflateSync = function (buffer, opts) {
  2426. return zlibBufferSync(new Deflate(opts), buffer);
  2427. };
  2428. exports.gzip = function (buffer, opts, callback) {
  2429. if (typeof opts === 'function') {
  2430. callback = opts;
  2431. opts = {};
  2432. }
  2433. return zlibBuffer(new Gzip(opts), buffer, callback);
  2434. };
  2435. exports.gzipSync = function (buffer, opts) {
  2436. return zlibBufferSync(new Gzip(opts), buffer);
  2437. };
  2438. exports.deflateRaw = function (buffer, opts, callback) {
  2439. if (typeof opts === 'function') {
  2440. callback = opts;
  2441. opts = {};
  2442. }
  2443. return zlibBuffer(new DeflateRaw(opts), buffer, callback);
  2444. };
  2445. exports.deflateRawSync = function (buffer, opts) {
  2446. return zlibBufferSync(new DeflateRaw(opts), buffer);
  2447. };
  2448. exports.unzip = function (buffer, opts, callback) {
  2449. if (typeof opts === 'function') {
  2450. callback = opts;
  2451. opts = {};
  2452. }
  2453. return zlibBuffer(new Unzip(opts), buffer, callback);
  2454. };
  2455. exports.unzipSync = function (buffer, opts) {
  2456. return zlibBufferSync(new Unzip(opts), buffer);
  2457. };
  2458. exports.inflate = function (buffer, opts, callback) {
  2459. if (typeof opts === 'function') {
  2460. callback = opts;
  2461. opts = {};
  2462. }
  2463. return zlibBuffer(new Inflate(opts), buffer, callback);
  2464. };
  2465. exports.inflateSync = function (buffer, opts) {
  2466. return zlibBufferSync(new Inflate(opts), buffer);
  2467. };
  2468. exports.gunzip = function (buffer, opts, callback) {
  2469. if (typeof opts === 'function') {
  2470. callback = opts;
  2471. opts = {};
  2472. }
  2473. return zlibBuffer(new Gunzip(opts), buffer, callback);
  2474. };
  2475. exports.gunzipSync = function (buffer, opts) {
  2476. return zlibBufferSync(new Gunzip(opts), buffer);
  2477. };
  2478. exports.inflateRaw = function (buffer, opts, callback) {
  2479. if (typeof opts === 'function') {
  2480. callback = opts;
  2481. opts = {};
  2482. }
  2483. return zlibBuffer(new InflateRaw(opts), buffer, callback);
  2484. };
  2485. exports.inflateRawSync = function (buffer, opts) {
  2486. return zlibBufferSync(new InflateRaw(opts), buffer);
  2487. };
  2488. function zlibBuffer(engine, buffer, callback) {
  2489. var buffers = [];
  2490. var nread = 0;
  2491. engine.on('error', onError);
  2492. engine.on('end', onEnd);
  2493. engine.end(buffer);
  2494. flow();
  2495. function flow() {
  2496. var chunk;
  2497. while (null !== (chunk = engine.read())) {
  2498. buffers.push(chunk);
  2499. nread += chunk.length;
  2500. }
  2501. engine.once('readable', flow);
  2502. }
  2503. function onError(err) {
  2504. engine.removeListener('end', onEnd);
  2505. engine.removeListener('readable', flow);
  2506. callback(err);
  2507. }
  2508. function onEnd() {
  2509. var buf;
  2510. var err = null;
  2511. if (nread >= kMaxLength) {
  2512. err = new RangeError(kRangeErrorMessage);
  2513. } else {
  2514. buf = Buffer.concat(buffers, nread);
  2515. }
  2516. buffers = [];
  2517. engine.close();
  2518. callback(err, buf);
  2519. }
  2520. }
  2521. function zlibBufferSync(engine, buffer) {
  2522. if (typeof buffer === 'string') buffer = Buffer.from(buffer);
  2523. if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
  2524. var flushFlag = engine._finishFlushFlag;
  2525. return engine._processChunk(buffer, flushFlag);
  2526. }
  2527. // generic zlib
  2528. // minimal 2-byte header
  2529. function Deflate(opts) {
  2530. if (!(this instanceof Deflate)) return new Deflate(opts);
  2531. Zlib.call(this, opts, binding.DEFLATE);
  2532. }
  2533. function Inflate(opts) {
  2534. if (!(this instanceof Inflate)) return new Inflate(opts);
  2535. Zlib.call(this, opts, binding.INFLATE);
  2536. }
  2537. // gzip - bigger header, same deflate compression
  2538. function Gzip(opts) {
  2539. if (!(this instanceof Gzip)) return new Gzip(opts);
  2540. Zlib.call(this, opts, binding.GZIP);
  2541. }
  2542. function Gunzip(opts) {
  2543. if (!(this instanceof Gunzip)) return new Gunzip(opts);
  2544. Zlib.call(this, opts, binding.GUNZIP);
  2545. }
  2546. // raw - no header
  2547. function DeflateRaw(opts) {
  2548. if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  2549. Zlib.call(this, opts, binding.DEFLATERAW);
  2550. }
  2551. function InflateRaw(opts) {
  2552. if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  2553. Zlib.call(this, opts, binding.INFLATERAW);
  2554. }
  2555. // auto-detect header.
  2556. function Unzip(opts) {
  2557. if (!(this instanceof Unzip)) return new Unzip(opts);
  2558. Zlib.call(this, opts, binding.UNZIP);
  2559. }
  2560. function isValidFlushFlag(flag) {
  2561. return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
  2562. }
  2563. // the Zlib class they all inherit from
  2564. // This thing manages the queue of requests, and returns
  2565. // true or false if there is anything in the queue when
  2566. // you call the .write() method.
  2567. function Zlib(opts, mode) {
  2568. var _this = this;
  2569. this._opts = opts = opts || {};
  2570. this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
  2571. Transform.call(this, opts);
  2572. if (opts.flush && !isValidFlushFlag(opts.flush)) {
  2573. throw new Error('Invalid flush flag: ' + opts.flush);
  2574. }
  2575. if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
  2576. throw new Error('Invalid flush flag: ' + opts.finishFlush);
  2577. }
  2578. this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  2579. this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
  2580. if (opts.chunkSize) {
  2581. if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
  2582. throw new Error('Invalid chunk size: ' + opts.chunkSize);
  2583. }
  2584. }
  2585. if (opts.windowBits) {
  2586. if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
  2587. throw new Error('Invalid windowBits: ' + opts.windowBits);
  2588. }
  2589. }
  2590. if (opts.level) {
  2591. if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
  2592. throw new Error('Invalid compression level: ' + opts.level);
  2593. }
  2594. }
  2595. if (opts.memLevel) {
  2596. if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
  2597. throw new Error('Invalid memLevel: ' + opts.memLevel);
  2598. }
  2599. }
  2600. if (opts.strategy) {
  2601. if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
  2602. throw new Error('Invalid strategy: ' + opts.strategy);
  2603. }
  2604. }
  2605. if (opts.dictionary) {
  2606. if (!Buffer.isBuffer(opts.dictionary)) {
  2607. throw new Error('Invalid dictionary: it should be a Buffer instance');
  2608. }
  2609. }
  2610. this._handle = new binding.Zlib(mode);
  2611. var self = this;
  2612. this._hadError = false;
  2613. this._handle.onerror = function (message, errno) {
  2614. // there is no way to cleanly recover.
  2615. // continuing only obscures problems.
  2616. _close(self);
  2617. self._hadError = true;
  2618. var error = new Error(message);
  2619. error.errno = errno;
  2620. error.code = exports.codes[errno];
  2621. self.emit('error', error);
  2622. };
  2623. var level = exports.Z_DEFAULT_COMPRESSION;
  2624. if (typeof opts.level === 'number') level = opts.level;
  2625. var strategy = exports.Z_DEFAULT_STRATEGY;
  2626. if (typeof opts.strategy === 'number') strategy = opts.strategy;
  2627. this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
  2628. this._buffer = Buffer.allocUnsafe(this._chunkSize);
  2629. this._offset = 0;
  2630. this._level = level;
  2631. this._strategy = strategy;
  2632. this.once('end', this.close);
  2633. Object.defineProperty(this, '_closed', {
  2634. get: function () {
  2635. return !_this._handle;
  2636. },
  2637. configurable: true,
  2638. enumerable: true
  2639. });
  2640. }
  2641. util.inherits(Zlib, Transform);
  2642. Zlib.prototype.params = function (level, strategy, callback) {
  2643. if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
  2644. throw new RangeError('Invalid compression level: ' + level);
  2645. }
  2646. if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
  2647. throw new TypeError('Invalid strategy: ' + strategy);
  2648. }
  2649. if (this._level !== level || this._strategy !== strategy) {
  2650. var self = this;
  2651. this.flush(binding.Z_SYNC_FLUSH, function () {
  2652. assert(self._handle, 'zlib binding closed');
  2653. self._handle.params(level, strategy);
  2654. if (!self._hadError) {
  2655. self._level = level;
  2656. self._strategy = strategy;
  2657. if (callback) callback();
  2658. }
  2659. });
  2660. } else {
  2661. process.nextTick(callback);
  2662. }
  2663. };
  2664. Zlib.prototype.reset = function () {
  2665. assert(this._handle, 'zlib binding closed');
  2666. return this._handle.reset();
  2667. };
  2668. // This is the _flush function called by the transform class,
  2669. // internally, when the last chunk has been written.
  2670. Zlib.prototype._flush = function (callback) {
  2671. this._transform(Buffer.alloc(0), '', callback);
  2672. };
  2673. Zlib.prototype.flush = function (kind, callback) {
  2674. var _this2 = this;
  2675. var ws = this._writableState;
  2676. if (typeof kind === 'function' || kind === undefined && !callback) {
  2677. callback = kind;
  2678. kind = binding.Z_FULL_FLUSH;
  2679. }
  2680. if (ws.ended) {
  2681. if (callback) process.nextTick(callback);
  2682. } else if (ws.ending) {
  2683. if (callback) this.once('end', callback);
  2684. } else if (ws.needDrain) {
  2685. if (callback) {
  2686. this.once('drain', function () {
  2687. return _this2.flush(kind, callback);
  2688. });
  2689. }
  2690. } else {
  2691. this._flushFlag = kind;
  2692. this.write(Buffer.alloc(0), '', callback);
  2693. }
  2694. };
  2695. Zlib.prototype.close = function (callback) {
  2696. _close(this, callback);
  2697. process.nextTick(emitCloseNT, this);
  2698. };
  2699. function _close(engine, callback) {
  2700. if (callback) process.nextTick(callback);
  2701. // Caller may invoke .close after a zlib error (which will null _handle).
  2702. if (!engine._handle) return;
  2703. engine._handle.close();
  2704. engine._handle = null;
  2705. }
  2706. function emitCloseNT(self) {
  2707. self.emit('close');
  2708. }
  2709. Zlib.prototype._transform = function (chunk, encoding, cb) {
  2710. var flushFlag;
  2711. var ws = this._writableState;
  2712. var ending = ws.ending || ws.ended;
  2713. var last = ending && (!chunk || ws.length === chunk.length);
  2714. if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
  2715. if (!this._handle) return cb(new Error('zlib binding closed'));
  2716. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  2717. // (or whatever flag was provided using opts.finishFlush).
  2718. // If it's explicitly flushing at some other time, then we use
  2719. // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  2720. // goodness.
  2721. if (last) flushFlag = this._finishFlushFlag;else {
  2722. flushFlag = this._flushFlag;
  2723. // once we've flushed the last of the queue, stop flushing and
  2724. // go back to the normal behavior.
  2725. if (chunk.length >= ws.length) {
  2726. this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
  2727. }
  2728. }
  2729. this._processChunk(chunk, flushFlag, cb);
  2730. };
  2731. Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  2732. var availInBefore = chunk && chunk.length;
  2733. var availOutBefore = this._chunkSize - this._offset;
  2734. var inOff = 0;
  2735. var self = this;
  2736. var async = typeof cb === 'function';
  2737. if (!async) {
  2738. var buffers = [];
  2739. var nread = 0;
  2740. var error;
  2741. this.on('error', function (er) {
  2742. error = er;
  2743. });
  2744. assert(this._handle, 'zlib binding closed');
  2745. do {
  2746. var res = this._handle.writeSync(flushFlag, chunk, // in
  2747. inOff, // in_off
  2748. availInBefore, // in_len
  2749. this._buffer, // out
  2750. this._offset, //out_off
  2751. availOutBefore); // out_len
  2752. } while (!this._hadError && callback(res[0], res[1]));
  2753. if (this._hadError) {
  2754. throw error;
  2755. }
  2756. if (nread >= kMaxLength) {
  2757. _close(this);
  2758. throw new RangeError(kRangeErrorMessage);
  2759. }
  2760. var buf = Buffer.concat(buffers, nread);
  2761. _close(this);
  2762. return buf;
  2763. }
  2764. assert(this._handle, 'zlib binding closed');
  2765. var req = this._handle.write(flushFlag, chunk, // in
  2766. inOff, // in_off
  2767. availInBefore, // in_len
  2768. this._buffer, // out
  2769. this._offset, //out_off
  2770. availOutBefore); // out_len
  2771. req.buffer = chunk;
  2772. req.callback = callback;
  2773. function callback(availInAfter, availOutAfter) {
  2774. // When the callback is used in an async write, the callback's
  2775. // context is the `req` object that was created. The req object
  2776. // is === this._handle, and that's why it's important to null
  2777. // out the values after they are done being used. `this._handle`
  2778. // can stay in memory longer than the callback and buffer are needed.
  2779. if (this) {
  2780. this.buffer = null;
  2781. this.callback = null;
  2782. }
  2783. if (self._hadError) return;
  2784. var have = availOutBefore - availOutAfter;
  2785. assert(have >= 0, 'have should not go down');
  2786. if (have > 0) {
  2787. var out = self._buffer.slice(self._offset, self._offset + have);
  2788. self._offset += have;
  2789. // serve some output to the consumer.
  2790. if (async) {
  2791. self.push(out);
  2792. } else {
  2793. buffers.push(out);
  2794. nread += out.length;
  2795. }
  2796. }
  2797. // exhausted the output buffer, or used all the input create a new one.
  2798. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  2799. availOutBefore = self._chunkSize;
  2800. self._offset = 0;
  2801. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  2802. }
  2803. if (availOutAfter === 0) {
  2804. // Not actually done. Need to reprocess.
  2805. // Also, update the availInBefore to the availInAfter value,
  2806. // so that if we have to hit it a third (fourth, etc.) time,
  2807. // it'll have the correct byte counts.
  2808. inOff += availInBefore - availInAfter;
  2809. availInBefore = availInAfter;
  2810. if (!async) return true;
  2811. var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
  2812. newReq.callback = callback; // this same function
  2813. newReq.buffer = chunk;
  2814. return;
  2815. }
  2816. if (!async) return false;
  2817. // finished with the chunk.
  2818. cb();
  2819. }
  2820. };
  2821. util.inherits(Deflate, Zlib);
  2822. util.inherits(Inflate, Zlib);
  2823. util.inherits(Gzip, Zlib);
  2824. util.inherits(Gunzip, Zlib);
  2825. util.inherits(DeflateRaw, Zlib);
  2826. util.inherits(InflateRaw, Zlib);
  2827. util.inherits(Unzip, Zlib);
  2828. }).call(this,require('_process'))
  2829. },{"./binding":33,"_process":312,"assert":24,"buffer":47,"stream":334,"util":365}],35:[function(require,module,exports){
  2830. 'use strict';
  2831. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  2832. (typeof Uint16Array !== 'undefined') &&
  2833. (typeof Int32Array !== 'undefined');
  2834. function _has(obj, key) {
  2835. return Object.prototype.hasOwnProperty.call(obj, key);
  2836. }
  2837. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  2838. var sources = Array.prototype.slice.call(arguments, 1);
  2839. while (sources.length) {
  2840. var source = sources.shift();
  2841. if (!source) { continue; }
  2842. if (typeof source !== 'object') {
  2843. throw new TypeError(source + 'must be non-object');
  2844. }
  2845. for (var p in source) {
  2846. if (_has(source, p)) {
  2847. obj[p] = source[p];
  2848. }
  2849. }
  2850. }
  2851. return obj;
  2852. };
  2853. // reduce buffer size, avoiding mem copy
  2854. exports.shrinkBuf = function (buf, size) {
  2855. if (buf.length === size) { return buf; }
  2856. if (buf.subarray) { return buf.subarray(0, size); }
  2857. buf.length = size;
  2858. return buf;
  2859. };
  2860. var fnTyped = {
  2861. arraySet: function (dest, src, src_offs, len, dest_offs) {
  2862. if (src.subarray && dest.subarray) {
  2863. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  2864. return;
  2865. }
  2866. // Fallback to ordinary array
  2867. for (var i = 0; i < len; i++) {
  2868. dest[dest_offs + i] = src[src_offs + i];
  2869. }
  2870. },
  2871. // Join array of chunks to single array.
  2872. flattenChunks: function (chunks) {
  2873. var i, l, len, pos, chunk, result;
  2874. // calculate data length
  2875. len = 0;
  2876. for (i = 0, l = chunks.length; i < l; i++) {
  2877. len += chunks[i].length;
  2878. }
  2879. // join chunks
  2880. result = new Uint8Array(len);
  2881. pos = 0;
  2882. for (i = 0, l = chunks.length; i < l; i++) {
  2883. chunk = chunks[i];
  2884. result.set(chunk, pos);
  2885. pos += chunk.length;
  2886. }
  2887. return result;
  2888. }
  2889. };
  2890. var fnUntyped = {
  2891. arraySet: function (dest, src, src_offs, len, dest_offs) {
  2892. for (var i = 0; i < len; i++) {
  2893. dest[dest_offs + i] = src[src_offs + i];
  2894. }
  2895. },
  2896. // Join array of chunks to single array.
  2897. flattenChunks: function (chunks) {
  2898. return [].concat.apply([], chunks);
  2899. }
  2900. };
  2901. // Enable/Disable typed arrays use, for testing
  2902. //
  2903. exports.setTyped = function (on) {
  2904. if (on) {
  2905. exports.Buf8 = Uint8Array;
  2906. exports.Buf16 = Uint16Array;
  2907. exports.Buf32 = Int32Array;
  2908. exports.assign(exports, fnTyped);
  2909. } else {
  2910. exports.Buf8 = Array;
  2911. exports.Buf16 = Array;
  2912. exports.Buf32 = Array;
  2913. exports.assign(exports, fnUntyped);
  2914. }
  2915. };
  2916. exports.setTyped(TYPED_OK);
  2917. },{}],36:[function(require,module,exports){
  2918. 'use strict';
  2919. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  2920. // It isn't worth it to make additional optimizations as in original.
  2921. // Small size is preferable.
  2922. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  2923. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  2924. //
  2925. // This software is provided 'as-is', without any express or implied
  2926. // warranty. In no event will the authors be held liable for any damages
  2927. // arising from the use of this software.
  2928. //
  2929. // Permission is granted to anyone to use this software for any purpose,
  2930. // including commercial applications, and to alter it and redistribute it
  2931. // freely, subject to the following restrictions:
  2932. //
  2933. // 1. The origin of this software must not be misrepresented; you must not
  2934. // claim that you wrote the original software. If you use this software
  2935. // in a product, an acknowledgment in the product documentation would be
  2936. // appreciated but is not required.
  2937. // 2. Altered source versions must be plainly marked as such, and must not be
  2938. // misrepresented as being the original software.
  2939. // 3. This notice may not be removed or altered from any source distribution.
  2940. function adler32(adler, buf, len, pos) {
  2941. var s1 = (adler & 0xffff) |0,
  2942. s2 = ((adler >>> 16) & 0xffff) |0,
  2943. n = 0;
  2944. while (len !== 0) {
  2945. // Set limit ~ twice less than 5552, to keep
  2946. // s2 in 31-bits, because we force signed ints.
  2947. // in other case %= will fail.
  2948. n = len > 2000 ? 2000 : len;
  2949. len -= n;
  2950. do {
  2951. s1 = (s1 + buf[pos++]) |0;
  2952. s2 = (s2 + s1) |0;
  2953. } while (--n);
  2954. s1 %= 65521;
  2955. s2 %= 65521;
  2956. }
  2957. return (s1 | (s2 << 16)) |0;
  2958. }
  2959. module.exports = adler32;
  2960. },{}],37:[function(require,module,exports){
  2961. 'use strict';
  2962. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  2963. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  2964. //
  2965. // This software is provided 'as-is', without any express or implied
  2966. // warranty. In no event will the authors be held liable for any damages
  2967. // arising from the use of this software.
  2968. //
  2969. // Permission is granted to anyone to use this software for any purpose,
  2970. // including commercial applications, and to alter it and redistribute it
  2971. // freely, subject to the following restrictions:
  2972. //
  2973. // 1. The origin of this software must not be misrepresented; you must not
  2974. // claim that you wrote the original software. If you use this software
  2975. // in a product, an acknowledgment in the product documentation would be
  2976. // appreciated but is not required.
  2977. // 2. Altered source versions must be plainly marked as such, and must not be
  2978. // misrepresented as being the original software.
  2979. // 3. This notice may not be removed or altered from any source distribution.
  2980. module.exports = {
  2981. /* Allowed flush values; see deflate() and inflate() below for details */
  2982. Z_NO_FLUSH: 0,
  2983. Z_PARTIAL_FLUSH: 1,
  2984. Z_SYNC_FLUSH: 2,
  2985. Z_FULL_FLUSH: 3,
  2986. Z_FINISH: 4,
  2987. Z_BLOCK: 5,
  2988. Z_TREES: 6,
  2989. /* Return codes for the compression/decompression functions. Negative values
  2990. * are errors, positive values are used for special but normal events.
  2991. */
  2992. Z_OK: 0,
  2993. Z_STREAM_END: 1,
  2994. Z_NEED_DICT: 2,
  2995. Z_ERRNO: -1,
  2996. Z_STREAM_ERROR: -2,
  2997. Z_DATA_ERROR: -3,
  2998. //Z_MEM_ERROR: -4,
  2999. Z_BUF_ERROR: -5,
  3000. //Z_VERSION_ERROR: -6,
  3001. /* compression levels */
  3002. Z_NO_COMPRESSION: 0,
  3003. Z_BEST_SPEED: 1,
  3004. Z_BEST_COMPRESSION: 9,
  3005. Z_DEFAULT_COMPRESSION: -1,
  3006. Z_FILTERED: 1,
  3007. Z_HUFFMAN_ONLY: 2,
  3008. Z_RLE: 3,
  3009. Z_FIXED: 4,
  3010. Z_DEFAULT_STRATEGY: 0,
  3011. /* Possible values of the data_type field (though see inflate()) */
  3012. Z_BINARY: 0,
  3013. Z_TEXT: 1,
  3014. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  3015. Z_UNKNOWN: 2,
  3016. /* The deflate compression method */
  3017. Z_DEFLATED: 8
  3018. //Z_NULL: null // Use -1 or null inline, depending on var type
  3019. };
  3020. },{}],38:[function(require,module,exports){
  3021. 'use strict';
  3022. // Note: we can't get significant speed boost here.
  3023. // So write code to minimize size - no pregenerated tables
  3024. // and array tools dependencies.
  3025. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  3026. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  3027. //
  3028. // This software is provided 'as-is', without any express or implied
  3029. // warranty. In no event will the authors be held liable for any damages
  3030. // arising from the use of this software.
  3031. //
  3032. // Permission is granted to anyone to use this software for any purpose,
  3033. // including commercial applications, and to alter it and redistribute it
  3034. // freely, subject to the following restrictions:
  3035. //
  3036. // 1. The origin of this software must not be misrepresented; you must not
  3037. // claim that you wrote the original software. If you use this software
  3038. // in a product, an acknowledgment in the product documentation would be
  3039. // appreciated but is not required.
  3040. // 2. Altered source versions must be plainly marked as such, and must not be
  3041. // misrepresented as being the original software.
  3042. // 3. This notice may not be removed or altered from any source distribution.
  3043. // Use ordinary array, since untyped makes no boost here
  3044. function makeTable() {
  3045. var c, table = [];
  3046. for (var n = 0; n < 256; n++) {
  3047. c = n;
  3048. for (var k = 0; k < 8; k++) {
  3049. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  3050. }
  3051. table[n] = c;
  3052. }
  3053. return table;
  3054. }
  3055. // Create table on load. Just 255 signed longs. Not a problem.
  3056. var crcTable = makeTable();
  3057. function crc32(crc, buf, len, pos) {
  3058. var t = crcTable,
  3059. end = pos + len;
  3060. crc ^= -1;
  3061. for (var i = pos; i < end; i++) {
  3062. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  3063. }
  3064. return (crc ^ (-1)); // >>> 0;
  3065. }
  3066. module.exports = crc32;
  3067. },{}],39:[function(require,module,exports){
  3068. 'use strict';
  3069. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  3070. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  3071. //
  3072. // This software is provided 'as-is', without any express or implied
  3073. // warranty. In no event will the authors be held liable for any damages
  3074. // arising from the use of this software.
  3075. //
  3076. // Permission is granted to anyone to use this software for any purpose,
  3077. // including commercial applications, and to alter it and redistribute it
  3078. // freely, subject to the following restrictions:
  3079. //
  3080. // 1. The origin of this software must not be misrepresented; you must not
  3081. // claim that you wrote the original software. If you use this software
  3082. // in a product, an acknowledgment in the product documentation would be
  3083. // appreciated but is not required.
  3084. // 2. Altered source versions must be plainly marked as such, and must not be
  3085. // misrepresented as being the original software.
  3086. // 3. This notice may not be removed or altered from any source distribution.
  3087. var utils = require('../utils/common');
  3088. var trees = require('./trees');
  3089. var adler32 = require('./adler32');
  3090. var crc32 = require('./crc32');
  3091. var msg = require('./messages');
  3092. /* Public constants ==========================================================*/
  3093. /* ===========================================================================*/
  3094. /* Allowed flush values; see deflate() and inflate() below for details */
  3095. var Z_NO_FLUSH = 0;
  3096. var Z_PARTIAL_FLUSH = 1;
  3097. //var Z_SYNC_FLUSH = 2;
  3098. var Z_FULL_FLUSH = 3;
  3099. var Z_FINISH = 4;
  3100. var Z_BLOCK = 5;
  3101. //var Z_TREES = 6;
  3102. /* Return codes for the compression/decompression functions. Negative values
  3103. * are errors, positive values are used for special but normal events.
  3104. */
  3105. var Z_OK = 0;
  3106. var Z_STREAM_END = 1;
  3107. //var Z_NEED_DICT = 2;
  3108. //var Z_ERRNO = -1;
  3109. var Z_STREAM_ERROR = -2;
  3110. var Z_DATA_ERROR = -3;
  3111. //var Z_MEM_ERROR = -4;
  3112. var Z_BUF_ERROR = -5;
  3113. //var Z_VERSION_ERROR = -6;
  3114. /* compression levels */
  3115. //var Z_NO_COMPRESSION = 0;
  3116. //var Z_BEST_SPEED = 1;
  3117. //var Z_BEST_COMPRESSION = 9;
  3118. var Z_DEFAULT_COMPRESSION = -1;
  3119. var Z_FILTERED = 1;
  3120. var Z_HUFFMAN_ONLY = 2;
  3121. var Z_RLE = 3;
  3122. var Z_FIXED = 4;
  3123. var Z_DEFAULT_STRATEGY = 0;
  3124. /* Possible values of the data_type field (though see inflate()) */
  3125. //var Z_BINARY = 0;
  3126. //var Z_TEXT = 1;
  3127. //var Z_ASCII = 1; // = Z_TEXT
  3128. var Z_UNKNOWN = 2;
  3129. /* The deflate compression method */
  3130. var Z_DEFLATED = 8;
  3131. /*============================================================================*/
  3132. var MAX_MEM_LEVEL = 9;
  3133. /* Maximum value for memLevel in deflateInit2 */
  3134. var MAX_WBITS = 15;
  3135. /* 32K LZ77 window */
  3136. var DEF_MEM_LEVEL = 8;
  3137. var LENGTH_CODES = 29;
  3138. /* number of length codes, not counting the special END_BLOCK code */
  3139. var LITERALS = 256;
  3140. /* number of literal bytes 0..255 */
  3141. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  3142. /* number of Literal or Length codes, including the END_BLOCK code */
  3143. var D_CODES = 30;
  3144. /* number of distance codes */
  3145. var BL_CODES = 19;
  3146. /* number of codes used to transfer the bit lengths */
  3147. var HEAP_SIZE = 2 * L_CODES + 1;
  3148. /* maximum heap size */
  3149. var MAX_BITS = 15;
  3150. /* All codes must not exceed MAX_BITS bits */
  3151. var MIN_MATCH = 3;
  3152. var MAX_MATCH = 258;
  3153. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  3154. var PRESET_DICT = 0x20;
  3155. var INIT_STATE = 42;
  3156. var EXTRA_STATE = 69;
  3157. var NAME_STATE = 73;
  3158. var COMMENT_STATE = 91;
  3159. var HCRC_STATE = 103;
  3160. var BUSY_STATE = 113;
  3161. var FINISH_STATE = 666;
  3162. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  3163. var BS_BLOCK_DONE = 2; /* block flush performed */
  3164. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  3165. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  3166. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  3167. function err(strm, errorCode) {
  3168. strm.msg = msg[errorCode];
  3169. return errorCode;
  3170. }
  3171. function rank(f) {
  3172. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  3173. }
  3174. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  3175. /* =========================================================================
  3176. * Flush as much pending output as possible. All deflate() output goes
  3177. * through this function so some applications may wish to modify it
  3178. * to avoid allocating a large strm->output buffer and copying into it.
  3179. * (See also read_buf()).
  3180. */
  3181. function flush_pending(strm) {
  3182. var s = strm.state;
  3183. //_tr_flush_bits(s);
  3184. var len = s.pending;
  3185. if (len > strm.avail_out) {
  3186. len = strm.avail_out;
  3187. }
  3188. if (len === 0) { return; }
  3189. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  3190. strm.next_out += len;
  3191. s.pending_out += len;
  3192. strm.total_out += len;
  3193. strm.avail_out -= len;
  3194. s.pending -= len;
  3195. if (s.pending === 0) {
  3196. s.pending_out = 0;
  3197. }
  3198. }
  3199. function flush_block_only(s, last) {
  3200. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  3201. s.block_start = s.strstart;
  3202. flush_pending(s.strm);
  3203. }
  3204. function put_byte(s, b) {
  3205. s.pending_buf[s.pending++] = b;
  3206. }
  3207. /* =========================================================================
  3208. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  3209. * IN assertion: the stream state is correct and there is enough room in
  3210. * pending_buf.
  3211. */
  3212. function putShortMSB(s, b) {
  3213. // put_byte(s, (Byte)(b >> 8));
  3214. // put_byte(s, (Byte)(b & 0xff));
  3215. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  3216. s.pending_buf[s.pending++] = b & 0xff;
  3217. }
  3218. /* ===========================================================================
  3219. * Read a new buffer from the current input stream, update the adler32
  3220. * and total number of bytes read. All deflate() input goes through
  3221. * this function so some applications may wish to modify it to avoid
  3222. * allocating a large strm->input buffer and copying from it.
  3223. * (See also flush_pending()).
  3224. */
  3225. function read_buf(strm, buf, start, size) {
  3226. var len = strm.avail_in;
  3227. if (len > size) { len = size; }
  3228. if (len === 0) { return 0; }
  3229. strm.avail_in -= len;
  3230. // zmemcpy(buf, strm->next_in, len);
  3231. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  3232. if (strm.state.wrap === 1) {
  3233. strm.adler = adler32(strm.adler, buf, len, start);
  3234. }
  3235. else if (strm.state.wrap === 2) {
  3236. strm.adler = crc32(strm.adler, buf, len, start);
  3237. }
  3238. strm.next_in += len;
  3239. strm.total_in += len;
  3240. return len;
  3241. }
  3242. /* ===========================================================================
  3243. * Set match_start to the longest match starting at the given string and
  3244. * return its length. Matches shorter or equal to prev_length are discarded,
  3245. * in which case the result is equal to prev_length and match_start is
  3246. * garbage.
  3247. * IN assertions: cur_match is the head of the hash chain for the current
  3248. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  3249. * OUT assertion: the match length is not greater than s->lookahead.
  3250. */
  3251. function longest_match(s, cur_match) {
  3252. var chain_length = s.max_chain_length; /* max hash chain length */
  3253. var scan = s.strstart; /* current string */
  3254. var match; /* matched string */
  3255. var len; /* length of current match */
  3256. var best_len = s.prev_length; /* best match length so far */
  3257. var nice_match = s.nice_match; /* stop if match long enough */
  3258. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  3259. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  3260. var _win = s.window; // shortcut
  3261. var wmask = s.w_mask;
  3262. var prev = s.prev;
  3263. /* Stop when cur_match becomes <= limit. To simplify the code,
  3264. * we prevent matches with the string of window index 0.
  3265. */
  3266. var strend = s.strstart + MAX_MATCH;
  3267. var scan_end1 = _win[scan + best_len - 1];
  3268. var scan_end = _win[scan + best_len];
  3269. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  3270. * It is easy to get rid of this optimization if necessary.
  3271. */
  3272. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  3273. /* Do not waste too much time if we already have a good match: */
  3274. if (s.prev_length >= s.good_match) {
  3275. chain_length >>= 2;
  3276. }
  3277. /* Do not look for matches beyond the end of the input. This is necessary
  3278. * to make deflate deterministic.
  3279. */
  3280. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  3281. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  3282. do {
  3283. // Assert(cur_match < s->strstart, "no future");
  3284. match = cur_match;
  3285. /* Skip to next match if the match length cannot increase
  3286. * or if the match length is less than 2. Note that the checks below
  3287. * for insufficient lookahead only occur occasionally for performance
  3288. * reasons. Therefore uninitialized memory will be accessed, and
  3289. * conditional jumps will be made that depend on those values.
  3290. * However the length of the match is limited to the lookahead, so
  3291. * the output of deflate is not affected by the uninitialized values.
  3292. */
  3293. if (_win[match + best_len] !== scan_end ||
  3294. _win[match + best_len - 1] !== scan_end1 ||
  3295. _win[match] !== _win[scan] ||
  3296. _win[++match] !== _win[scan + 1]) {
  3297. continue;
  3298. }
  3299. /* The check at best_len-1 can be removed because it will be made
  3300. * again later. (This heuristic is not always a win.)
  3301. * It is not necessary to compare scan[2] and match[2] since they
  3302. * are always equal when the other bytes match, given that
  3303. * the hash keys are equal and that HASH_BITS >= 8.
  3304. */
  3305. scan += 2;
  3306. match++;
  3307. // Assert(*scan == *match, "match[2]?");
  3308. /* We check for insufficient lookahead only every 8th comparison;
  3309. * the 256th check will be made at strstart+258.
  3310. */
  3311. do {
  3312. /*jshint noempty:false*/
  3313. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3314. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3315. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3316. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3317. scan < strend);
  3318. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  3319. len = MAX_MATCH - (strend - scan);
  3320. scan = strend - MAX_MATCH;
  3321. if (len > best_len) {
  3322. s.match_start = cur_match;
  3323. best_len = len;
  3324. if (len >= nice_match) {
  3325. break;
  3326. }
  3327. scan_end1 = _win[scan + best_len - 1];
  3328. scan_end = _win[scan + best_len];
  3329. }
  3330. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  3331. if (best_len <= s.lookahead) {
  3332. return best_len;
  3333. }
  3334. return s.lookahead;
  3335. }
  3336. /* ===========================================================================
  3337. * Fill the window when the lookahead becomes insufficient.
  3338. * Updates strstart and lookahead.
  3339. *
  3340. * IN assertion: lookahead < MIN_LOOKAHEAD
  3341. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  3342. * At least one byte has been read, or avail_in == 0; reads are
  3343. * performed for at least two bytes (required for the zip translate_eol
  3344. * option -- not supported here).
  3345. */
  3346. function fill_window(s) {
  3347. var _w_size = s.w_size;
  3348. var p, n, m, more, str;
  3349. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  3350. do {
  3351. more = s.window_size - s.lookahead - s.strstart;
  3352. // JS ints have 32 bit, block below not needed
  3353. /* Deal with !@#$% 64K limit: */
  3354. //if (sizeof(int) <= 2) {
  3355. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  3356. // more = wsize;
  3357. //
  3358. // } else if (more == (unsigned)(-1)) {
  3359. // /* Very unlikely, but possible on 16 bit machine if
  3360. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  3361. // */
  3362. // more--;
  3363. // }
  3364. //}
  3365. /* If the window is almost full and there is insufficient lookahead,
  3366. * move the upper half to the lower one to make room in the upper half.
  3367. */
  3368. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  3369. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  3370. s.match_start -= _w_size;
  3371. s.strstart -= _w_size;
  3372. /* we now have strstart >= MAX_DIST */
  3373. s.block_start -= _w_size;
  3374. /* Slide the hash table (could be avoided with 32 bit values
  3375. at the expense of memory usage). We slide even when level == 0
  3376. to keep the hash table consistent if we switch back to level > 0
  3377. later. (Using level 0 permanently is not an optimal usage of
  3378. zlib, so we don't care about this pathological case.)
  3379. */
  3380. n = s.hash_size;
  3381. p = n;
  3382. do {
  3383. m = s.head[--p];
  3384. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  3385. } while (--n);
  3386. n = _w_size;
  3387. p = n;
  3388. do {
  3389. m = s.prev[--p];
  3390. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  3391. /* If n is not on any hash chain, prev[n] is garbage but
  3392. * its value will never be used.
  3393. */
  3394. } while (--n);
  3395. more += _w_size;
  3396. }
  3397. if (s.strm.avail_in === 0) {
  3398. break;
  3399. }
  3400. /* If there was no sliding:
  3401. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  3402. * more == window_size - lookahead - strstart
  3403. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  3404. * => more >= window_size - 2*WSIZE + 2
  3405. * In the BIG_MEM or MMAP case (not yet supported),
  3406. * window_size == input_size + MIN_LOOKAHEAD &&
  3407. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  3408. * Otherwise, window_size == 2*WSIZE so more >= 2.
  3409. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  3410. */
  3411. //Assert(more >= 2, "more < 2");
  3412. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  3413. s.lookahead += n;
  3414. /* Initialize the hash value now that we have some input: */
  3415. if (s.lookahead + s.insert >= MIN_MATCH) {
  3416. str = s.strstart - s.insert;
  3417. s.ins_h = s.window[str];
  3418. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  3419. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  3420. //#if MIN_MATCH != 3
  3421. // Call update_hash() MIN_MATCH-3 more times
  3422. //#endif
  3423. while (s.insert) {
  3424. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  3425. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  3426. s.prev[str & s.w_mask] = s.head[s.ins_h];
  3427. s.head[s.ins_h] = str;
  3428. str++;
  3429. s.insert--;
  3430. if (s.lookahead + s.insert < MIN_MATCH) {
  3431. break;
  3432. }
  3433. }
  3434. }
  3435. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  3436. * but this is not important since only literal bytes will be emitted.
  3437. */
  3438. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  3439. /* If the WIN_INIT bytes after the end of the current data have never been
  3440. * written, then zero those bytes in order to avoid memory check reports of
  3441. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  3442. * the longest match routines. Update the high water mark for the next
  3443. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  3444. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  3445. */
  3446. // if (s.high_water < s.window_size) {
  3447. // var curr = s.strstart + s.lookahead;
  3448. // var init = 0;
  3449. //
  3450. // if (s.high_water < curr) {
  3451. // /* Previous high water mark below current data -- zero WIN_INIT
  3452. // * bytes or up to end of window, whichever is less.
  3453. // */
  3454. // init = s.window_size - curr;
  3455. // if (init > WIN_INIT)
  3456. // init = WIN_INIT;
  3457. // zmemzero(s->window + curr, (unsigned)init);
  3458. // s->high_water = curr + init;
  3459. // }
  3460. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  3461. // /* High water mark at or above current data, but below current data
  3462. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  3463. // * to end of window, whichever is less.
  3464. // */
  3465. // init = (ulg)curr + WIN_INIT - s->high_water;
  3466. // if (init > s->window_size - s->high_water)
  3467. // init = s->window_size - s->high_water;
  3468. // zmemzero(s->window + s->high_water, (unsigned)init);
  3469. // s->high_water += init;
  3470. // }
  3471. // }
  3472. //
  3473. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  3474. // "not enough room for search");
  3475. }
  3476. /* ===========================================================================
  3477. * Copy without compression as much as possible from the input stream, return
  3478. * the current block state.
  3479. * This function does not insert new strings in the dictionary since
  3480. * uncompressible data is probably not useful. This function is used
  3481. * only for the level=0 compression option.
  3482. * NOTE: this function should be optimized to avoid extra copying from
  3483. * window to pending_buf.
  3484. */
  3485. function deflate_stored(s, flush) {
  3486. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  3487. * to pending_buf_size, and each stored block has a 5 byte header:
  3488. */
  3489. var max_block_size = 0xffff;
  3490. if (max_block_size > s.pending_buf_size - 5) {
  3491. max_block_size = s.pending_buf_size - 5;
  3492. }
  3493. /* Copy as much as possible from input to output: */
  3494. for (;;) {
  3495. /* Fill the window as much as possible: */
  3496. if (s.lookahead <= 1) {
  3497. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  3498. // s->block_start >= (long)s->w_size, "slide too late");
  3499. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  3500. // s.block_start >= s.w_size)) {
  3501. // throw new Error("slide too late");
  3502. // }
  3503. fill_window(s);
  3504. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  3505. return BS_NEED_MORE;
  3506. }
  3507. if (s.lookahead === 0) {
  3508. break;
  3509. }
  3510. /* flush the current block */
  3511. }
  3512. //Assert(s->block_start >= 0L, "block gone");
  3513. // if (s.block_start < 0) throw new Error("block gone");
  3514. s.strstart += s.lookahead;
  3515. s.lookahead = 0;
  3516. /* Emit a stored block if pending_buf will be full: */
  3517. var max_start = s.block_start + max_block_size;
  3518. if (s.strstart === 0 || s.strstart >= max_start) {
  3519. /* strstart == 0 is possible when wraparound on 16-bit machine */
  3520. s.lookahead = s.strstart - max_start;
  3521. s.strstart = max_start;
  3522. /*** FLUSH_BLOCK(s, 0); ***/
  3523. flush_block_only(s, false);
  3524. if (s.strm.avail_out === 0) {
  3525. return BS_NEED_MORE;
  3526. }
  3527. /***/
  3528. }
  3529. /* Flush if we may have to slide, otherwise block_start may become
  3530. * negative and the data will be gone:
  3531. */
  3532. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  3533. /*** FLUSH_BLOCK(s, 0); ***/
  3534. flush_block_only(s, false);
  3535. if (s.strm.avail_out === 0) {
  3536. return BS_NEED_MORE;
  3537. }
  3538. /***/
  3539. }
  3540. }
  3541. s.insert = 0;
  3542. if (flush === Z_FINISH) {
  3543. /*** FLUSH_BLOCK(s, 1); ***/
  3544. flush_block_only(s, true);
  3545. if (s.strm.avail_out === 0) {
  3546. return BS_FINISH_STARTED;
  3547. }
  3548. /***/
  3549. return BS_FINISH_DONE;
  3550. }
  3551. if (s.strstart > s.block_start) {
  3552. /*** FLUSH_BLOCK(s, 0); ***/
  3553. flush_block_only(s, false);
  3554. if (s.strm.avail_out === 0) {
  3555. return BS_NEED_MORE;
  3556. }
  3557. /***/
  3558. }
  3559. return BS_NEED_MORE;
  3560. }
  3561. /* ===========================================================================
  3562. * Compress as much as possible from the input stream, return the current
  3563. * block state.
  3564. * This function does not perform lazy evaluation of matches and inserts
  3565. * new strings in the dictionary only for unmatched strings or for short
  3566. * matches. It is used only for the fast compression options.
  3567. */
  3568. function deflate_fast(s, flush) {
  3569. var hash_head; /* head of the hash chain */
  3570. var bflush; /* set if current block must be flushed */
  3571. for (;;) {
  3572. /* Make sure that we always have enough lookahead, except
  3573. * at the end of the input file. We need MAX_MATCH bytes
  3574. * for the next match, plus MIN_MATCH bytes to insert the
  3575. * string following the next match.
  3576. */
  3577. if (s.lookahead < MIN_LOOKAHEAD) {
  3578. fill_window(s);
  3579. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  3580. return BS_NEED_MORE;
  3581. }
  3582. if (s.lookahead === 0) {
  3583. break; /* flush the current block */
  3584. }
  3585. }
  3586. /* Insert the string window[strstart .. strstart+2] in the
  3587. * dictionary, and set hash_head to the head of the hash chain:
  3588. */
  3589. hash_head = 0/*NIL*/;
  3590. if (s.lookahead >= MIN_MATCH) {
  3591. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3592. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3593. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3594. s.head[s.ins_h] = s.strstart;
  3595. /***/
  3596. }
  3597. /* Find the longest match, discarding those <= prev_length.
  3598. * At this point we have always match_length < MIN_MATCH
  3599. */
  3600. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  3601. /* To simplify the code, we prevent matches with the string
  3602. * of window index 0 (in particular we have to avoid a match
  3603. * of the string with itself at the start of the input file).
  3604. */
  3605. s.match_length = longest_match(s, hash_head);
  3606. /* longest_match() sets match_start */
  3607. }
  3608. if (s.match_length >= MIN_MATCH) {
  3609. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  3610. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  3611. s.match_length - MIN_MATCH, bflush); ***/
  3612. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  3613. s.lookahead -= s.match_length;
  3614. /* Insert new strings in the hash table only if the match length
  3615. * is not too large. This saves time but degrades compression.
  3616. */
  3617. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  3618. s.match_length--; /* string at strstart already in table */
  3619. do {
  3620. s.strstart++;
  3621. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3622. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3623. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3624. s.head[s.ins_h] = s.strstart;
  3625. /***/
  3626. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  3627. * always MIN_MATCH bytes ahead.
  3628. */
  3629. } while (--s.match_length !== 0);
  3630. s.strstart++;
  3631. } else
  3632. {
  3633. s.strstart += s.match_length;
  3634. s.match_length = 0;
  3635. s.ins_h = s.window[s.strstart];
  3636. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  3637. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  3638. //#if MIN_MATCH != 3
  3639. // Call UPDATE_HASH() MIN_MATCH-3 more times
  3640. //#endif
  3641. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  3642. * matter since it will be recomputed at next deflate call.
  3643. */
  3644. }
  3645. } else {
  3646. /* No match, output a literal byte */
  3647. //Tracevv((stderr,"%c", s.window[s.strstart]));
  3648. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  3649. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  3650. s.lookahead--;
  3651. s.strstart++;
  3652. }
  3653. if (bflush) {
  3654. /*** FLUSH_BLOCK(s, 0); ***/
  3655. flush_block_only(s, false);
  3656. if (s.strm.avail_out === 0) {
  3657. return BS_NEED_MORE;
  3658. }
  3659. /***/
  3660. }
  3661. }
  3662. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  3663. if (flush === Z_FINISH) {
  3664. /*** FLUSH_BLOCK(s, 1); ***/
  3665. flush_block_only(s, true);
  3666. if (s.strm.avail_out === 0) {
  3667. return BS_FINISH_STARTED;
  3668. }
  3669. /***/
  3670. return BS_FINISH_DONE;
  3671. }
  3672. if (s.last_lit) {
  3673. /*** FLUSH_BLOCK(s, 0); ***/
  3674. flush_block_only(s, false);
  3675. if (s.strm.avail_out === 0) {
  3676. return BS_NEED_MORE;
  3677. }
  3678. /***/
  3679. }
  3680. return BS_BLOCK_DONE;
  3681. }
  3682. /* ===========================================================================
  3683. * Same as above, but achieves better compression. We use a lazy
  3684. * evaluation for matches: a match is finally adopted only if there is
  3685. * no better match at the next window position.
  3686. */
  3687. function deflate_slow(s, flush) {
  3688. var hash_head; /* head of hash chain */
  3689. var bflush; /* set if current block must be flushed */
  3690. var max_insert;
  3691. /* Process the input block. */
  3692. for (;;) {
  3693. /* Make sure that we always have enough lookahead, except
  3694. * at the end of the input file. We need MAX_MATCH bytes
  3695. * for the next match, plus MIN_MATCH bytes to insert the
  3696. * string following the next match.
  3697. */
  3698. if (s.lookahead < MIN_LOOKAHEAD) {
  3699. fill_window(s);
  3700. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  3701. return BS_NEED_MORE;
  3702. }
  3703. if (s.lookahead === 0) { break; } /* flush the current block */
  3704. }
  3705. /* Insert the string window[strstart .. strstart+2] in the
  3706. * dictionary, and set hash_head to the head of the hash chain:
  3707. */
  3708. hash_head = 0/*NIL*/;
  3709. if (s.lookahead >= MIN_MATCH) {
  3710. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3711. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3712. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3713. s.head[s.ins_h] = s.strstart;
  3714. /***/
  3715. }
  3716. /* Find the longest match, discarding those <= prev_length.
  3717. */
  3718. s.prev_length = s.match_length;
  3719. s.prev_match = s.match_start;
  3720. s.match_length = MIN_MATCH - 1;
  3721. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  3722. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  3723. /* To simplify the code, we prevent matches with the string
  3724. * of window index 0 (in particular we have to avoid a match
  3725. * of the string with itself at the start of the input file).
  3726. */
  3727. s.match_length = longest_match(s, hash_head);
  3728. /* longest_match() sets match_start */
  3729. if (s.match_length <= 5 &&
  3730. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  3731. /* If prev_match is also MIN_MATCH, match_start is garbage
  3732. * but we will ignore the current match anyway.
  3733. */
  3734. s.match_length = MIN_MATCH - 1;
  3735. }
  3736. }
  3737. /* If there was a match at the previous step and the current
  3738. * match is not better, output the previous match:
  3739. */
  3740. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  3741. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  3742. /* Do not insert strings in hash table beyond this. */
  3743. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  3744. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  3745. s.prev_length - MIN_MATCH, bflush);***/
  3746. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  3747. /* Insert in hash table all strings up to the end of the match.
  3748. * strstart-1 and strstart are already inserted. If there is not
  3749. * enough lookahead, the last two strings are not inserted in
  3750. * the hash table.
  3751. */
  3752. s.lookahead -= s.prev_length - 1;
  3753. s.prev_length -= 2;
  3754. do {
  3755. if (++s.strstart <= max_insert) {
  3756. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3757. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3758. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3759. s.head[s.ins_h] = s.strstart;
  3760. /***/
  3761. }
  3762. } while (--s.prev_length !== 0);
  3763. s.match_available = 0;
  3764. s.match_length = MIN_MATCH - 1;
  3765. s.strstart++;
  3766. if (bflush) {
  3767. /*** FLUSH_BLOCK(s, 0); ***/
  3768. flush_block_only(s, false);
  3769. if (s.strm.avail_out === 0) {
  3770. return BS_NEED_MORE;
  3771. }
  3772. /***/
  3773. }
  3774. } else if (s.match_available) {
  3775. /* If there was no match at the previous position, output a
  3776. * single literal. If there was a match but the current match
  3777. * is longer, truncate the previous match to a single literal.
  3778. */
  3779. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  3780. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  3781. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  3782. if (bflush) {
  3783. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  3784. flush_block_only(s, false);
  3785. /***/
  3786. }
  3787. s.strstart++;
  3788. s.lookahead--;
  3789. if (s.strm.avail_out === 0) {
  3790. return BS_NEED_MORE;
  3791. }
  3792. } else {
  3793. /* There is no previous match to compare with, wait for
  3794. * the next step to decide.
  3795. */
  3796. s.match_available = 1;
  3797. s.strstart++;
  3798. s.lookahead--;
  3799. }
  3800. }
  3801. //Assert (flush != Z_NO_FLUSH, "no flush?");
  3802. if (s.match_available) {
  3803. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  3804. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  3805. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  3806. s.match_available = 0;
  3807. }
  3808. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  3809. if (flush === Z_FINISH) {
  3810. /*** FLUSH_BLOCK(s, 1); ***/
  3811. flush_block_only(s, true);
  3812. if (s.strm.avail_out === 0) {
  3813. return BS_FINISH_STARTED;
  3814. }
  3815. /***/
  3816. return BS_FINISH_DONE;
  3817. }
  3818. if (s.last_lit) {
  3819. /*** FLUSH_BLOCK(s, 0); ***/
  3820. flush_block_only(s, false);
  3821. if (s.strm.avail_out === 0) {
  3822. return BS_NEED_MORE;
  3823. }
  3824. /***/
  3825. }
  3826. return BS_BLOCK_DONE;
  3827. }
  3828. /* ===========================================================================
  3829. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  3830. * one. Do not maintain a hash table. (It will be regenerated if this run of
  3831. * deflate switches away from Z_RLE.)
  3832. */
  3833. function deflate_rle(s, flush) {
  3834. var bflush; /* set if current block must be flushed */
  3835. var prev; /* byte at distance one to match */
  3836. var scan, strend; /* scan goes up to strend for length of run */
  3837. var _win = s.window;
  3838. for (;;) {
  3839. /* Make sure that we always have enough lookahead, except
  3840. * at the end of the input file. We need MAX_MATCH bytes
  3841. * for the longest run, plus one for the unrolled loop.
  3842. */
  3843. if (s.lookahead <= MAX_MATCH) {
  3844. fill_window(s);
  3845. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  3846. return BS_NEED_MORE;
  3847. }
  3848. if (s.lookahead === 0) { break; } /* flush the current block */
  3849. }
  3850. /* See how many times the previous byte repeats */
  3851. s.match_length = 0;
  3852. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  3853. scan = s.strstart - 1;
  3854. prev = _win[scan];
  3855. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  3856. strend = s.strstart + MAX_MATCH;
  3857. do {
  3858. /*jshint noempty:false*/
  3859. } while (prev === _win[++scan] && prev === _win[++scan] &&
  3860. prev === _win[++scan] && prev === _win[++scan] &&
  3861. prev === _win[++scan] && prev === _win[++scan] &&
  3862. prev === _win[++scan] && prev === _win[++scan] &&
  3863. scan < strend);
  3864. s.match_length = MAX_MATCH - (strend - scan);
  3865. if (s.match_length > s.lookahead) {
  3866. s.match_length = s.lookahead;
  3867. }
  3868. }
  3869. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  3870. }
  3871. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  3872. if (s.match_length >= MIN_MATCH) {
  3873. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  3874. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  3875. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  3876. s.lookahead -= s.match_length;
  3877. s.strstart += s.match_length;
  3878. s.match_length = 0;
  3879. } else {
  3880. /* No match, output a literal byte */
  3881. //Tracevv((stderr,"%c", s->window[s->strstart]));
  3882. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  3883. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  3884. s.lookahead--;
  3885. s.strstart++;
  3886. }
  3887. if (bflush) {
  3888. /*** FLUSH_BLOCK(s, 0); ***/
  3889. flush_block_only(s, false);
  3890. if (s.strm.avail_out === 0) {
  3891. return BS_NEED_MORE;
  3892. }
  3893. /***/
  3894. }
  3895. }
  3896. s.insert = 0;
  3897. if (flush === Z_FINISH) {
  3898. /*** FLUSH_BLOCK(s, 1); ***/
  3899. flush_block_only(s, true);
  3900. if (s.strm.avail_out === 0) {
  3901. return BS_FINISH_STARTED;
  3902. }
  3903. /***/
  3904. return BS_FINISH_DONE;
  3905. }
  3906. if (s.last_lit) {
  3907. /*** FLUSH_BLOCK(s, 0); ***/
  3908. flush_block_only(s, false);
  3909. if (s.strm.avail_out === 0) {
  3910. return BS_NEED_MORE;
  3911. }
  3912. /***/
  3913. }
  3914. return BS_BLOCK_DONE;
  3915. }
  3916. /* ===========================================================================
  3917. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  3918. * (It will be regenerated if this run of deflate switches away from Huffman.)
  3919. */
  3920. function deflate_huff(s, flush) {
  3921. var bflush; /* set if current block must be flushed */
  3922. for (;;) {
  3923. /* Make sure that we have a literal to write. */
  3924. if (s.lookahead === 0) {
  3925. fill_window(s);
  3926. if (s.lookahead === 0) {
  3927. if (flush === Z_NO_FLUSH) {
  3928. return BS_NEED_MORE;
  3929. }
  3930. break; /* flush the current block */
  3931. }
  3932. }
  3933. /* Output a literal byte */
  3934. s.match_length = 0;
  3935. //Tracevv((stderr,"%c", s->window[s->strstart]));
  3936. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  3937. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  3938. s.lookahead--;
  3939. s.strstart++;
  3940. if (bflush) {
  3941. /*** FLUSH_BLOCK(s, 0); ***/
  3942. flush_block_only(s, false);
  3943. if (s.strm.avail_out === 0) {
  3944. return BS_NEED_MORE;
  3945. }
  3946. /***/
  3947. }
  3948. }
  3949. s.insert = 0;
  3950. if (flush === Z_FINISH) {
  3951. /*** FLUSH_BLOCK(s, 1); ***/
  3952. flush_block_only(s, true);
  3953. if (s.strm.avail_out === 0) {
  3954. return BS_FINISH_STARTED;
  3955. }
  3956. /***/
  3957. return BS_FINISH_DONE;
  3958. }
  3959. if (s.last_lit) {
  3960. /*** FLUSH_BLOCK(s, 0); ***/
  3961. flush_block_only(s, false);
  3962. if (s.strm.avail_out === 0) {
  3963. return BS_NEED_MORE;
  3964. }
  3965. /***/
  3966. }
  3967. return BS_BLOCK_DONE;
  3968. }
  3969. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  3970. * the desired pack level (0..9). The values given below have been tuned to
  3971. * exclude worst case performance for pathological files. Better values may be
  3972. * found for specific files.
  3973. */
  3974. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  3975. this.good_length = good_length;
  3976. this.max_lazy = max_lazy;
  3977. this.nice_length = nice_length;
  3978. this.max_chain = max_chain;
  3979. this.func = func;
  3980. }
  3981. var configuration_table;
  3982. configuration_table = [
  3983. /* good lazy nice chain */
  3984. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  3985. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  3986. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  3987. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  3988. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  3989. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  3990. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  3991. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  3992. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  3993. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  3994. ];
  3995. /* ===========================================================================
  3996. * Initialize the "longest match" routines for a new zlib stream
  3997. */
  3998. function lm_init(s) {
  3999. s.window_size = 2 * s.w_size;
  4000. /*** CLEAR_HASH(s); ***/
  4001. zero(s.head); // Fill with NIL (= 0);
  4002. /* Set the default configuration parameters:
  4003. */
  4004. s.max_lazy_match = configuration_table[s.level].max_lazy;
  4005. s.good_match = configuration_table[s.level].good_length;
  4006. s.nice_match = configuration_table[s.level].nice_length;
  4007. s.max_chain_length = configuration_table[s.level].max_chain;
  4008. s.strstart = 0;
  4009. s.block_start = 0;
  4010. s.lookahead = 0;
  4011. s.insert = 0;
  4012. s.match_length = s.prev_length = MIN_MATCH - 1;
  4013. s.match_available = 0;
  4014. s.ins_h = 0;
  4015. }
  4016. function DeflateState() {
  4017. this.strm = null; /* pointer back to this zlib stream */
  4018. this.status = 0; /* as the name implies */
  4019. this.pending_buf = null; /* output still pending */
  4020. this.pending_buf_size = 0; /* size of pending_buf */
  4021. this.pending_out = 0; /* next pending byte to output to the stream */
  4022. this.pending = 0; /* nb of bytes in the pending buffer */
  4023. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  4024. this.gzhead = null; /* gzip header information to write */
  4025. this.gzindex = 0; /* where in extra, name, or comment */
  4026. this.method = Z_DEFLATED; /* can only be DEFLATED */
  4027. this.last_flush = -1; /* value of flush param for previous deflate call */
  4028. this.w_size = 0; /* LZ77 window size (32K by default) */
  4029. this.w_bits = 0; /* log2(w_size) (8..16) */
  4030. this.w_mask = 0; /* w_size - 1 */
  4031. this.window = null;
  4032. /* Sliding window. Input bytes are read into the second half of the window,
  4033. * and move to the first half later to keep a dictionary of at least wSize
  4034. * bytes. With this organization, matches are limited to a distance of
  4035. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  4036. * performed with a length multiple of the block size.
  4037. */
  4038. this.window_size = 0;
  4039. /* Actual size of window: 2*wSize, except when the user input buffer
  4040. * is directly used as sliding window.
  4041. */
  4042. this.prev = null;
  4043. /* Link to older string with same hash index. To limit the size of this
  4044. * array to 64K, this link is maintained only for the last 32K strings.
  4045. * An index in this array is thus a window index modulo 32K.
  4046. */
  4047. this.head = null; /* Heads of the hash chains or NIL. */
  4048. this.ins_h = 0; /* hash index of string to be inserted */
  4049. this.hash_size = 0; /* number of elements in hash table */
  4050. this.hash_bits = 0; /* log2(hash_size) */
  4051. this.hash_mask = 0; /* hash_size-1 */
  4052. this.hash_shift = 0;
  4053. /* Number of bits by which ins_h must be shifted at each input
  4054. * step. It must be such that after MIN_MATCH steps, the oldest
  4055. * byte no longer takes part in the hash key, that is:
  4056. * hash_shift * MIN_MATCH >= hash_bits
  4057. */
  4058. this.block_start = 0;
  4059. /* Window position at the beginning of the current output block. Gets
  4060. * negative when the window is moved backwards.
  4061. */
  4062. this.match_length = 0; /* length of best match */
  4063. this.prev_match = 0; /* previous match */
  4064. this.match_available = 0; /* set if previous match exists */
  4065. this.strstart = 0; /* start of string to insert */
  4066. this.match_start = 0; /* start of matching string */
  4067. this.lookahead = 0; /* number of valid bytes ahead in window */
  4068. this.prev_length = 0;
  4069. /* Length of the best match at previous step. Matches not greater than this
  4070. * are discarded. This is used in the lazy match evaluation.
  4071. */
  4072. this.max_chain_length = 0;
  4073. /* To speed up deflation, hash chains are never searched beyond this
  4074. * length. A higher limit improves compression ratio but degrades the
  4075. * speed.
  4076. */
  4077. this.max_lazy_match = 0;
  4078. /* Attempt to find a better match only when the current match is strictly
  4079. * smaller than this value. This mechanism is used only for compression
  4080. * levels >= 4.
  4081. */
  4082. // That's alias to max_lazy_match, don't use directly
  4083. //this.max_insert_length = 0;
  4084. /* Insert new strings in the hash table only if the match length is not
  4085. * greater than this length. This saves time but degrades compression.
  4086. * max_insert_length is used only for compression levels <= 3.
  4087. */
  4088. this.level = 0; /* compression level (1..9) */
  4089. this.strategy = 0; /* favor or force Huffman coding*/
  4090. this.good_match = 0;
  4091. /* Use a faster search when the previous match is longer than this */
  4092. this.nice_match = 0; /* Stop searching when current match exceeds this */
  4093. /* used by trees.c: */
  4094. /* Didn't use ct_data typedef below to suppress compiler warning */
  4095. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  4096. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  4097. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  4098. // Use flat array of DOUBLE size, with interleaved fata,
  4099. // because JS does not support effective
  4100. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  4101. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  4102. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  4103. zero(this.dyn_ltree);
  4104. zero(this.dyn_dtree);
  4105. zero(this.bl_tree);
  4106. this.l_desc = null; /* desc. for literal tree */
  4107. this.d_desc = null; /* desc. for distance tree */
  4108. this.bl_desc = null; /* desc. for bit length tree */
  4109. //ush bl_count[MAX_BITS+1];
  4110. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  4111. /* number of codes at each bit length for an optimal tree */
  4112. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  4113. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  4114. zero(this.heap);
  4115. this.heap_len = 0; /* number of elements in the heap */
  4116. this.heap_max = 0; /* element of largest frequency */
  4117. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  4118. * The same heap array is used to build all trees.
  4119. */
  4120. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  4121. zero(this.depth);
  4122. /* Depth of each subtree used as tie breaker for trees of equal frequency
  4123. */
  4124. this.l_buf = 0; /* buffer index for literals or lengths */
  4125. this.lit_bufsize = 0;
  4126. /* Size of match buffer for literals/lengths. There are 4 reasons for
  4127. * limiting lit_bufsize to 64K:
  4128. * - frequencies can be kept in 16 bit counters
  4129. * - if compression is not successful for the first block, all input
  4130. * data is still in the window so we can still emit a stored block even
  4131. * when input comes from standard input. (This can also be done for
  4132. * all blocks if lit_bufsize is not greater than 32K.)
  4133. * - if compression is not successful for a file smaller than 64K, we can
  4134. * even emit a stored file instead of a stored block (saving 5 bytes).
  4135. * This is applicable only for zip (not gzip or zlib).
  4136. * - creating new Huffman trees less frequently may not provide fast
  4137. * adaptation to changes in the input data statistics. (Take for
  4138. * example a binary file with poorly compressible code followed by
  4139. * a highly compressible string table.) Smaller buffer sizes give
  4140. * fast adaptation but have of course the overhead of transmitting
  4141. * trees more frequently.
  4142. * - I can't count above 4
  4143. */
  4144. this.last_lit = 0; /* running index in l_buf */
  4145. this.d_buf = 0;
  4146. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  4147. * the same number of elements. To use different lengths, an extra flag
  4148. * array would be necessary.
  4149. */
  4150. this.opt_len = 0; /* bit length of current block with optimal trees */
  4151. this.static_len = 0; /* bit length of current block with static trees */
  4152. this.matches = 0; /* number of string matches in current block */
  4153. this.insert = 0; /* bytes at end of window left to insert */
  4154. this.bi_buf = 0;
  4155. /* Output buffer. bits are inserted starting at the bottom (least
  4156. * significant bits).
  4157. */
  4158. this.bi_valid = 0;
  4159. /* Number of valid bits in bi_buf. All bits above the last valid bit
  4160. * are always zero.
  4161. */
  4162. // Used for window memory init. We safely ignore it for JS. That makes
  4163. // sense only for pointers and memory check tools.
  4164. //this.high_water = 0;
  4165. /* High water mark offset in window for initialized bytes -- bytes above
  4166. * this are set to zero in order to avoid memory check warnings when
  4167. * longest match routines access bytes past the input. This is then
  4168. * updated to the new high water mark.
  4169. */
  4170. }
  4171. function deflateResetKeep(strm) {
  4172. var s;
  4173. if (!strm || !strm.state) {
  4174. return err(strm, Z_STREAM_ERROR);
  4175. }
  4176. strm.total_in = strm.total_out = 0;
  4177. strm.data_type = Z_UNKNOWN;
  4178. s = strm.state;
  4179. s.pending = 0;
  4180. s.pending_out = 0;
  4181. if (s.wrap < 0) {
  4182. s.wrap = -s.wrap;
  4183. /* was made negative by deflate(..., Z_FINISH); */
  4184. }
  4185. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  4186. strm.adler = (s.wrap === 2) ?
  4187. 0 // crc32(0, Z_NULL, 0)
  4188. :
  4189. 1; // adler32(0, Z_NULL, 0)
  4190. s.last_flush = Z_NO_FLUSH;
  4191. trees._tr_init(s);
  4192. return Z_OK;
  4193. }
  4194. function deflateReset(strm) {
  4195. var ret = deflateResetKeep(strm);
  4196. if (ret === Z_OK) {
  4197. lm_init(strm.state);
  4198. }
  4199. return ret;
  4200. }
  4201. function deflateSetHeader(strm, head) {
  4202. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  4203. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  4204. strm.state.gzhead = head;
  4205. return Z_OK;
  4206. }
  4207. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  4208. if (!strm) { // === Z_NULL
  4209. return Z_STREAM_ERROR;
  4210. }
  4211. var wrap = 1;
  4212. if (level === Z_DEFAULT_COMPRESSION) {
  4213. level = 6;
  4214. }
  4215. if (windowBits < 0) { /* suppress zlib wrapper */
  4216. wrap = 0;
  4217. windowBits = -windowBits;
  4218. }
  4219. else if (windowBits > 15) {
  4220. wrap = 2; /* write gzip wrapper instead */
  4221. windowBits -= 16;
  4222. }
  4223. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  4224. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  4225. strategy < 0 || strategy > Z_FIXED) {
  4226. return err(strm, Z_STREAM_ERROR);
  4227. }
  4228. if (windowBits === 8) {
  4229. windowBits = 9;
  4230. }
  4231. /* until 256-byte window bug fixed */
  4232. var s = new DeflateState();
  4233. strm.state = s;
  4234. s.strm = strm;
  4235. s.wrap = wrap;
  4236. s.gzhead = null;
  4237. s.w_bits = windowBits;
  4238. s.w_size = 1 << s.w_bits;
  4239. s.w_mask = s.w_size - 1;
  4240. s.hash_bits = memLevel + 7;
  4241. s.hash_size = 1 << s.hash_bits;
  4242. s.hash_mask = s.hash_size - 1;
  4243. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  4244. s.window = new utils.Buf8(s.w_size * 2);
  4245. s.head = new utils.Buf16(s.hash_size);
  4246. s.prev = new utils.Buf16(s.w_size);
  4247. // Don't need mem init magic for JS.
  4248. //s.high_water = 0; /* nothing written to s->window yet */
  4249. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  4250. s.pending_buf_size = s.lit_bufsize * 4;
  4251. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  4252. //s->pending_buf = (uchf *) overlay;
  4253. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  4254. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  4255. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  4256. s.d_buf = 1 * s.lit_bufsize;
  4257. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  4258. s.l_buf = (1 + 2) * s.lit_bufsize;
  4259. s.level = level;
  4260. s.strategy = strategy;
  4261. s.method = method;
  4262. return deflateReset(strm);
  4263. }
  4264. function deflateInit(strm, level) {
  4265. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  4266. }
  4267. function deflate(strm, flush) {
  4268. var old_flush, s;
  4269. var beg, val; // for gzip header write only
  4270. if (!strm || !strm.state ||
  4271. flush > Z_BLOCK || flush < 0) {
  4272. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  4273. }
  4274. s = strm.state;
  4275. if (!strm.output ||
  4276. (!strm.input && strm.avail_in !== 0) ||
  4277. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  4278. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  4279. }
  4280. s.strm = strm; /* just in case */
  4281. old_flush = s.last_flush;
  4282. s.last_flush = flush;
  4283. /* Write the header */
  4284. if (s.status === INIT_STATE) {
  4285. if (s.wrap === 2) { // GZIP header
  4286. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4287. put_byte(s, 31);
  4288. put_byte(s, 139);
  4289. put_byte(s, 8);
  4290. if (!s.gzhead) { // s->gzhead == Z_NULL
  4291. put_byte(s, 0);
  4292. put_byte(s, 0);
  4293. put_byte(s, 0);
  4294. put_byte(s, 0);
  4295. put_byte(s, 0);
  4296. put_byte(s, s.level === 9 ? 2 :
  4297. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4298. 4 : 0));
  4299. put_byte(s, OS_CODE);
  4300. s.status = BUSY_STATE;
  4301. }
  4302. else {
  4303. put_byte(s, (s.gzhead.text ? 1 : 0) +
  4304. (s.gzhead.hcrc ? 2 : 0) +
  4305. (!s.gzhead.extra ? 0 : 4) +
  4306. (!s.gzhead.name ? 0 : 8) +
  4307. (!s.gzhead.comment ? 0 : 16)
  4308. );
  4309. put_byte(s, s.gzhead.time & 0xff);
  4310. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  4311. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  4312. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  4313. put_byte(s, s.level === 9 ? 2 :
  4314. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4315. 4 : 0));
  4316. put_byte(s, s.gzhead.os & 0xff);
  4317. if (s.gzhead.extra && s.gzhead.extra.length) {
  4318. put_byte(s, s.gzhead.extra.length & 0xff);
  4319. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  4320. }
  4321. if (s.gzhead.hcrc) {
  4322. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  4323. }
  4324. s.gzindex = 0;
  4325. s.status = EXTRA_STATE;
  4326. }
  4327. }
  4328. else // DEFLATE header
  4329. {
  4330. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  4331. var level_flags = -1;
  4332. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  4333. level_flags = 0;
  4334. } else if (s.level < 6) {
  4335. level_flags = 1;
  4336. } else if (s.level === 6) {
  4337. level_flags = 2;
  4338. } else {
  4339. level_flags = 3;
  4340. }
  4341. header |= (level_flags << 6);
  4342. if (s.strstart !== 0) { header |= PRESET_DICT; }
  4343. header += 31 - (header % 31);
  4344. s.status = BUSY_STATE;
  4345. putShortMSB(s, header);
  4346. /* Save the adler32 of the preset dictionary: */
  4347. if (s.strstart !== 0) {
  4348. putShortMSB(s, strm.adler >>> 16);
  4349. putShortMSB(s, strm.adler & 0xffff);
  4350. }
  4351. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  4352. }
  4353. }
  4354. //#ifdef GZIP
  4355. if (s.status === EXTRA_STATE) {
  4356. if (s.gzhead.extra/* != Z_NULL*/) {
  4357. beg = s.pending; /* start of bytes to update crc */
  4358. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  4359. if (s.pending === s.pending_buf_size) {
  4360. if (s.gzhead.hcrc && s.pending > beg) {
  4361. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4362. }
  4363. flush_pending(strm);
  4364. beg = s.pending;
  4365. if (s.pending === s.pending_buf_size) {
  4366. break;
  4367. }
  4368. }
  4369. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  4370. s.gzindex++;
  4371. }
  4372. if (s.gzhead.hcrc && s.pending > beg) {
  4373. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4374. }
  4375. if (s.gzindex === s.gzhead.extra.length) {
  4376. s.gzindex = 0;
  4377. s.status = NAME_STATE;
  4378. }
  4379. }
  4380. else {
  4381. s.status = NAME_STATE;
  4382. }
  4383. }
  4384. if (s.status === NAME_STATE) {
  4385. if (s.gzhead.name/* != Z_NULL*/) {
  4386. beg = s.pending; /* start of bytes to update crc */
  4387. //int val;
  4388. do {
  4389. if (s.pending === s.pending_buf_size) {
  4390. if (s.gzhead.hcrc && s.pending > beg) {
  4391. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4392. }
  4393. flush_pending(strm);
  4394. beg = s.pending;
  4395. if (s.pending === s.pending_buf_size) {
  4396. val = 1;
  4397. break;
  4398. }
  4399. }
  4400. // JS specific: little magic to add zero terminator to end of string
  4401. if (s.gzindex < s.gzhead.name.length) {
  4402. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  4403. } else {
  4404. val = 0;
  4405. }
  4406. put_byte(s, val);
  4407. } while (val !== 0);
  4408. if (s.gzhead.hcrc && s.pending > beg) {
  4409. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4410. }
  4411. if (val === 0) {
  4412. s.gzindex = 0;
  4413. s.status = COMMENT_STATE;
  4414. }
  4415. }
  4416. else {
  4417. s.status = COMMENT_STATE;
  4418. }
  4419. }
  4420. if (s.status === COMMENT_STATE) {
  4421. if (s.gzhead.comment/* != Z_NULL*/) {
  4422. beg = s.pending; /* start of bytes to update crc */
  4423. //int val;
  4424. do {
  4425. if (s.pending === s.pending_buf_size) {
  4426. if (s.gzhead.hcrc && s.pending > beg) {
  4427. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4428. }
  4429. flush_pending(strm);
  4430. beg = s.pending;
  4431. if (s.pending === s.pending_buf_size) {
  4432. val = 1;
  4433. break;
  4434. }
  4435. }
  4436. // JS specific: little magic to add zero terminator to end of string
  4437. if (s.gzindex < s.gzhead.comment.length) {
  4438. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  4439. } else {
  4440. val = 0;
  4441. }
  4442. put_byte(s, val);
  4443. } while (val !== 0);
  4444. if (s.gzhead.hcrc && s.pending > beg) {
  4445. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4446. }
  4447. if (val === 0) {
  4448. s.status = HCRC_STATE;
  4449. }
  4450. }
  4451. else {
  4452. s.status = HCRC_STATE;
  4453. }
  4454. }
  4455. if (s.status === HCRC_STATE) {
  4456. if (s.gzhead.hcrc) {
  4457. if (s.pending + 2 > s.pending_buf_size) {
  4458. flush_pending(strm);
  4459. }
  4460. if (s.pending + 2 <= s.pending_buf_size) {
  4461. put_byte(s, strm.adler & 0xff);
  4462. put_byte(s, (strm.adler >> 8) & 0xff);
  4463. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4464. s.status = BUSY_STATE;
  4465. }
  4466. }
  4467. else {
  4468. s.status = BUSY_STATE;
  4469. }
  4470. }
  4471. //#endif
  4472. /* Flush as much pending output as possible */
  4473. if (s.pending !== 0) {
  4474. flush_pending(strm);
  4475. if (strm.avail_out === 0) {
  4476. /* Since avail_out is 0, deflate will be called again with
  4477. * more output space, but possibly with both pending and
  4478. * avail_in equal to zero. There won't be anything to do,
  4479. * but this is not an error situation so make sure we
  4480. * return OK instead of BUF_ERROR at next call of deflate:
  4481. */
  4482. s.last_flush = -1;
  4483. return Z_OK;
  4484. }
  4485. /* Make sure there is something to do and avoid duplicate consecutive
  4486. * flushes. For repeated and useless calls with Z_FINISH, we keep
  4487. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  4488. */
  4489. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  4490. flush !== Z_FINISH) {
  4491. return err(strm, Z_BUF_ERROR);
  4492. }
  4493. /* User must not provide more input after the first FINISH: */
  4494. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  4495. return err(strm, Z_BUF_ERROR);
  4496. }
  4497. /* Start a new block or continue the current one.
  4498. */
  4499. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  4500. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  4501. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  4502. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  4503. configuration_table[s.level].func(s, flush));
  4504. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  4505. s.status = FINISH_STATE;
  4506. }
  4507. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  4508. if (strm.avail_out === 0) {
  4509. s.last_flush = -1;
  4510. /* avoid BUF_ERROR next call, see above */
  4511. }
  4512. return Z_OK;
  4513. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  4514. * of deflate should use the same flush parameter to make sure
  4515. * that the flush is complete. So we don't have to output an
  4516. * empty block here, this will be done at next call. This also
  4517. * ensures that for a very small output buffer, we emit at most
  4518. * one empty block.
  4519. */
  4520. }
  4521. if (bstate === BS_BLOCK_DONE) {
  4522. if (flush === Z_PARTIAL_FLUSH) {
  4523. trees._tr_align(s);
  4524. }
  4525. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  4526. trees._tr_stored_block(s, 0, 0, false);
  4527. /* For a full flush, this empty block will be recognized
  4528. * as a special marker by inflate_sync().
  4529. */
  4530. if (flush === Z_FULL_FLUSH) {
  4531. /*** CLEAR_HASH(s); ***/ /* forget history */
  4532. zero(s.head); // Fill with NIL (= 0);
  4533. if (s.lookahead === 0) {
  4534. s.strstart = 0;
  4535. s.block_start = 0;
  4536. s.insert = 0;
  4537. }
  4538. }
  4539. }
  4540. flush_pending(strm);
  4541. if (strm.avail_out === 0) {
  4542. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  4543. return Z_OK;
  4544. }
  4545. }
  4546. }
  4547. //Assert(strm->avail_out > 0, "bug2");
  4548. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  4549. if (flush !== Z_FINISH) { return Z_OK; }
  4550. if (s.wrap <= 0) { return Z_STREAM_END; }
  4551. /* Write the trailer */
  4552. if (s.wrap === 2) {
  4553. put_byte(s, strm.adler & 0xff);
  4554. put_byte(s, (strm.adler >> 8) & 0xff);
  4555. put_byte(s, (strm.adler >> 16) & 0xff);
  4556. put_byte(s, (strm.adler >> 24) & 0xff);
  4557. put_byte(s, strm.total_in & 0xff);
  4558. put_byte(s, (strm.total_in >> 8) & 0xff);
  4559. put_byte(s, (strm.total_in >> 16) & 0xff);
  4560. put_byte(s, (strm.total_in >> 24) & 0xff);
  4561. }
  4562. else
  4563. {
  4564. putShortMSB(s, strm.adler >>> 16);
  4565. putShortMSB(s, strm.adler & 0xffff);
  4566. }
  4567. flush_pending(strm);
  4568. /* If avail_out is zero, the application will call deflate again
  4569. * to flush the rest.
  4570. */
  4571. if (s.wrap > 0) { s.wrap = -s.wrap; }
  4572. /* write the trailer only once! */
  4573. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  4574. }
  4575. function deflateEnd(strm) {
  4576. var status;
  4577. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  4578. return Z_STREAM_ERROR;
  4579. }
  4580. status = strm.state.status;
  4581. if (status !== INIT_STATE &&
  4582. status !== EXTRA_STATE &&
  4583. status !== NAME_STATE &&
  4584. status !== COMMENT_STATE &&
  4585. status !== HCRC_STATE &&
  4586. status !== BUSY_STATE &&
  4587. status !== FINISH_STATE
  4588. ) {
  4589. return err(strm, Z_STREAM_ERROR);
  4590. }
  4591. strm.state = null;
  4592. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  4593. }
  4594. /* =========================================================================
  4595. * Initializes the compression dictionary from the given byte
  4596. * sequence without producing any compressed output.
  4597. */
  4598. function deflateSetDictionary(strm, dictionary) {
  4599. var dictLength = dictionary.length;
  4600. var s;
  4601. var str, n;
  4602. var wrap;
  4603. var avail;
  4604. var next;
  4605. var input;
  4606. var tmpDict;
  4607. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  4608. return Z_STREAM_ERROR;
  4609. }
  4610. s = strm.state;
  4611. wrap = s.wrap;
  4612. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  4613. return Z_STREAM_ERROR;
  4614. }
  4615. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  4616. if (wrap === 1) {
  4617. /* adler32(strm->adler, dictionary, dictLength); */
  4618. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  4619. }
  4620. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  4621. /* if dictionary would fill window, just replace the history */
  4622. if (dictLength >= s.w_size) {
  4623. if (wrap === 0) { /* already empty otherwise */
  4624. /*** CLEAR_HASH(s); ***/
  4625. zero(s.head); // Fill with NIL (= 0);
  4626. s.strstart = 0;
  4627. s.block_start = 0;
  4628. s.insert = 0;
  4629. }
  4630. /* use the tail */
  4631. // dictionary = dictionary.slice(dictLength - s.w_size);
  4632. tmpDict = new utils.Buf8(s.w_size);
  4633. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  4634. dictionary = tmpDict;
  4635. dictLength = s.w_size;
  4636. }
  4637. /* insert dictionary into window and hash */
  4638. avail = strm.avail_in;
  4639. next = strm.next_in;
  4640. input = strm.input;
  4641. strm.avail_in = dictLength;
  4642. strm.next_in = 0;
  4643. strm.input = dictionary;
  4644. fill_window(s);
  4645. while (s.lookahead >= MIN_MATCH) {
  4646. str = s.strstart;
  4647. n = s.lookahead - (MIN_MATCH - 1);
  4648. do {
  4649. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  4650. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  4651. s.prev[str & s.w_mask] = s.head[s.ins_h];
  4652. s.head[s.ins_h] = str;
  4653. str++;
  4654. } while (--n);
  4655. s.strstart = str;
  4656. s.lookahead = MIN_MATCH - 1;
  4657. fill_window(s);
  4658. }
  4659. s.strstart += s.lookahead;
  4660. s.block_start = s.strstart;
  4661. s.insert = s.lookahead;
  4662. s.lookahead = 0;
  4663. s.match_length = s.prev_length = MIN_MATCH - 1;
  4664. s.match_available = 0;
  4665. strm.next_in = next;
  4666. strm.input = input;
  4667. strm.avail_in = avail;
  4668. s.wrap = wrap;
  4669. return Z_OK;
  4670. }
  4671. exports.deflateInit = deflateInit;
  4672. exports.deflateInit2 = deflateInit2;
  4673. exports.deflateReset = deflateReset;
  4674. exports.deflateResetKeep = deflateResetKeep;
  4675. exports.deflateSetHeader = deflateSetHeader;
  4676. exports.deflate = deflate;
  4677. exports.deflateEnd = deflateEnd;
  4678. exports.deflateSetDictionary = deflateSetDictionary;
  4679. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  4680. /* Not implemented
  4681. exports.deflateBound = deflateBound;
  4682. exports.deflateCopy = deflateCopy;
  4683. exports.deflateParams = deflateParams;
  4684. exports.deflatePending = deflatePending;
  4685. exports.deflatePrime = deflatePrime;
  4686. exports.deflateTune = deflateTune;
  4687. */
  4688. },{"../utils/common":35,"./adler32":36,"./crc32":38,"./messages":43,"./trees":44}],40:[function(require,module,exports){
  4689. 'use strict';
  4690. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  4691. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  4692. //
  4693. // This software is provided 'as-is', without any express or implied
  4694. // warranty. In no event will the authors be held liable for any damages
  4695. // arising from the use of this software.
  4696. //
  4697. // Permission is granted to anyone to use this software for any purpose,
  4698. // including commercial applications, and to alter it and redistribute it
  4699. // freely, subject to the following restrictions:
  4700. //
  4701. // 1. The origin of this software must not be misrepresented; you must not
  4702. // claim that you wrote the original software. If you use this software
  4703. // in a product, an acknowledgment in the product documentation would be
  4704. // appreciated but is not required.
  4705. // 2. Altered source versions must be plainly marked as such, and must not be
  4706. // misrepresented as being the original software.
  4707. // 3. This notice may not be removed or altered from any source distribution.
  4708. // See state defs from inflate.js
  4709. var BAD = 30; /* got a data error -- remain here until reset */
  4710. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  4711. /*
  4712. Decode literal, length, and distance codes and write out the resulting
  4713. literal and match bytes until either not enough input or output is
  4714. available, an end-of-block is encountered, or a data error is encountered.
  4715. When large enough input and output buffers are supplied to inflate(), for
  4716. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  4717. inflate execution time is spent in this routine.
  4718. Entry assumptions:
  4719. state.mode === LEN
  4720. strm.avail_in >= 6
  4721. strm.avail_out >= 258
  4722. start >= strm.avail_out
  4723. state.bits < 8
  4724. On return, state.mode is one of:
  4725. LEN -- ran out of enough output space or enough available input
  4726. TYPE -- reached end of block code, inflate() to interpret next block
  4727. BAD -- error in block data
  4728. Notes:
  4729. - The maximum input bits used by a length/distance pair is 15 bits for the
  4730. length code, 5 bits for the length extra, 15 bits for the distance code,
  4731. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  4732. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  4733. checking for available input while decoding.
  4734. - The maximum bytes that a single length/distance pair can output is 258
  4735. bytes, which is the maximum length that can be coded. inflate_fast()
  4736. requires strm.avail_out >= 258 for each loop to avoid checking for
  4737. output space.
  4738. */
  4739. module.exports = function inflate_fast(strm, start) {
  4740. var state;
  4741. var _in; /* local strm.input */
  4742. var last; /* have enough input while in < last */
  4743. var _out; /* local strm.output */
  4744. var beg; /* inflate()'s initial strm.output */
  4745. var end; /* while out < end, enough space available */
  4746. //#ifdef INFLATE_STRICT
  4747. var dmax; /* maximum distance from zlib header */
  4748. //#endif
  4749. var wsize; /* window size or zero if not using window */
  4750. var whave; /* valid bytes in the window */
  4751. var wnext; /* window write index */
  4752. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  4753. var s_window; /* allocated sliding window, if wsize != 0 */
  4754. var hold; /* local strm.hold */
  4755. var bits; /* local strm.bits */
  4756. var lcode; /* local strm.lencode */
  4757. var dcode; /* local strm.distcode */
  4758. var lmask; /* mask for first level of length codes */
  4759. var dmask; /* mask for first level of distance codes */
  4760. var here; /* retrieved table entry */
  4761. var op; /* code bits, operation, extra bits, or */
  4762. /* window position, window bytes to copy */
  4763. var len; /* match length, unused bytes */
  4764. var dist; /* match distance */
  4765. var from; /* where to copy match from */
  4766. var from_source;
  4767. var input, output; // JS specific, because we have no pointers
  4768. /* copy state to local variables */
  4769. state = strm.state;
  4770. //here = state.here;
  4771. _in = strm.next_in;
  4772. input = strm.input;
  4773. last = _in + (strm.avail_in - 5);
  4774. _out = strm.next_out;
  4775. output = strm.output;
  4776. beg = _out - (start - strm.avail_out);
  4777. end = _out + (strm.avail_out - 257);
  4778. //#ifdef INFLATE_STRICT
  4779. dmax = state.dmax;
  4780. //#endif
  4781. wsize = state.wsize;
  4782. whave = state.whave;
  4783. wnext = state.wnext;
  4784. s_window = state.window;
  4785. hold = state.hold;
  4786. bits = state.bits;
  4787. lcode = state.lencode;
  4788. dcode = state.distcode;
  4789. lmask = (1 << state.lenbits) - 1;
  4790. dmask = (1 << state.distbits) - 1;
  4791. /* decode literals and length/distances until end-of-block or not enough
  4792. input data or output space */
  4793. top:
  4794. do {
  4795. if (bits < 15) {
  4796. hold += input[_in++] << bits;
  4797. bits += 8;
  4798. hold += input[_in++] << bits;
  4799. bits += 8;
  4800. }
  4801. here = lcode[hold & lmask];
  4802. dolen:
  4803. for (;;) { // Goto emulation
  4804. op = here >>> 24/*here.bits*/;
  4805. hold >>>= op;
  4806. bits -= op;
  4807. op = (here >>> 16) & 0xff/*here.op*/;
  4808. if (op === 0) { /* literal */
  4809. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  4810. // "inflate: literal '%c'\n" :
  4811. // "inflate: literal 0x%02x\n", here.val));
  4812. output[_out++] = here & 0xffff/*here.val*/;
  4813. }
  4814. else if (op & 16) { /* length base */
  4815. len = here & 0xffff/*here.val*/;
  4816. op &= 15; /* number of extra bits */
  4817. if (op) {
  4818. if (bits < op) {
  4819. hold += input[_in++] << bits;
  4820. bits += 8;
  4821. }
  4822. len += hold & ((1 << op) - 1);
  4823. hold >>>= op;
  4824. bits -= op;
  4825. }
  4826. //Tracevv((stderr, "inflate: length %u\n", len));
  4827. if (bits < 15) {
  4828. hold += input[_in++] << bits;
  4829. bits += 8;
  4830. hold += input[_in++] << bits;
  4831. bits += 8;
  4832. }
  4833. here = dcode[hold & dmask];
  4834. dodist:
  4835. for (;;) { // goto emulation
  4836. op = here >>> 24/*here.bits*/;
  4837. hold >>>= op;
  4838. bits -= op;
  4839. op = (here >>> 16) & 0xff/*here.op*/;
  4840. if (op & 16) { /* distance base */
  4841. dist = here & 0xffff/*here.val*/;
  4842. op &= 15; /* number of extra bits */
  4843. if (bits < op) {
  4844. hold += input[_in++] << bits;
  4845. bits += 8;
  4846. if (bits < op) {
  4847. hold += input[_in++] << bits;
  4848. bits += 8;
  4849. }
  4850. }
  4851. dist += hold & ((1 << op) - 1);
  4852. //#ifdef INFLATE_STRICT
  4853. if (dist > dmax) {
  4854. strm.msg = 'invalid distance too far back';
  4855. state.mode = BAD;
  4856. break top;
  4857. }
  4858. //#endif
  4859. hold >>>= op;
  4860. bits -= op;
  4861. //Tracevv((stderr, "inflate: distance %u\n", dist));
  4862. op = _out - beg; /* max distance in output */
  4863. if (dist > op) { /* see if copy from window */
  4864. op = dist - op; /* distance back in window */
  4865. if (op > whave) {
  4866. if (state.sane) {
  4867. strm.msg = 'invalid distance too far back';
  4868. state.mode = BAD;
  4869. break top;
  4870. }
  4871. // (!) This block is disabled in zlib defaults,
  4872. // don't enable it for binary compatibility
  4873. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  4874. // if (len <= op - whave) {
  4875. // do {
  4876. // output[_out++] = 0;
  4877. // } while (--len);
  4878. // continue top;
  4879. // }
  4880. // len -= op - whave;
  4881. // do {
  4882. // output[_out++] = 0;
  4883. // } while (--op > whave);
  4884. // if (op === 0) {
  4885. // from = _out - dist;
  4886. // do {
  4887. // output[_out++] = output[from++];
  4888. // } while (--len);
  4889. // continue top;
  4890. // }
  4891. //#endif
  4892. }
  4893. from = 0; // window index
  4894. from_source = s_window;
  4895. if (wnext === 0) { /* very common case */
  4896. from += wsize - op;
  4897. if (op < len) { /* some from window */
  4898. len -= op;
  4899. do {
  4900. output[_out++] = s_window[from++];
  4901. } while (--op);
  4902. from = _out - dist; /* rest from output */
  4903. from_source = output;
  4904. }
  4905. }
  4906. else if (wnext < op) { /* wrap around window */
  4907. from += wsize + wnext - op;
  4908. op -= wnext;
  4909. if (op < len) { /* some from end of window */
  4910. len -= op;
  4911. do {
  4912. output[_out++] = s_window[from++];
  4913. } while (--op);
  4914. from = 0;
  4915. if (wnext < len) { /* some from start of window */
  4916. op = wnext;
  4917. len -= op;
  4918. do {
  4919. output[_out++] = s_window[from++];
  4920. } while (--op);
  4921. from = _out - dist; /* rest from output */
  4922. from_source = output;
  4923. }
  4924. }
  4925. }
  4926. else { /* contiguous in window */
  4927. from += wnext - op;
  4928. if (op < len) { /* some from window */
  4929. len -= op;
  4930. do {
  4931. output[_out++] = s_window[from++];
  4932. } while (--op);
  4933. from = _out - dist; /* rest from output */
  4934. from_source = output;
  4935. }
  4936. }
  4937. while (len > 2) {
  4938. output[_out++] = from_source[from++];
  4939. output[_out++] = from_source[from++];
  4940. output[_out++] = from_source[from++];
  4941. len -= 3;
  4942. }
  4943. if (len) {
  4944. output[_out++] = from_source[from++];
  4945. if (len > 1) {
  4946. output[_out++] = from_source[from++];
  4947. }
  4948. }
  4949. }
  4950. else {
  4951. from = _out - dist; /* copy direct from output */
  4952. do { /* minimum length is three */
  4953. output[_out++] = output[from++];
  4954. output[_out++] = output[from++];
  4955. output[_out++] = output[from++];
  4956. len -= 3;
  4957. } while (len > 2);
  4958. if (len) {
  4959. output[_out++] = output[from++];
  4960. if (len > 1) {
  4961. output[_out++] = output[from++];
  4962. }
  4963. }
  4964. }
  4965. }
  4966. else if ((op & 64) === 0) { /* 2nd level distance code */
  4967. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  4968. continue dodist;
  4969. }
  4970. else {
  4971. strm.msg = 'invalid distance code';
  4972. state.mode = BAD;
  4973. break top;
  4974. }
  4975. break; // need to emulate goto via "continue"
  4976. }
  4977. }
  4978. else if ((op & 64) === 0) { /* 2nd level length code */
  4979. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  4980. continue dolen;
  4981. }
  4982. else if (op & 32) { /* end-of-block */
  4983. //Tracevv((stderr, "inflate: end of block\n"));
  4984. state.mode = TYPE;
  4985. break top;
  4986. }
  4987. else {
  4988. strm.msg = 'invalid literal/length code';
  4989. state.mode = BAD;
  4990. break top;
  4991. }
  4992. break; // need to emulate goto via "continue"
  4993. }
  4994. } while (_in < last && _out < end);
  4995. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  4996. len = bits >> 3;
  4997. _in -= len;
  4998. bits -= len << 3;
  4999. hold &= (1 << bits) - 1;
  5000. /* update state and return */
  5001. strm.next_in = _in;
  5002. strm.next_out = _out;
  5003. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  5004. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  5005. state.hold = hold;
  5006. state.bits = bits;
  5007. return;
  5008. };
  5009. },{}],41:[function(require,module,exports){
  5010. 'use strict';
  5011. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5012. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5013. //
  5014. // This software is provided 'as-is', without any express or implied
  5015. // warranty. In no event will the authors be held liable for any damages
  5016. // arising from the use of this software.
  5017. //
  5018. // Permission is granted to anyone to use this software for any purpose,
  5019. // including commercial applications, and to alter it and redistribute it
  5020. // freely, subject to the following restrictions:
  5021. //
  5022. // 1. The origin of this software must not be misrepresented; you must not
  5023. // claim that you wrote the original software. If you use this software
  5024. // in a product, an acknowledgment in the product documentation would be
  5025. // appreciated but is not required.
  5026. // 2. Altered source versions must be plainly marked as such, and must not be
  5027. // misrepresented as being the original software.
  5028. // 3. This notice may not be removed or altered from any source distribution.
  5029. var utils = require('../utils/common');
  5030. var adler32 = require('./adler32');
  5031. var crc32 = require('./crc32');
  5032. var inflate_fast = require('./inffast');
  5033. var inflate_table = require('./inftrees');
  5034. var CODES = 0;
  5035. var LENS = 1;
  5036. var DISTS = 2;
  5037. /* Public constants ==========================================================*/
  5038. /* ===========================================================================*/
  5039. /* Allowed flush values; see deflate() and inflate() below for details */
  5040. //var Z_NO_FLUSH = 0;
  5041. //var Z_PARTIAL_FLUSH = 1;
  5042. //var Z_SYNC_FLUSH = 2;
  5043. //var Z_FULL_FLUSH = 3;
  5044. var Z_FINISH = 4;
  5045. var Z_BLOCK = 5;
  5046. var Z_TREES = 6;
  5047. /* Return codes for the compression/decompression functions. Negative values
  5048. * are errors, positive values are used for special but normal events.
  5049. */
  5050. var Z_OK = 0;
  5051. var Z_STREAM_END = 1;
  5052. var Z_NEED_DICT = 2;
  5053. //var Z_ERRNO = -1;
  5054. var Z_STREAM_ERROR = -2;
  5055. var Z_DATA_ERROR = -3;
  5056. var Z_MEM_ERROR = -4;
  5057. var Z_BUF_ERROR = -5;
  5058. //var Z_VERSION_ERROR = -6;
  5059. /* The deflate compression method */
  5060. var Z_DEFLATED = 8;
  5061. /* STATES ====================================================================*/
  5062. /* ===========================================================================*/
  5063. var HEAD = 1; /* i: waiting for magic header */
  5064. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  5065. var TIME = 3; /* i: waiting for modification time (gzip) */
  5066. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  5067. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  5068. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  5069. var NAME = 7; /* i: waiting for end of file name (gzip) */
  5070. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  5071. var HCRC = 9; /* i: waiting for header crc (gzip) */
  5072. var DICTID = 10; /* i: waiting for dictionary check value */
  5073. var DICT = 11; /* waiting for inflateSetDictionary() call */
  5074. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5075. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  5076. var STORED = 14; /* i: waiting for stored size (length and complement) */
  5077. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  5078. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  5079. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  5080. var LENLENS = 18; /* i: waiting for code length code lengths */
  5081. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  5082. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  5083. var LEN = 21; /* i: waiting for length/lit/eob code */
  5084. var LENEXT = 22; /* i: waiting for length extra bits */
  5085. var DIST = 23; /* i: waiting for distance code */
  5086. var DISTEXT = 24; /* i: waiting for distance extra bits */
  5087. var MATCH = 25; /* o: waiting for output space to copy string */
  5088. var LIT = 26; /* o: waiting for output space to write literal */
  5089. var CHECK = 27; /* i: waiting for 32-bit check value */
  5090. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  5091. var DONE = 29; /* finished check, done -- remain here until reset */
  5092. var BAD = 30; /* got a data error -- remain here until reset */
  5093. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  5094. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  5095. /* ===========================================================================*/
  5096. var ENOUGH_LENS = 852;
  5097. var ENOUGH_DISTS = 592;
  5098. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  5099. var MAX_WBITS = 15;
  5100. /* 32K LZ77 window */
  5101. var DEF_WBITS = MAX_WBITS;
  5102. function zswap32(q) {
  5103. return (((q >>> 24) & 0xff) +
  5104. ((q >>> 8) & 0xff00) +
  5105. ((q & 0xff00) << 8) +
  5106. ((q & 0xff) << 24));
  5107. }
  5108. function InflateState() {
  5109. this.mode = 0; /* current inflate mode */
  5110. this.last = false; /* true if processing last block */
  5111. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5112. this.havedict = false; /* true if dictionary provided */
  5113. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  5114. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  5115. this.check = 0; /* protected copy of check value */
  5116. this.total = 0; /* protected copy of output count */
  5117. // TODO: may be {}
  5118. this.head = null; /* where to save gzip header information */
  5119. /* sliding window */
  5120. this.wbits = 0; /* log base 2 of requested window size */
  5121. this.wsize = 0; /* window size or zero if not using window */
  5122. this.whave = 0; /* valid bytes in the window */
  5123. this.wnext = 0; /* window write index */
  5124. this.window = null; /* allocated sliding window, if needed */
  5125. /* bit accumulator */
  5126. this.hold = 0; /* input bit accumulator */
  5127. this.bits = 0; /* number of bits in "in" */
  5128. /* for string and stored block copying */
  5129. this.length = 0; /* literal or length of data to copy */
  5130. this.offset = 0; /* distance back to copy string from */
  5131. /* for table and code decoding */
  5132. this.extra = 0; /* extra bits needed */
  5133. /* fixed and dynamic code tables */
  5134. this.lencode = null; /* starting table for length/literal codes */
  5135. this.distcode = null; /* starting table for distance codes */
  5136. this.lenbits = 0; /* index bits for lencode */
  5137. this.distbits = 0; /* index bits for distcode */
  5138. /* dynamic table building */
  5139. this.ncode = 0; /* number of code length code lengths */
  5140. this.nlen = 0; /* number of length code lengths */
  5141. this.ndist = 0; /* number of distance code lengths */
  5142. this.have = 0; /* number of code lengths in lens[] */
  5143. this.next = null; /* next available space in codes[] */
  5144. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  5145. this.work = new utils.Buf16(288); /* work area for code table building */
  5146. /*
  5147. because we don't have pointers in js, we use lencode and distcode directly
  5148. as buffers so we don't need codes
  5149. */
  5150. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  5151. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  5152. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  5153. this.sane = 0; /* if false, allow invalid distance too far */
  5154. this.back = 0; /* bits back of last unprocessed length/lit */
  5155. this.was = 0; /* initial length of match */
  5156. }
  5157. function inflateResetKeep(strm) {
  5158. var state;
  5159. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5160. state = strm.state;
  5161. strm.total_in = strm.total_out = state.total = 0;
  5162. strm.msg = ''; /*Z_NULL*/
  5163. if (state.wrap) { /* to support ill-conceived Java test suite */
  5164. strm.adler = state.wrap & 1;
  5165. }
  5166. state.mode = HEAD;
  5167. state.last = 0;
  5168. state.havedict = 0;
  5169. state.dmax = 32768;
  5170. state.head = null/*Z_NULL*/;
  5171. state.hold = 0;
  5172. state.bits = 0;
  5173. //state.lencode = state.distcode = state.next = state.codes;
  5174. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  5175. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  5176. state.sane = 1;
  5177. state.back = -1;
  5178. //Tracev((stderr, "inflate: reset\n"));
  5179. return Z_OK;
  5180. }
  5181. function inflateReset(strm) {
  5182. var state;
  5183. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5184. state = strm.state;
  5185. state.wsize = 0;
  5186. state.whave = 0;
  5187. state.wnext = 0;
  5188. return inflateResetKeep(strm);
  5189. }
  5190. function inflateReset2(strm, windowBits) {
  5191. var wrap;
  5192. var state;
  5193. /* get the state */
  5194. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5195. state = strm.state;
  5196. /* extract wrap request from windowBits parameter */
  5197. if (windowBits < 0) {
  5198. wrap = 0;
  5199. windowBits = -windowBits;
  5200. }
  5201. else {
  5202. wrap = (windowBits >> 4) + 1;
  5203. if (windowBits < 48) {
  5204. windowBits &= 15;
  5205. }
  5206. }
  5207. /* set number of window bits, free window if different */
  5208. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  5209. return Z_STREAM_ERROR;
  5210. }
  5211. if (state.window !== null && state.wbits !== windowBits) {
  5212. state.window = null;
  5213. }
  5214. /* update state and reset the rest of it */
  5215. state.wrap = wrap;
  5216. state.wbits = windowBits;
  5217. return inflateReset(strm);
  5218. }
  5219. function inflateInit2(strm, windowBits) {
  5220. var ret;
  5221. var state;
  5222. if (!strm) { return Z_STREAM_ERROR; }
  5223. //strm.msg = Z_NULL; /* in case we return an error */
  5224. state = new InflateState();
  5225. //if (state === Z_NULL) return Z_MEM_ERROR;
  5226. //Tracev((stderr, "inflate: allocated\n"));
  5227. strm.state = state;
  5228. state.window = null/*Z_NULL*/;
  5229. ret = inflateReset2(strm, windowBits);
  5230. if (ret !== Z_OK) {
  5231. strm.state = null/*Z_NULL*/;
  5232. }
  5233. return ret;
  5234. }
  5235. function inflateInit(strm) {
  5236. return inflateInit2(strm, DEF_WBITS);
  5237. }
  5238. /*
  5239. Return state with length and distance decoding tables and index sizes set to
  5240. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  5241. If BUILDFIXED is defined, then instead this routine builds the tables the
  5242. first time it's called, and returns those tables the first time and
  5243. thereafter. This reduces the size of the code by about 2K bytes, in
  5244. exchange for a little execution time. However, BUILDFIXED should not be
  5245. used for threaded applications, since the rewriting of the tables and virgin
  5246. may not be thread-safe.
  5247. */
  5248. var virgin = true;
  5249. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  5250. function fixedtables(state) {
  5251. /* build fixed huffman tables if first call (may not be thread safe) */
  5252. if (virgin) {
  5253. var sym;
  5254. lenfix = new utils.Buf32(512);
  5255. distfix = new utils.Buf32(32);
  5256. /* literal/length table */
  5257. sym = 0;
  5258. while (sym < 144) { state.lens[sym++] = 8; }
  5259. while (sym < 256) { state.lens[sym++] = 9; }
  5260. while (sym < 280) { state.lens[sym++] = 7; }
  5261. while (sym < 288) { state.lens[sym++] = 8; }
  5262. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  5263. /* distance table */
  5264. sym = 0;
  5265. while (sym < 32) { state.lens[sym++] = 5; }
  5266. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  5267. /* do this just once */
  5268. virgin = false;
  5269. }
  5270. state.lencode = lenfix;
  5271. state.lenbits = 9;
  5272. state.distcode = distfix;
  5273. state.distbits = 5;
  5274. }
  5275. /*
  5276. Update the window with the last wsize (normally 32K) bytes written before
  5277. returning. If window does not exist yet, create it. This is only called
  5278. when a window is already in use, or when output has been written during this
  5279. inflate call, but the end of the deflate stream has not been reached yet.
  5280. It is also called to create a window for dictionary data when a dictionary
  5281. is loaded.
  5282. Providing output buffers larger than 32K to inflate() should provide a speed
  5283. advantage, since only the last 32K of output is copied to the sliding window
  5284. upon return from inflate(), and since all distances after the first 32K of
  5285. output will fall in the output data, making match copies simpler and faster.
  5286. The advantage may be dependent on the size of the processor's data caches.
  5287. */
  5288. function updatewindow(strm, src, end, copy) {
  5289. var dist;
  5290. var state = strm.state;
  5291. /* if it hasn't been done already, allocate space for the window */
  5292. if (state.window === null) {
  5293. state.wsize = 1 << state.wbits;
  5294. state.wnext = 0;
  5295. state.whave = 0;
  5296. state.window = new utils.Buf8(state.wsize);
  5297. }
  5298. /* copy state->wsize or less output bytes into the circular window */
  5299. if (copy >= state.wsize) {
  5300. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  5301. state.wnext = 0;
  5302. state.whave = state.wsize;
  5303. }
  5304. else {
  5305. dist = state.wsize - state.wnext;
  5306. if (dist > copy) {
  5307. dist = copy;
  5308. }
  5309. //zmemcpy(state->window + state->wnext, end - copy, dist);
  5310. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  5311. copy -= dist;
  5312. if (copy) {
  5313. //zmemcpy(state->window, end - copy, copy);
  5314. utils.arraySet(state.window, src, end - copy, copy, 0);
  5315. state.wnext = copy;
  5316. state.whave = state.wsize;
  5317. }
  5318. else {
  5319. state.wnext += dist;
  5320. if (state.wnext === state.wsize) { state.wnext = 0; }
  5321. if (state.whave < state.wsize) { state.whave += dist; }
  5322. }
  5323. }
  5324. return 0;
  5325. }
  5326. function inflate(strm, flush) {
  5327. var state;
  5328. var input, output; // input/output buffers
  5329. var next; /* next input INDEX */
  5330. var put; /* next output INDEX */
  5331. var have, left; /* available input and output */
  5332. var hold; /* bit buffer */
  5333. var bits; /* bits in bit buffer */
  5334. var _in, _out; /* save starting available input and output */
  5335. var copy; /* number of stored or match bytes to copy */
  5336. var from; /* where to copy match bytes from */
  5337. var from_source;
  5338. var here = 0; /* current decoding table entry */
  5339. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  5340. //var last; /* parent table entry */
  5341. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  5342. var len; /* length to copy for repeats, bits to drop */
  5343. var ret; /* return code */
  5344. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  5345. var opts;
  5346. var n; // temporary var for NEED_BITS
  5347. var order = /* permutation of code lengths */
  5348. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  5349. if (!strm || !strm.state || !strm.output ||
  5350. (!strm.input && strm.avail_in !== 0)) {
  5351. return Z_STREAM_ERROR;
  5352. }
  5353. state = strm.state;
  5354. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  5355. //--- LOAD() ---
  5356. put = strm.next_out;
  5357. output = strm.output;
  5358. left = strm.avail_out;
  5359. next = strm.next_in;
  5360. input = strm.input;
  5361. have = strm.avail_in;
  5362. hold = state.hold;
  5363. bits = state.bits;
  5364. //---
  5365. _in = have;
  5366. _out = left;
  5367. ret = Z_OK;
  5368. inf_leave: // goto emulation
  5369. for (;;) {
  5370. switch (state.mode) {
  5371. case HEAD:
  5372. if (state.wrap === 0) {
  5373. state.mode = TYPEDO;
  5374. break;
  5375. }
  5376. //=== NEEDBITS(16);
  5377. while (bits < 16) {
  5378. if (have === 0) { break inf_leave; }
  5379. have--;
  5380. hold += input[next++] << bits;
  5381. bits += 8;
  5382. }
  5383. //===//
  5384. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  5385. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  5386. //=== CRC2(state.check, hold);
  5387. hbuf[0] = hold & 0xff;
  5388. hbuf[1] = (hold >>> 8) & 0xff;
  5389. state.check = crc32(state.check, hbuf, 2, 0);
  5390. //===//
  5391. //=== INITBITS();
  5392. hold = 0;
  5393. bits = 0;
  5394. //===//
  5395. state.mode = FLAGS;
  5396. break;
  5397. }
  5398. state.flags = 0; /* expect zlib header */
  5399. if (state.head) {
  5400. state.head.done = false;
  5401. }
  5402. if (!(state.wrap & 1) || /* check if zlib header allowed */
  5403. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  5404. strm.msg = 'incorrect header check';
  5405. state.mode = BAD;
  5406. break;
  5407. }
  5408. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  5409. strm.msg = 'unknown compression method';
  5410. state.mode = BAD;
  5411. break;
  5412. }
  5413. //--- DROPBITS(4) ---//
  5414. hold >>>= 4;
  5415. bits -= 4;
  5416. //---//
  5417. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  5418. if (state.wbits === 0) {
  5419. state.wbits = len;
  5420. }
  5421. else if (len > state.wbits) {
  5422. strm.msg = 'invalid window size';
  5423. state.mode = BAD;
  5424. break;
  5425. }
  5426. state.dmax = 1 << len;
  5427. //Tracev((stderr, "inflate: zlib header ok\n"));
  5428. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  5429. state.mode = hold & 0x200 ? DICTID : TYPE;
  5430. //=== INITBITS();
  5431. hold = 0;
  5432. bits = 0;
  5433. //===//
  5434. break;
  5435. case FLAGS:
  5436. //=== NEEDBITS(16); */
  5437. while (bits < 16) {
  5438. if (have === 0) { break inf_leave; }
  5439. have--;
  5440. hold += input[next++] << bits;
  5441. bits += 8;
  5442. }
  5443. //===//
  5444. state.flags = hold;
  5445. if ((state.flags & 0xff) !== Z_DEFLATED) {
  5446. strm.msg = 'unknown compression method';
  5447. state.mode = BAD;
  5448. break;
  5449. }
  5450. if (state.flags & 0xe000) {
  5451. strm.msg = 'unknown header flags set';
  5452. state.mode = BAD;
  5453. break;
  5454. }
  5455. if (state.head) {
  5456. state.head.text = ((hold >> 8) & 1);
  5457. }
  5458. if (state.flags & 0x0200) {
  5459. //=== CRC2(state.check, hold);
  5460. hbuf[0] = hold & 0xff;
  5461. hbuf[1] = (hold >>> 8) & 0xff;
  5462. state.check = crc32(state.check, hbuf, 2, 0);
  5463. //===//
  5464. }
  5465. //=== INITBITS();
  5466. hold = 0;
  5467. bits = 0;
  5468. //===//
  5469. state.mode = TIME;
  5470. /* falls through */
  5471. case TIME:
  5472. //=== NEEDBITS(32); */
  5473. while (bits < 32) {
  5474. if (have === 0) { break inf_leave; }
  5475. have--;
  5476. hold += input[next++] << bits;
  5477. bits += 8;
  5478. }
  5479. //===//
  5480. if (state.head) {
  5481. state.head.time = hold;
  5482. }
  5483. if (state.flags & 0x0200) {
  5484. //=== CRC4(state.check, hold)
  5485. hbuf[0] = hold & 0xff;
  5486. hbuf[1] = (hold >>> 8) & 0xff;
  5487. hbuf[2] = (hold >>> 16) & 0xff;
  5488. hbuf[3] = (hold >>> 24) & 0xff;
  5489. state.check = crc32(state.check, hbuf, 4, 0);
  5490. //===
  5491. }
  5492. //=== INITBITS();
  5493. hold = 0;
  5494. bits = 0;
  5495. //===//
  5496. state.mode = OS;
  5497. /* falls through */
  5498. case OS:
  5499. //=== NEEDBITS(16); */
  5500. while (bits < 16) {
  5501. if (have === 0) { break inf_leave; }
  5502. have--;
  5503. hold += input[next++] << bits;
  5504. bits += 8;
  5505. }
  5506. //===//
  5507. if (state.head) {
  5508. state.head.xflags = (hold & 0xff);
  5509. state.head.os = (hold >> 8);
  5510. }
  5511. if (state.flags & 0x0200) {
  5512. //=== CRC2(state.check, hold);
  5513. hbuf[0] = hold & 0xff;
  5514. hbuf[1] = (hold >>> 8) & 0xff;
  5515. state.check = crc32(state.check, hbuf, 2, 0);
  5516. //===//
  5517. }
  5518. //=== INITBITS();
  5519. hold = 0;
  5520. bits = 0;
  5521. //===//
  5522. state.mode = EXLEN;
  5523. /* falls through */
  5524. case EXLEN:
  5525. if (state.flags & 0x0400) {
  5526. //=== NEEDBITS(16); */
  5527. while (bits < 16) {
  5528. if (have === 0) { break inf_leave; }
  5529. have--;
  5530. hold += input[next++] << bits;
  5531. bits += 8;
  5532. }
  5533. //===//
  5534. state.length = hold;
  5535. if (state.head) {
  5536. state.head.extra_len = hold;
  5537. }
  5538. if (state.flags & 0x0200) {
  5539. //=== CRC2(state.check, hold);
  5540. hbuf[0] = hold & 0xff;
  5541. hbuf[1] = (hold >>> 8) & 0xff;
  5542. state.check = crc32(state.check, hbuf, 2, 0);
  5543. //===//
  5544. }
  5545. //=== INITBITS();
  5546. hold = 0;
  5547. bits = 0;
  5548. //===//
  5549. }
  5550. else if (state.head) {
  5551. state.head.extra = null/*Z_NULL*/;
  5552. }
  5553. state.mode = EXTRA;
  5554. /* falls through */
  5555. case EXTRA:
  5556. if (state.flags & 0x0400) {
  5557. copy = state.length;
  5558. if (copy > have) { copy = have; }
  5559. if (copy) {
  5560. if (state.head) {
  5561. len = state.head.extra_len - state.length;
  5562. if (!state.head.extra) {
  5563. // Use untyped array for more convenient processing later
  5564. state.head.extra = new Array(state.head.extra_len);
  5565. }
  5566. utils.arraySet(
  5567. state.head.extra,
  5568. input,
  5569. next,
  5570. // extra field is limited to 65536 bytes
  5571. // - no need for additional size check
  5572. copy,
  5573. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  5574. len
  5575. );
  5576. //zmemcpy(state.head.extra + len, next,
  5577. // len + copy > state.head.extra_max ?
  5578. // state.head.extra_max - len : copy);
  5579. }
  5580. if (state.flags & 0x0200) {
  5581. state.check = crc32(state.check, input, copy, next);
  5582. }
  5583. have -= copy;
  5584. next += copy;
  5585. state.length -= copy;
  5586. }
  5587. if (state.length) { break inf_leave; }
  5588. }
  5589. state.length = 0;
  5590. state.mode = NAME;
  5591. /* falls through */
  5592. case NAME:
  5593. if (state.flags & 0x0800) {
  5594. if (have === 0) { break inf_leave; }
  5595. copy = 0;
  5596. do {
  5597. // TODO: 2 or 1 bytes?
  5598. len = input[next + copy++];
  5599. /* use constant limit because in js we should not preallocate memory */
  5600. if (state.head && len &&
  5601. (state.length < 65536 /*state.head.name_max*/)) {
  5602. state.head.name += String.fromCharCode(len);
  5603. }
  5604. } while (len && copy < have);
  5605. if (state.flags & 0x0200) {
  5606. state.check = crc32(state.check, input, copy, next);
  5607. }
  5608. have -= copy;
  5609. next += copy;
  5610. if (len) { break inf_leave; }
  5611. }
  5612. else if (state.head) {
  5613. state.head.name = null;
  5614. }
  5615. state.length = 0;
  5616. state.mode = COMMENT;
  5617. /* falls through */
  5618. case COMMENT:
  5619. if (state.flags & 0x1000) {
  5620. if (have === 0) { break inf_leave; }
  5621. copy = 0;
  5622. do {
  5623. len = input[next + copy++];
  5624. /* use constant limit because in js we should not preallocate memory */
  5625. if (state.head && len &&
  5626. (state.length < 65536 /*state.head.comm_max*/)) {
  5627. state.head.comment += String.fromCharCode(len);
  5628. }
  5629. } while (len && copy < have);
  5630. if (state.flags & 0x0200) {
  5631. state.check = crc32(state.check, input, copy, next);
  5632. }
  5633. have -= copy;
  5634. next += copy;
  5635. if (len) { break inf_leave; }
  5636. }
  5637. else if (state.head) {
  5638. state.head.comment = null;
  5639. }
  5640. state.mode = HCRC;
  5641. /* falls through */
  5642. case HCRC:
  5643. if (state.flags & 0x0200) {
  5644. //=== NEEDBITS(16); */
  5645. while (bits < 16) {
  5646. if (have === 0) { break inf_leave; }
  5647. have--;
  5648. hold += input[next++] << bits;
  5649. bits += 8;
  5650. }
  5651. //===//
  5652. if (hold !== (state.check & 0xffff)) {
  5653. strm.msg = 'header crc mismatch';
  5654. state.mode = BAD;
  5655. break;
  5656. }
  5657. //=== INITBITS();
  5658. hold = 0;
  5659. bits = 0;
  5660. //===//
  5661. }
  5662. if (state.head) {
  5663. state.head.hcrc = ((state.flags >> 9) & 1);
  5664. state.head.done = true;
  5665. }
  5666. strm.adler = state.check = 0;
  5667. state.mode = TYPE;
  5668. break;
  5669. case DICTID:
  5670. //=== NEEDBITS(32); */
  5671. while (bits < 32) {
  5672. if (have === 0) { break inf_leave; }
  5673. have--;
  5674. hold += input[next++] << bits;
  5675. bits += 8;
  5676. }
  5677. //===//
  5678. strm.adler = state.check = zswap32(hold);
  5679. //=== INITBITS();
  5680. hold = 0;
  5681. bits = 0;
  5682. //===//
  5683. state.mode = DICT;
  5684. /* falls through */
  5685. case DICT:
  5686. if (state.havedict === 0) {
  5687. //--- RESTORE() ---
  5688. strm.next_out = put;
  5689. strm.avail_out = left;
  5690. strm.next_in = next;
  5691. strm.avail_in = have;
  5692. state.hold = hold;
  5693. state.bits = bits;
  5694. //---
  5695. return Z_NEED_DICT;
  5696. }
  5697. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  5698. state.mode = TYPE;
  5699. /* falls through */
  5700. case TYPE:
  5701. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  5702. /* falls through */
  5703. case TYPEDO:
  5704. if (state.last) {
  5705. //--- BYTEBITS() ---//
  5706. hold >>>= bits & 7;
  5707. bits -= bits & 7;
  5708. //---//
  5709. state.mode = CHECK;
  5710. break;
  5711. }
  5712. //=== NEEDBITS(3); */
  5713. while (bits < 3) {
  5714. if (have === 0) { break inf_leave; }
  5715. have--;
  5716. hold += input[next++] << bits;
  5717. bits += 8;
  5718. }
  5719. //===//
  5720. state.last = (hold & 0x01)/*BITS(1)*/;
  5721. //--- DROPBITS(1) ---//
  5722. hold >>>= 1;
  5723. bits -= 1;
  5724. //---//
  5725. switch ((hold & 0x03)/*BITS(2)*/) {
  5726. case 0: /* stored block */
  5727. //Tracev((stderr, "inflate: stored block%s\n",
  5728. // state.last ? " (last)" : ""));
  5729. state.mode = STORED;
  5730. break;
  5731. case 1: /* fixed block */
  5732. fixedtables(state);
  5733. //Tracev((stderr, "inflate: fixed codes block%s\n",
  5734. // state.last ? " (last)" : ""));
  5735. state.mode = LEN_; /* decode codes */
  5736. if (flush === Z_TREES) {
  5737. //--- DROPBITS(2) ---//
  5738. hold >>>= 2;
  5739. bits -= 2;
  5740. //---//
  5741. break inf_leave;
  5742. }
  5743. break;
  5744. case 2: /* dynamic block */
  5745. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  5746. // state.last ? " (last)" : ""));
  5747. state.mode = TABLE;
  5748. break;
  5749. case 3:
  5750. strm.msg = 'invalid block type';
  5751. state.mode = BAD;
  5752. }
  5753. //--- DROPBITS(2) ---//
  5754. hold >>>= 2;
  5755. bits -= 2;
  5756. //---//
  5757. break;
  5758. case STORED:
  5759. //--- BYTEBITS() ---// /* go to byte boundary */
  5760. hold >>>= bits & 7;
  5761. bits -= bits & 7;
  5762. //---//
  5763. //=== NEEDBITS(32); */
  5764. while (bits < 32) {
  5765. if (have === 0) { break inf_leave; }
  5766. have--;
  5767. hold += input[next++] << bits;
  5768. bits += 8;
  5769. }
  5770. //===//
  5771. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  5772. strm.msg = 'invalid stored block lengths';
  5773. state.mode = BAD;
  5774. break;
  5775. }
  5776. state.length = hold & 0xffff;
  5777. //Tracev((stderr, "inflate: stored length %u\n",
  5778. // state.length));
  5779. //=== INITBITS();
  5780. hold = 0;
  5781. bits = 0;
  5782. //===//
  5783. state.mode = COPY_;
  5784. if (flush === Z_TREES) { break inf_leave; }
  5785. /* falls through */
  5786. case COPY_:
  5787. state.mode = COPY;
  5788. /* falls through */
  5789. case COPY:
  5790. copy = state.length;
  5791. if (copy) {
  5792. if (copy > have) { copy = have; }
  5793. if (copy > left) { copy = left; }
  5794. if (copy === 0) { break inf_leave; }
  5795. //--- zmemcpy(put, next, copy); ---
  5796. utils.arraySet(output, input, next, copy, put);
  5797. //---//
  5798. have -= copy;
  5799. next += copy;
  5800. left -= copy;
  5801. put += copy;
  5802. state.length -= copy;
  5803. break;
  5804. }
  5805. //Tracev((stderr, "inflate: stored end\n"));
  5806. state.mode = TYPE;
  5807. break;
  5808. case TABLE:
  5809. //=== NEEDBITS(14); */
  5810. while (bits < 14) {
  5811. if (have === 0) { break inf_leave; }
  5812. have--;
  5813. hold += input[next++] << bits;
  5814. bits += 8;
  5815. }
  5816. //===//
  5817. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  5818. //--- DROPBITS(5) ---//
  5819. hold >>>= 5;
  5820. bits -= 5;
  5821. //---//
  5822. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  5823. //--- DROPBITS(5) ---//
  5824. hold >>>= 5;
  5825. bits -= 5;
  5826. //---//
  5827. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  5828. //--- DROPBITS(4) ---//
  5829. hold >>>= 4;
  5830. bits -= 4;
  5831. //---//
  5832. //#ifndef PKZIP_BUG_WORKAROUND
  5833. if (state.nlen > 286 || state.ndist > 30) {
  5834. strm.msg = 'too many length or distance symbols';
  5835. state.mode = BAD;
  5836. break;
  5837. }
  5838. //#endif
  5839. //Tracev((stderr, "inflate: table sizes ok\n"));
  5840. state.have = 0;
  5841. state.mode = LENLENS;
  5842. /* falls through */
  5843. case LENLENS:
  5844. while (state.have < state.ncode) {
  5845. //=== NEEDBITS(3);
  5846. while (bits < 3) {
  5847. if (have === 0) { break inf_leave; }
  5848. have--;
  5849. hold += input[next++] << bits;
  5850. bits += 8;
  5851. }
  5852. //===//
  5853. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  5854. //--- DROPBITS(3) ---//
  5855. hold >>>= 3;
  5856. bits -= 3;
  5857. //---//
  5858. }
  5859. while (state.have < 19) {
  5860. state.lens[order[state.have++]] = 0;
  5861. }
  5862. // We have separate tables & no pointers. 2 commented lines below not needed.
  5863. //state.next = state.codes;
  5864. //state.lencode = state.next;
  5865. // Switch to use dynamic table
  5866. state.lencode = state.lendyn;
  5867. state.lenbits = 7;
  5868. opts = { bits: state.lenbits };
  5869. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  5870. state.lenbits = opts.bits;
  5871. if (ret) {
  5872. strm.msg = 'invalid code lengths set';
  5873. state.mode = BAD;
  5874. break;
  5875. }
  5876. //Tracev((stderr, "inflate: code lengths ok\n"));
  5877. state.have = 0;
  5878. state.mode = CODELENS;
  5879. /* falls through */
  5880. case CODELENS:
  5881. while (state.have < state.nlen + state.ndist) {
  5882. for (;;) {
  5883. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  5884. here_bits = here >>> 24;
  5885. here_op = (here >>> 16) & 0xff;
  5886. here_val = here & 0xffff;
  5887. if ((here_bits) <= bits) { break; }
  5888. //--- PULLBYTE() ---//
  5889. if (have === 0) { break inf_leave; }
  5890. have--;
  5891. hold += input[next++] << bits;
  5892. bits += 8;
  5893. //---//
  5894. }
  5895. if (here_val < 16) {
  5896. //--- DROPBITS(here.bits) ---//
  5897. hold >>>= here_bits;
  5898. bits -= here_bits;
  5899. //---//
  5900. state.lens[state.have++] = here_val;
  5901. }
  5902. else {
  5903. if (here_val === 16) {
  5904. //=== NEEDBITS(here.bits + 2);
  5905. n = here_bits + 2;
  5906. while (bits < n) {
  5907. if (have === 0) { break inf_leave; }
  5908. have--;
  5909. hold += input[next++] << bits;
  5910. bits += 8;
  5911. }
  5912. //===//
  5913. //--- DROPBITS(here.bits) ---//
  5914. hold >>>= here_bits;
  5915. bits -= here_bits;
  5916. //---//
  5917. if (state.have === 0) {
  5918. strm.msg = 'invalid bit length repeat';
  5919. state.mode = BAD;
  5920. break;
  5921. }
  5922. len = state.lens[state.have - 1];
  5923. copy = 3 + (hold & 0x03);//BITS(2);
  5924. //--- DROPBITS(2) ---//
  5925. hold >>>= 2;
  5926. bits -= 2;
  5927. //---//
  5928. }
  5929. else if (here_val === 17) {
  5930. //=== NEEDBITS(here.bits + 3);
  5931. n = here_bits + 3;
  5932. while (bits < n) {
  5933. if (have === 0) { break inf_leave; }
  5934. have--;
  5935. hold += input[next++] << bits;
  5936. bits += 8;
  5937. }
  5938. //===//
  5939. //--- DROPBITS(here.bits) ---//
  5940. hold >>>= here_bits;
  5941. bits -= here_bits;
  5942. //---//
  5943. len = 0;
  5944. copy = 3 + (hold & 0x07);//BITS(3);
  5945. //--- DROPBITS(3) ---//
  5946. hold >>>= 3;
  5947. bits -= 3;
  5948. //---//
  5949. }
  5950. else {
  5951. //=== NEEDBITS(here.bits + 7);
  5952. n = here_bits + 7;
  5953. while (bits < n) {
  5954. if (have === 0) { break inf_leave; }
  5955. have--;
  5956. hold += input[next++] << bits;
  5957. bits += 8;
  5958. }
  5959. //===//
  5960. //--- DROPBITS(here.bits) ---//
  5961. hold >>>= here_bits;
  5962. bits -= here_bits;
  5963. //---//
  5964. len = 0;
  5965. copy = 11 + (hold & 0x7f);//BITS(7);
  5966. //--- DROPBITS(7) ---//
  5967. hold >>>= 7;
  5968. bits -= 7;
  5969. //---//
  5970. }
  5971. if (state.have + copy > state.nlen + state.ndist) {
  5972. strm.msg = 'invalid bit length repeat';
  5973. state.mode = BAD;
  5974. break;
  5975. }
  5976. while (copy--) {
  5977. state.lens[state.have++] = len;
  5978. }
  5979. }
  5980. }
  5981. /* handle error breaks in while */
  5982. if (state.mode === BAD) { break; }
  5983. /* check for end-of-block code (better have one) */
  5984. if (state.lens[256] === 0) {
  5985. strm.msg = 'invalid code -- missing end-of-block';
  5986. state.mode = BAD;
  5987. break;
  5988. }
  5989. /* build code tables -- note: do not change the lenbits or distbits
  5990. values here (9 and 6) without reading the comments in inftrees.h
  5991. concerning the ENOUGH constants, which depend on those values */
  5992. state.lenbits = 9;
  5993. opts = { bits: state.lenbits };
  5994. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  5995. // We have separate tables & no pointers. 2 commented lines below not needed.
  5996. // state.next_index = opts.table_index;
  5997. state.lenbits = opts.bits;
  5998. // state.lencode = state.next;
  5999. if (ret) {
  6000. strm.msg = 'invalid literal/lengths set';
  6001. state.mode = BAD;
  6002. break;
  6003. }
  6004. state.distbits = 6;
  6005. //state.distcode.copy(state.codes);
  6006. // Switch to use dynamic table
  6007. state.distcode = state.distdyn;
  6008. opts = { bits: state.distbits };
  6009. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  6010. // We have separate tables & no pointers. 2 commented lines below not needed.
  6011. // state.next_index = opts.table_index;
  6012. state.distbits = opts.bits;
  6013. // state.distcode = state.next;
  6014. if (ret) {
  6015. strm.msg = 'invalid distances set';
  6016. state.mode = BAD;
  6017. break;
  6018. }
  6019. //Tracev((stderr, 'inflate: codes ok\n'));
  6020. state.mode = LEN_;
  6021. if (flush === Z_TREES) { break inf_leave; }
  6022. /* falls through */
  6023. case LEN_:
  6024. state.mode = LEN;
  6025. /* falls through */
  6026. case LEN:
  6027. if (have >= 6 && left >= 258) {
  6028. //--- RESTORE() ---
  6029. strm.next_out = put;
  6030. strm.avail_out = left;
  6031. strm.next_in = next;
  6032. strm.avail_in = have;
  6033. state.hold = hold;
  6034. state.bits = bits;
  6035. //---
  6036. inflate_fast(strm, _out);
  6037. //--- LOAD() ---
  6038. put = strm.next_out;
  6039. output = strm.output;
  6040. left = strm.avail_out;
  6041. next = strm.next_in;
  6042. input = strm.input;
  6043. have = strm.avail_in;
  6044. hold = state.hold;
  6045. bits = state.bits;
  6046. //---
  6047. if (state.mode === TYPE) {
  6048. state.back = -1;
  6049. }
  6050. break;
  6051. }
  6052. state.back = 0;
  6053. for (;;) {
  6054. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  6055. here_bits = here >>> 24;
  6056. here_op = (here >>> 16) & 0xff;
  6057. here_val = here & 0xffff;
  6058. if (here_bits <= bits) { break; }
  6059. //--- PULLBYTE() ---//
  6060. if (have === 0) { break inf_leave; }
  6061. have--;
  6062. hold += input[next++] << bits;
  6063. bits += 8;
  6064. //---//
  6065. }
  6066. if (here_op && (here_op & 0xf0) === 0) {
  6067. last_bits = here_bits;
  6068. last_op = here_op;
  6069. last_val = here_val;
  6070. for (;;) {
  6071. here = state.lencode[last_val +
  6072. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6073. here_bits = here >>> 24;
  6074. here_op = (here >>> 16) & 0xff;
  6075. here_val = here & 0xffff;
  6076. if ((last_bits + here_bits) <= bits) { break; }
  6077. //--- PULLBYTE() ---//
  6078. if (have === 0) { break inf_leave; }
  6079. have--;
  6080. hold += input[next++] << bits;
  6081. bits += 8;
  6082. //---//
  6083. }
  6084. //--- DROPBITS(last.bits) ---//
  6085. hold >>>= last_bits;
  6086. bits -= last_bits;
  6087. //---//
  6088. state.back += last_bits;
  6089. }
  6090. //--- DROPBITS(here.bits) ---//
  6091. hold >>>= here_bits;
  6092. bits -= here_bits;
  6093. //---//
  6094. state.back += here_bits;
  6095. state.length = here_val;
  6096. if (here_op === 0) {
  6097. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6098. // "inflate: literal '%c'\n" :
  6099. // "inflate: literal 0x%02x\n", here.val));
  6100. state.mode = LIT;
  6101. break;
  6102. }
  6103. if (here_op & 32) {
  6104. //Tracevv((stderr, "inflate: end of block\n"));
  6105. state.back = -1;
  6106. state.mode = TYPE;
  6107. break;
  6108. }
  6109. if (here_op & 64) {
  6110. strm.msg = 'invalid literal/length code';
  6111. state.mode = BAD;
  6112. break;
  6113. }
  6114. state.extra = here_op & 15;
  6115. state.mode = LENEXT;
  6116. /* falls through */
  6117. case LENEXT:
  6118. if (state.extra) {
  6119. //=== NEEDBITS(state.extra);
  6120. n = state.extra;
  6121. while (bits < n) {
  6122. if (have === 0) { break inf_leave; }
  6123. have--;
  6124. hold += input[next++] << bits;
  6125. bits += 8;
  6126. }
  6127. //===//
  6128. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  6129. //--- DROPBITS(state.extra) ---//
  6130. hold >>>= state.extra;
  6131. bits -= state.extra;
  6132. //---//
  6133. state.back += state.extra;
  6134. }
  6135. //Tracevv((stderr, "inflate: length %u\n", state.length));
  6136. state.was = state.length;
  6137. state.mode = DIST;
  6138. /* falls through */
  6139. case DIST:
  6140. for (;;) {
  6141. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  6142. here_bits = here >>> 24;
  6143. here_op = (here >>> 16) & 0xff;
  6144. here_val = here & 0xffff;
  6145. if ((here_bits) <= bits) { break; }
  6146. //--- PULLBYTE() ---//
  6147. if (have === 0) { break inf_leave; }
  6148. have--;
  6149. hold += input[next++] << bits;
  6150. bits += 8;
  6151. //---//
  6152. }
  6153. if ((here_op & 0xf0) === 0) {
  6154. last_bits = here_bits;
  6155. last_op = here_op;
  6156. last_val = here_val;
  6157. for (;;) {
  6158. here = state.distcode[last_val +
  6159. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6160. here_bits = here >>> 24;
  6161. here_op = (here >>> 16) & 0xff;
  6162. here_val = here & 0xffff;
  6163. if ((last_bits + here_bits) <= bits) { break; }
  6164. //--- PULLBYTE() ---//
  6165. if (have === 0) { break inf_leave; }
  6166. have--;
  6167. hold += input[next++] << bits;
  6168. bits += 8;
  6169. //---//
  6170. }
  6171. //--- DROPBITS(last.bits) ---//
  6172. hold >>>= last_bits;
  6173. bits -= last_bits;
  6174. //---//
  6175. state.back += last_bits;
  6176. }
  6177. //--- DROPBITS(here.bits) ---//
  6178. hold >>>= here_bits;
  6179. bits -= here_bits;
  6180. //---//
  6181. state.back += here_bits;
  6182. if (here_op & 64) {
  6183. strm.msg = 'invalid distance code';
  6184. state.mode = BAD;
  6185. break;
  6186. }
  6187. state.offset = here_val;
  6188. state.extra = (here_op) & 15;
  6189. state.mode = DISTEXT;
  6190. /* falls through */
  6191. case DISTEXT:
  6192. if (state.extra) {
  6193. //=== NEEDBITS(state.extra);
  6194. n = state.extra;
  6195. while (bits < n) {
  6196. if (have === 0) { break inf_leave; }
  6197. have--;
  6198. hold += input[next++] << bits;
  6199. bits += 8;
  6200. }
  6201. //===//
  6202. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  6203. //--- DROPBITS(state.extra) ---//
  6204. hold >>>= state.extra;
  6205. bits -= state.extra;
  6206. //---//
  6207. state.back += state.extra;
  6208. }
  6209. //#ifdef INFLATE_STRICT
  6210. if (state.offset > state.dmax) {
  6211. strm.msg = 'invalid distance too far back';
  6212. state.mode = BAD;
  6213. break;
  6214. }
  6215. //#endif
  6216. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  6217. state.mode = MATCH;
  6218. /* falls through */
  6219. case MATCH:
  6220. if (left === 0) { break inf_leave; }
  6221. copy = _out - left;
  6222. if (state.offset > copy) { /* copy from window */
  6223. copy = state.offset - copy;
  6224. if (copy > state.whave) {
  6225. if (state.sane) {
  6226. strm.msg = 'invalid distance too far back';
  6227. state.mode = BAD;
  6228. break;
  6229. }
  6230. // (!) This block is disabled in zlib defaults,
  6231. // don't enable it for binary compatibility
  6232. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6233. // Trace((stderr, "inflate.c too far\n"));
  6234. // copy -= state.whave;
  6235. // if (copy > state.length) { copy = state.length; }
  6236. // if (copy > left) { copy = left; }
  6237. // left -= copy;
  6238. // state.length -= copy;
  6239. // do {
  6240. // output[put++] = 0;
  6241. // } while (--copy);
  6242. // if (state.length === 0) { state.mode = LEN; }
  6243. // break;
  6244. //#endif
  6245. }
  6246. if (copy > state.wnext) {
  6247. copy -= state.wnext;
  6248. from = state.wsize - copy;
  6249. }
  6250. else {
  6251. from = state.wnext - copy;
  6252. }
  6253. if (copy > state.length) { copy = state.length; }
  6254. from_source = state.window;
  6255. }
  6256. else { /* copy from output */
  6257. from_source = output;
  6258. from = put - state.offset;
  6259. copy = state.length;
  6260. }
  6261. if (copy > left) { copy = left; }
  6262. left -= copy;
  6263. state.length -= copy;
  6264. do {
  6265. output[put++] = from_source[from++];
  6266. } while (--copy);
  6267. if (state.length === 0) { state.mode = LEN; }
  6268. break;
  6269. case LIT:
  6270. if (left === 0) { break inf_leave; }
  6271. output[put++] = state.length;
  6272. left--;
  6273. state.mode = LEN;
  6274. break;
  6275. case CHECK:
  6276. if (state.wrap) {
  6277. //=== NEEDBITS(32);
  6278. while (bits < 32) {
  6279. if (have === 0) { break inf_leave; }
  6280. have--;
  6281. // Use '|' instead of '+' to make sure that result is signed
  6282. hold |= input[next++] << bits;
  6283. bits += 8;
  6284. }
  6285. //===//
  6286. _out -= left;
  6287. strm.total_out += _out;
  6288. state.total += _out;
  6289. if (_out) {
  6290. strm.adler = state.check =
  6291. /*UPDATE(state.check, put - _out, _out);*/
  6292. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  6293. }
  6294. _out = left;
  6295. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  6296. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  6297. strm.msg = 'incorrect data check';
  6298. state.mode = BAD;
  6299. break;
  6300. }
  6301. //=== INITBITS();
  6302. hold = 0;
  6303. bits = 0;
  6304. //===//
  6305. //Tracev((stderr, "inflate: check matches trailer\n"));
  6306. }
  6307. state.mode = LENGTH;
  6308. /* falls through */
  6309. case LENGTH:
  6310. if (state.wrap && state.flags) {
  6311. //=== NEEDBITS(32);
  6312. while (bits < 32) {
  6313. if (have === 0) { break inf_leave; }
  6314. have--;
  6315. hold += input[next++] << bits;
  6316. bits += 8;
  6317. }
  6318. //===//
  6319. if (hold !== (state.total & 0xffffffff)) {
  6320. strm.msg = 'incorrect length check';
  6321. state.mode = BAD;
  6322. break;
  6323. }
  6324. //=== INITBITS();
  6325. hold = 0;
  6326. bits = 0;
  6327. //===//
  6328. //Tracev((stderr, "inflate: length matches trailer\n"));
  6329. }
  6330. state.mode = DONE;
  6331. /* falls through */
  6332. case DONE:
  6333. ret = Z_STREAM_END;
  6334. break inf_leave;
  6335. case BAD:
  6336. ret = Z_DATA_ERROR;
  6337. break inf_leave;
  6338. case MEM:
  6339. return Z_MEM_ERROR;
  6340. case SYNC:
  6341. /* falls through */
  6342. default:
  6343. return Z_STREAM_ERROR;
  6344. }
  6345. }
  6346. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  6347. /*
  6348. Return from inflate(), updating the total counts and the check value.
  6349. If there was no progress during the inflate() call, return a buffer
  6350. error. Call updatewindow() to create and/or update the window state.
  6351. Note: a memory error from inflate() is non-recoverable.
  6352. */
  6353. //--- RESTORE() ---
  6354. strm.next_out = put;
  6355. strm.avail_out = left;
  6356. strm.next_in = next;
  6357. strm.avail_in = have;
  6358. state.hold = hold;
  6359. state.bits = bits;
  6360. //---
  6361. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  6362. (state.mode < CHECK || flush !== Z_FINISH))) {
  6363. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  6364. state.mode = MEM;
  6365. return Z_MEM_ERROR;
  6366. }
  6367. }
  6368. _in -= strm.avail_in;
  6369. _out -= strm.avail_out;
  6370. strm.total_in += _in;
  6371. strm.total_out += _out;
  6372. state.total += _out;
  6373. if (state.wrap && _out) {
  6374. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  6375. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  6376. }
  6377. strm.data_type = state.bits + (state.last ? 64 : 0) +
  6378. (state.mode === TYPE ? 128 : 0) +
  6379. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  6380. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  6381. ret = Z_BUF_ERROR;
  6382. }
  6383. return ret;
  6384. }
  6385. function inflateEnd(strm) {
  6386. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  6387. return Z_STREAM_ERROR;
  6388. }
  6389. var state = strm.state;
  6390. if (state.window) {
  6391. state.window = null;
  6392. }
  6393. strm.state = null;
  6394. return Z_OK;
  6395. }
  6396. function inflateGetHeader(strm, head) {
  6397. var state;
  6398. /* check state */
  6399. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6400. state = strm.state;
  6401. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  6402. /* save header structure */
  6403. state.head = head;
  6404. head.done = false;
  6405. return Z_OK;
  6406. }
  6407. function inflateSetDictionary(strm, dictionary) {
  6408. var dictLength = dictionary.length;
  6409. var state;
  6410. var dictid;
  6411. var ret;
  6412. /* check state */
  6413. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  6414. state = strm.state;
  6415. if (state.wrap !== 0 && state.mode !== DICT) {
  6416. return Z_STREAM_ERROR;
  6417. }
  6418. /* check for correct dictionary identifier */
  6419. if (state.mode === DICT) {
  6420. dictid = 1; /* adler32(0, null, 0)*/
  6421. /* dictid = adler32(dictid, dictionary, dictLength); */
  6422. dictid = adler32(dictid, dictionary, dictLength, 0);
  6423. if (dictid !== state.check) {
  6424. return Z_DATA_ERROR;
  6425. }
  6426. }
  6427. /* copy dictionary to window using updatewindow(), which will amend the
  6428. existing dictionary if appropriate */
  6429. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  6430. if (ret) {
  6431. state.mode = MEM;
  6432. return Z_MEM_ERROR;
  6433. }
  6434. state.havedict = 1;
  6435. // Tracev((stderr, "inflate: dictionary set\n"));
  6436. return Z_OK;
  6437. }
  6438. exports.inflateReset = inflateReset;
  6439. exports.inflateReset2 = inflateReset2;
  6440. exports.inflateResetKeep = inflateResetKeep;
  6441. exports.inflateInit = inflateInit;
  6442. exports.inflateInit2 = inflateInit2;
  6443. exports.inflate = inflate;
  6444. exports.inflateEnd = inflateEnd;
  6445. exports.inflateGetHeader = inflateGetHeader;
  6446. exports.inflateSetDictionary = inflateSetDictionary;
  6447. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  6448. /* Not implemented
  6449. exports.inflateCopy = inflateCopy;
  6450. exports.inflateGetDictionary = inflateGetDictionary;
  6451. exports.inflateMark = inflateMark;
  6452. exports.inflatePrime = inflatePrime;
  6453. exports.inflateSync = inflateSync;
  6454. exports.inflateSyncPoint = inflateSyncPoint;
  6455. exports.inflateUndermine = inflateUndermine;
  6456. */
  6457. },{"../utils/common":35,"./adler32":36,"./crc32":38,"./inffast":40,"./inftrees":42}],42:[function(require,module,exports){
  6458. 'use strict';
  6459. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6460. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6461. //
  6462. // This software is provided 'as-is', without any express or implied
  6463. // warranty. In no event will the authors be held liable for any damages
  6464. // arising from the use of this software.
  6465. //
  6466. // Permission is granted to anyone to use this software for any purpose,
  6467. // including commercial applications, and to alter it and redistribute it
  6468. // freely, subject to the following restrictions:
  6469. //
  6470. // 1. The origin of this software must not be misrepresented; you must not
  6471. // claim that you wrote the original software. If you use this software
  6472. // in a product, an acknowledgment in the product documentation would be
  6473. // appreciated but is not required.
  6474. // 2. Altered source versions must be plainly marked as such, and must not be
  6475. // misrepresented as being the original software.
  6476. // 3. This notice may not be removed or altered from any source distribution.
  6477. var utils = require('../utils/common');
  6478. var MAXBITS = 15;
  6479. var ENOUGH_LENS = 852;
  6480. var ENOUGH_DISTS = 592;
  6481. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  6482. var CODES = 0;
  6483. var LENS = 1;
  6484. var DISTS = 2;
  6485. var lbase = [ /* Length codes 257..285 base */
  6486. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  6487. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  6488. ];
  6489. var lext = [ /* Length codes 257..285 extra */
  6490. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  6491. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  6492. ];
  6493. var dbase = [ /* Distance codes 0..29 base */
  6494. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  6495. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  6496. 8193, 12289, 16385, 24577, 0, 0
  6497. ];
  6498. var dext = [ /* Distance codes 0..29 extra */
  6499. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  6500. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  6501. 28, 28, 29, 29, 64, 64
  6502. ];
  6503. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  6504. {
  6505. var bits = opts.bits;
  6506. //here = opts.here; /* table entry for duplication */
  6507. var len = 0; /* a code's length in bits */
  6508. var sym = 0; /* index of code symbols */
  6509. var min = 0, max = 0; /* minimum and maximum code lengths */
  6510. var root = 0; /* number of index bits for root table */
  6511. var curr = 0; /* number of index bits for current table */
  6512. var drop = 0; /* code bits to drop for sub-table */
  6513. var left = 0; /* number of prefix codes available */
  6514. var used = 0; /* code entries in table used */
  6515. var huff = 0; /* Huffman code */
  6516. var incr; /* for incrementing code, index */
  6517. var fill; /* index for replicating entries */
  6518. var low; /* low bits for current root entry */
  6519. var mask; /* mask for low root bits */
  6520. var next; /* next available space in table */
  6521. var base = null; /* base value table to use */
  6522. var base_index = 0;
  6523. // var shoextra; /* extra bits table to use */
  6524. var end; /* use base and extra for symbol > end */
  6525. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  6526. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  6527. var extra = null;
  6528. var extra_index = 0;
  6529. var here_bits, here_op, here_val;
  6530. /*
  6531. Process a set of code lengths to create a canonical Huffman code. The
  6532. code lengths are lens[0..codes-1]. Each length corresponds to the
  6533. symbols 0..codes-1. The Huffman code is generated by first sorting the
  6534. symbols by length from short to long, and retaining the symbol order
  6535. for codes with equal lengths. Then the code starts with all zero bits
  6536. for the first code of the shortest length, and the codes are integer
  6537. increments for the same length, and zeros are appended as the length
  6538. increases. For the deflate format, these bits are stored backwards
  6539. from their more natural integer increment ordering, and so when the
  6540. decoding tables are built in the large loop below, the integer codes
  6541. are incremented backwards.
  6542. This routine assumes, but does not check, that all of the entries in
  6543. lens[] are in the range 0..MAXBITS. The caller must assure this.
  6544. 1..MAXBITS is interpreted as that code length. zero means that that
  6545. symbol does not occur in this code.
  6546. The codes are sorted by computing a count of codes for each length,
  6547. creating from that a table of starting indices for each length in the
  6548. sorted table, and then entering the symbols in order in the sorted
  6549. table. The sorted table is work[], with that space being provided by
  6550. the caller.
  6551. The length counts are used for other purposes as well, i.e. finding
  6552. the minimum and maximum length codes, determining if there are any
  6553. codes at all, checking for a valid set of lengths, and looking ahead
  6554. at length counts to determine sub-table sizes when building the
  6555. decoding tables.
  6556. */
  6557. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  6558. for (len = 0; len <= MAXBITS; len++) {
  6559. count[len] = 0;
  6560. }
  6561. for (sym = 0; sym < codes; sym++) {
  6562. count[lens[lens_index + sym]]++;
  6563. }
  6564. /* bound code lengths, force root to be within code lengths */
  6565. root = bits;
  6566. for (max = MAXBITS; max >= 1; max--) {
  6567. if (count[max] !== 0) { break; }
  6568. }
  6569. if (root > max) {
  6570. root = max;
  6571. }
  6572. if (max === 0) { /* no symbols to code at all */
  6573. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  6574. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  6575. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  6576. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6577. //table.op[opts.table_index] = 64;
  6578. //table.bits[opts.table_index] = 1;
  6579. //table.val[opts.table_index++] = 0;
  6580. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6581. opts.bits = 1;
  6582. return 0; /* no symbols, but wait for decoding to report error */
  6583. }
  6584. for (min = 1; min < max; min++) {
  6585. if (count[min] !== 0) { break; }
  6586. }
  6587. if (root < min) {
  6588. root = min;
  6589. }
  6590. /* check for an over-subscribed or incomplete set of lengths */
  6591. left = 1;
  6592. for (len = 1; len <= MAXBITS; len++) {
  6593. left <<= 1;
  6594. left -= count[len];
  6595. if (left < 0) {
  6596. return -1;
  6597. } /* over-subscribed */
  6598. }
  6599. if (left > 0 && (type === CODES || max !== 1)) {
  6600. return -1; /* incomplete set */
  6601. }
  6602. /* generate offsets into symbol table for each length for sorting */
  6603. offs[1] = 0;
  6604. for (len = 1; len < MAXBITS; len++) {
  6605. offs[len + 1] = offs[len] + count[len];
  6606. }
  6607. /* sort symbols by length, by symbol order within each length */
  6608. for (sym = 0; sym < codes; sym++) {
  6609. if (lens[lens_index + sym] !== 0) {
  6610. work[offs[lens[lens_index + sym]]++] = sym;
  6611. }
  6612. }
  6613. /*
  6614. Create and fill in decoding tables. In this loop, the table being
  6615. filled is at next and has curr index bits. The code being used is huff
  6616. with length len. That code is converted to an index by dropping drop
  6617. bits off of the bottom. For codes where len is less than drop + curr,
  6618. those top drop + curr - len bits are incremented through all values to
  6619. fill the table with replicated entries.
  6620. root is the number of index bits for the root table. When len exceeds
  6621. root, sub-tables are created pointed to by the root entry with an index
  6622. of the low root bits of huff. This is saved in low to check for when a
  6623. new sub-table should be started. drop is zero when the root table is
  6624. being filled, and drop is root when sub-tables are being filled.
  6625. When a new sub-table is needed, it is necessary to look ahead in the
  6626. code lengths to determine what size sub-table is needed. The length
  6627. counts are used for this, and so count[] is decremented as codes are
  6628. entered in the tables.
  6629. used keeps track of how many table entries have been allocated from the
  6630. provided *table space. It is checked for LENS and DIST tables against
  6631. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  6632. the initial root table size constants. See the comments in inftrees.h
  6633. for more information.
  6634. sym increments through all symbols, and the loop terminates when
  6635. all codes of length max, i.e. all codes, have been processed. This
  6636. routine permits incomplete codes, so another loop after this one fills
  6637. in the rest of the decoding tables with invalid code markers.
  6638. */
  6639. /* set up for code type */
  6640. // poor man optimization - use if-else instead of switch,
  6641. // to avoid deopts in old v8
  6642. if (type === CODES) {
  6643. base = extra = work; /* dummy value--not used */
  6644. end = 19;
  6645. } else if (type === LENS) {
  6646. base = lbase;
  6647. base_index -= 257;
  6648. extra = lext;
  6649. extra_index -= 257;
  6650. end = 256;
  6651. } else { /* DISTS */
  6652. base = dbase;
  6653. extra = dext;
  6654. end = -1;
  6655. }
  6656. /* initialize opts for loop */
  6657. huff = 0; /* starting code */
  6658. sym = 0; /* starting code symbol */
  6659. len = min; /* starting code length */
  6660. next = table_index; /* current table to fill in */
  6661. curr = root; /* current table index bits */
  6662. drop = 0; /* current bits to drop from code for index */
  6663. low = -1; /* trigger new sub-table when len > root */
  6664. used = 1 << root; /* use root table entries */
  6665. mask = used - 1; /* mask for comparing low */
  6666. /* check available table space */
  6667. if ((type === LENS && used > ENOUGH_LENS) ||
  6668. (type === DISTS && used > ENOUGH_DISTS)) {
  6669. return 1;
  6670. }
  6671. /* process all codes and make table entries */
  6672. for (;;) {
  6673. /* create table entry */
  6674. here_bits = len - drop;
  6675. if (work[sym] < end) {
  6676. here_op = 0;
  6677. here_val = work[sym];
  6678. }
  6679. else if (work[sym] > end) {
  6680. here_op = extra[extra_index + work[sym]];
  6681. here_val = base[base_index + work[sym]];
  6682. }
  6683. else {
  6684. here_op = 32 + 64; /* end of block */
  6685. here_val = 0;
  6686. }
  6687. /* replicate for those indices with low len bits equal to huff */
  6688. incr = 1 << (len - drop);
  6689. fill = 1 << curr;
  6690. min = fill; /* save offset to next table */
  6691. do {
  6692. fill -= incr;
  6693. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  6694. } while (fill !== 0);
  6695. /* backwards increment the len-bit code huff */
  6696. incr = 1 << (len - 1);
  6697. while (huff & incr) {
  6698. incr >>= 1;
  6699. }
  6700. if (incr !== 0) {
  6701. huff &= incr - 1;
  6702. huff += incr;
  6703. } else {
  6704. huff = 0;
  6705. }
  6706. /* go to next symbol, update count, len */
  6707. sym++;
  6708. if (--count[len] === 0) {
  6709. if (len === max) { break; }
  6710. len = lens[lens_index + work[sym]];
  6711. }
  6712. /* create new sub-table if needed */
  6713. if (len > root && (huff & mask) !== low) {
  6714. /* if first time, transition to sub-tables */
  6715. if (drop === 0) {
  6716. drop = root;
  6717. }
  6718. /* increment past last table */
  6719. next += min; /* here min is 1 << curr */
  6720. /* determine length of next table */
  6721. curr = len - drop;
  6722. left = 1 << curr;
  6723. while (curr + drop < max) {
  6724. left -= count[curr + drop];
  6725. if (left <= 0) { break; }
  6726. curr++;
  6727. left <<= 1;
  6728. }
  6729. /* check for enough space */
  6730. used += 1 << curr;
  6731. if ((type === LENS && used > ENOUGH_LENS) ||
  6732. (type === DISTS && used > ENOUGH_DISTS)) {
  6733. return 1;
  6734. }
  6735. /* point entry in root table to sub-table */
  6736. low = huff & mask;
  6737. /*table.op[low] = curr;
  6738. table.bits[low] = root;
  6739. table.val[low] = next - opts.table_index;*/
  6740. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  6741. }
  6742. }
  6743. /* fill in remaining table entry if code is incomplete (guaranteed to have
  6744. at most one remaining entry, since if the code is incomplete, the
  6745. maximum code length that was allowed to get this far is one bit) */
  6746. if (huff !== 0) {
  6747. //table.op[next + huff] = 64; /* invalid code marker */
  6748. //table.bits[next + huff] = len - drop;
  6749. //table.val[next + huff] = 0;
  6750. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  6751. }
  6752. /* set return parameters */
  6753. //opts.table_index += used;
  6754. opts.bits = root;
  6755. return 0;
  6756. };
  6757. },{"../utils/common":35}],43:[function(require,module,exports){
  6758. 'use strict';
  6759. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6760. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6761. //
  6762. // This software is provided 'as-is', without any express or implied
  6763. // warranty. In no event will the authors be held liable for any damages
  6764. // arising from the use of this software.
  6765. //
  6766. // Permission is granted to anyone to use this software for any purpose,
  6767. // including commercial applications, and to alter it and redistribute it
  6768. // freely, subject to the following restrictions:
  6769. //
  6770. // 1. The origin of this software must not be misrepresented; you must not
  6771. // claim that you wrote the original software. If you use this software
  6772. // in a product, an acknowledgment in the product documentation would be
  6773. // appreciated but is not required.
  6774. // 2. Altered source versions must be plainly marked as such, and must not be
  6775. // misrepresented as being the original software.
  6776. // 3. This notice may not be removed or altered from any source distribution.
  6777. module.exports = {
  6778. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  6779. 1: 'stream end', /* Z_STREAM_END 1 */
  6780. 0: '', /* Z_OK 0 */
  6781. '-1': 'file error', /* Z_ERRNO (-1) */
  6782. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  6783. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  6784. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  6785. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  6786. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  6787. };
  6788. },{}],44:[function(require,module,exports){
  6789. 'use strict';
  6790. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6791. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6792. //
  6793. // This software is provided 'as-is', without any express or implied
  6794. // warranty. In no event will the authors be held liable for any damages
  6795. // arising from the use of this software.
  6796. //
  6797. // Permission is granted to anyone to use this software for any purpose,
  6798. // including commercial applications, and to alter it and redistribute it
  6799. // freely, subject to the following restrictions:
  6800. //
  6801. // 1. The origin of this software must not be misrepresented; you must not
  6802. // claim that you wrote the original software. If you use this software
  6803. // in a product, an acknowledgment in the product documentation would be
  6804. // appreciated but is not required.
  6805. // 2. Altered source versions must be plainly marked as such, and must not be
  6806. // misrepresented as being the original software.
  6807. // 3. This notice may not be removed or altered from any source distribution.
  6808. /* eslint-disable space-unary-ops */
  6809. var utils = require('../utils/common');
  6810. /* Public constants ==========================================================*/
  6811. /* ===========================================================================*/
  6812. //var Z_FILTERED = 1;
  6813. //var Z_HUFFMAN_ONLY = 2;
  6814. //var Z_RLE = 3;
  6815. var Z_FIXED = 4;
  6816. //var Z_DEFAULT_STRATEGY = 0;
  6817. /* Possible values of the data_type field (though see inflate()) */
  6818. var Z_BINARY = 0;
  6819. var Z_TEXT = 1;
  6820. //var Z_ASCII = 1; // = Z_TEXT
  6821. var Z_UNKNOWN = 2;
  6822. /*============================================================================*/
  6823. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6824. // From zutil.h
  6825. var STORED_BLOCK = 0;
  6826. var STATIC_TREES = 1;
  6827. var DYN_TREES = 2;
  6828. /* The three kinds of block type */
  6829. var MIN_MATCH = 3;
  6830. var MAX_MATCH = 258;
  6831. /* The minimum and maximum match lengths */
  6832. // From deflate.h
  6833. /* ===========================================================================
  6834. * Internal compression state.
  6835. */
  6836. var LENGTH_CODES = 29;
  6837. /* number of length codes, not counting the special END_BLOCK code */
  6838. var LITERALS = 256;
  6839. /* number of literal bytes 0..255 */
  6840. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6841. /* number of Literal or Length codes, including the END_BLOCK code */
  6842. var D_CODES = 30;
  6843. /* number of distance codes */
  6844. var BL_CODES = 19;
  6845. /* number of codes used to transfer the bit lengths */
  6846. var HEAP_SIZE = 2 * L_CODES + 1;
  6847. /* maximum heap size */
  6848. var MAX_BITS = 15;
  6849. /* All codes must not exceed MAX_BITS bits */
  6850. var Buf_size = 16;
  6851. /* size of bit buffer in bi_buf */
  6852. /* ===========================================================================
  6853. * Constants
  6854. */
  6855. var MAX_BL_BITS = 7;
  6856. /* Bit length codes must not exceed MAX_BL_BITS bits */
  6857. var END_BLOCK = 256;
  6858. /* end of block literal code */
  6859. var REP_3_6 = 16;
  6860. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  6861. var REPZ_3_10 = 17;
  6862. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  6863. var REPZ_11_138 = 18;
  6864. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  6865. /* eslint-disable comma-spacing,array-bracket-spacing */
  6866. var extra_lbits = /* extra bits for each length code */
  6867. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  6868. var extra_dbits = /* extra bits for each distance code */
  6869. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  6870. var extra_blbits = /* extra bits for each bit length code */
  6871. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  6872. var bl_order =
  6873. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  6874. /* eslint-enable comma-spacing,array-bracket-spacing */
  6875. /* The lengths of the bit length codes are sent in order of decreasing
  6876. * probability, to avoid transmitting the lengths for unused bit length codes.
  6877. */
  6878. /* ===========================================================================
  6879. * Local data. These are initialized only once.
  6880. */
  6881. // We pre-fill arrays with 0 to avoid uninitialized gaps
  6882. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  6883. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  6884. var static_ltree = new Array((L_CODES + 2) * 2);
  6885. zero(static_ltree);
  6886. /* The static literal tree. Since the bit lengths are imposed, there is no
  6887. * need for the L_CODES extra codes used during heap construction. However
  6888. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  6889. * below).
  6890. */
  6891. var static_dtree = new Array(D_CODES * 2);
  6892. zero(static_dtree);
  6893. /* The static distance tree. (Actually a trivial tree since all codes use
  6894. * 5 bits.)
  6895. */
  6896. var _dist_code = new Array(DIST_CODE_LEN);
  6897. zero(_dist_code);
  6898. /* Distance codes. The first 256 values correspond to the distances
  6899. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  6900. * the 15 bit distances.
  6901. */
  6902. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  6903. zero(_length_code);
  6904. /* length code for each normalized match length (0 == MIN_MATCH) */
  6905. var base_length = new Array(LENGTH_CODES);
  6906. zero(base_length);
  6907. /* First normalized length for each code (0 = MIN_MATCH) */
  6908. var base_dist = new Array(D_CODES);
  6909. zero(base_dist);
  6910. /* First normalized distance for each code (0 = distance of 1) */
  6911. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  6912. this.static_tree = static_tree; /* static tree or NULL */
  6913. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  6914. this.extra_base = extra_base; /* base index for extra_bits */
  6915. this.elems = elems; /* max number of elements in the tree */
  6916. this.max_length = max_length; /* max bit length for the codes */
  6917. // show if `static_tree` has data or dummy - needed for monomorphic objects
  6918. this.has_stree = static_tree && static_tree.length;
  6919. }
  6920. var static_l_desc;
  6921. var static_d_desc;
  6922. var static_bl_desc;
  6923. function TreeDesc(dyn_tree, stat_desc) {
  6924. this.dyn_tree = dyn_tree; /* the dynamic tree */
  6925. this.max_code = 0; /* largest code with non zero frequency */
  6926. this.stat_desc = stat_desc; /* the corresponding static tree */
  6927. }
  6928. function d_code(dist) {
  6929. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  6930. }
  6931. /* ===========================================================================
  6932. * Output a short LSB first on the stream.
  6933. * IN assertion: there is enough room in pendingBuf.
  6934. */
  6935. function put_short(s, w) {
  6936. // put_byte(s, (uch)((w) & 0xff));
  6937. // put_byte(s, (uch)((ush)(w) >> 8));
  6938. s.pending_buf[s.pending++] = (w) & 0xff;
  6939. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  6940. }
  6941. /* ===========================================================================
  6942. * Send a value on a given number of bits.
  6943. * IN assertion: length <= 16 and value fits in length bits.
  6944. */
  6945. function send_bits(s, value, length) {
  6946. if (s.bi_valid > (Buf_size - length)) {
  6947. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  6948. put_short(s, s.bi_buf);
  6949. s.bi_buf = value >> (Buf_size - s.bi_valid);
  6950. s.bi_valid += length - Buf_size;
  6951. } else {
  6952. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  6953. s.bi_valid += length;
  6954. }
  6955. }
  6956. function send_code(s, c, tree) {
  6957. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  6958. }
  6959. /* ===========================================================================
  6960. * Reverse the first len bits of a code, using straightforward code (a faster
  6961. * method would use a table)
  6962. * IN assertion: 1 <= len <= 15
  6963. */
  6964. function bi_reverse(code, len) {
  6965. var res = 0;
  6966. do {
  6967. res |= code & 1;
  6968. code >>>= 1;
  6969. res <<= 1;
  6970. } while (--len > 0);
  6971. return res >>> 1;
  6972. }
  6973. /* ===========================================================================
  6974. * Flush the bit buffer, keeping at most 7 bits in it.
  6975. */
  6976. function bi_flush(s) {
  6977. if (s.bi_valid === 16) {
  6978. put_short(s, s.bi_buf);
  6979. s.bi_buf = 0;
  6980. s.bi_valid = 0;
  6981. } else if (s.bi_valid >= 8) {
  6982. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  6983. s.bi_buf >>= 8;
  6984. s.bi_valid -= 8;
  6985. }
  6986. }
  6987. /* ===========================================================================
  6988. * Compute the optimal bit lengths for a tree and update the total bit length
  6989. * for the current block.
  6990. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  6991. * above are the tree nodes sorted by increasing frequency.
  6992. * OUT assertions: the field len is set to the optimal bit length, the
  6993. * array bl_count contains the frequencies for each bit length.
  6994. * The length opt_len is updated; static_len is also updated if stree is
  6995. * not null.
  6996. */
  6997. function gen_bitlen(s, desc)
  6998. // deflate_state *s;
  6999. // tree_desc *desc; /* the tree descriptor */
  7000. {
  7001. var tree = desc.dyn_tree;
  7002. var max_code = desc.max_code;
  7003. var stree = desc.stat_desc.static_tree;
  7004. var has_stree = desc.stat_desc.has_stree;
  7005. var extra = desc.stat_desc.extra_bits;
  7006. var base = desc.stat_desc.extra_base;
  7007. var max_length = desc.stat_desc.max_length;
  7008. var h; /* heap index */
  7009. var n, m; /* iterate over the tree elements */
  7010. var bits; /* bit length */
  7011. var xbits; /* extra bits */
  7012. var f; /* frequency */
  7013. var overflow = 0; /* number of elements with bit length too large */
  7014. for (bits = 0; bits <= MAX_BITS; bits++) {
  7015. s.bl_count[bits] = 0;
  7016. }
  7017. /* In a first pass, compute the optimal bit lengths (which may
  7018. * overflow in the case of the bit length tree).
  7019. */
  7020. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  7021. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  7022. n = s.heap[h];
  7023. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  7024. if (bits > max_length) {
  7025. bits = max_length;
  7026. overflow++;
  7027. }
  7028. tree[n * 2 + 1]/*.Len*/ = bits;
  7029. /* We overwrite tree[n].Dad which is no longer needed */
  7030. if (n > max_code) { continue; } /* not a leaf node */
  7031. s.bl_count[bits]++;
  7032. xbits = 0;
  7033. if (n >= base) {
  7034. xbits = extra[n - base];
  7035. }
  7036. f = tree[n * 2]/*.Freq*/;
  7037. s.opt_len += f * (bits + xbits);
  7038. if (has_stree) {
  7039. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  7040. }
  7041. }
  7042. if (overflow === 0) { return; }
  7043. // Trace((stderr,"\nbit length overflow\n"));
  7044. /* This happens for example on obj2 and pic of the Calgary corpus */
  7045. /* Find the first bit length which could increase: */
  7046. do {
  7047. bits = max_length - 1;
  7048. while (s.bl_count[bits] === 0) { bits--; }
  7049. s.bl_count[bits]--; /* move one leaf down the tree */
  7050. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  7051. s.bl_count[max_length]--;
  7052. /* The brother of the overflow item also moves one step up,
  7053. * but this does not affect bl_count[max_length]
  7054. */
  7055. overflow -= 2;
  7056. } while (overflow > 0);
  7057. /* Now recompute all bit lengths, scanning in increasing frequency.
  7058. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  7059. * lengths instead of fixing only the wrong ones. This idea is taken
  7060. * from 'ar' written by Haruhiko Okumura.)
  7061. */
  7062. for (bits = max_length; bits !== 0; bits--) {
  7063. n = s.bl_count[bits];
  7064. while (n !== 0) {
  7065. m = s.heap[--h];
  7066. if (m > max_code) { continue; }
  7067. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  7068. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  7069. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  7070. tree[m * 2 + 1]/*.Len*/ = bits;
  7071. }
  7072. n--;
  7073. }
  7074. }
  7075. }
  7076. /* ===========================================================================
  7077. * Generate the codes for a given tree and bit counts (which need not be
  7078. * optimal).
  7079. * IN assertion: the array bl_count contains the bit length statistics for
  7080. * the given tree and the field len is set for all tree elements.
  7081. * OUT assertion: the field code is set for all tree elements of non
  7082. * zero code length.
  7083. */
  7084. function gen_codes(tree, max_code, bl_count)
  7085. // ct_data *tree; /* the tree to decorate */
  7086. // int max_code; /* largest code with non zero frequency */
  7087. // ushf *bl_count; /* number of codes at each bit length */
  7088. {
  7089. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  7090. var code = 0; /* running code value */
  7091. var bits; /* bit index */
  7092. var n; /* code index */
  7093. /* The distribution counts are first used to generate the code values
  7094. * without bit reversal.
  7095. */
  7096. for (bits = 1; bits <= MAX_BITS; bits++) {
  7097. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  7098. }
  7099. /* Check that the bit counts in bl_count are consistent. The last code
  7100. * must be all ones.
  7101. */
  7102. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  7103. // "inconsistent bit counts");
  7104. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  7105. for (n = 0; n <= max_code; n++) {
  7106. var len = tree[n * 2 + 1]/*.Len*/;
  7107. if (len === 0) { continue; }
  7108. /* Now reverse the bits */
  7109. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  7110. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  7111. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  7112. }
  7113. }
  7114. /* ===========================================================================
  7115. * Initialize the various 'constant' tables.
  7116. */
  7117. function tr_static_init() {
  7118. var n; /* iterates over tree elements */
  7119. var bits; /* bit counter */
  7120. var length; /* length value */
  7121. var code; /* code value */
  7122. var dist; /* distance index */
  7123. var bl_count = new Array(MAX_BITS + 1);
  7124. /* number of codes at each bit length for an optimal tree */
  7125. // do check in _tr_init()
  7126. //if (static_init_done) return;
  7127. /* For some embedded targets, global variables are not initialized: */
  7128. /*#ifdef NO_INIT_GLOBAL_POINTERS
  7129. static_l_desc.static_tree = static_ltree;
  7130. static_l_desc.extra_bits = extra_lbits;
  7131. static_d_desc.static_tree = static_dtree;
  7132. static_d_desc.extra_bits = extra_dbits;
  7133. static_bl_desc.extra_bits = extra_blbits;
  7134. #endif*/
  7135. /* Initialize the mapping length (0..255) -> length code (0..28) */
  7136. length = 0;
  7137. for (code = 0; code < LENGTH_CODES - 1; code++) {
  7138. base_length[code] = length;
  7139. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  7140. _length_code[length++] = code;
  7141. }
  7142. }
  7143. //Assert (length == 256, "tr_static_init: length != 256");
  7144. /* Note that the length 255 (match length 258) can be represented
  7145. * in two different ways: code 284 + 5 bits or code 285, so we
  7146. * overwrite length_code[255] to use the best encoding:
  7147. */
  7148. _length_code[length - 1] = code;
  7149. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  7150. dist = 0;
  7151. for (code = 0; code < 16; code++) {
  7152. base_dist[code] = dist;
  7153. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  7154. _dist_code[dist++] = code;
  7155. }
  7156. }
  7157. //Assert (dist == 256, "tr_static_init: dist != 256");
  7158. dist >>= 7; /* from now on, all distances are divided by 128 */
  7159. for (; code < D_CODES; code++) {
  7160. base_dist[code] = dist << 7;
  7161. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  7162. _dist_code[256 + dist++] = code;
  7163. }
  7164. }
  7165. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  7166. /* Construct the codes of the static literal tree */
  7167. for (bits = 0; bits <= MAX_BITS; bits++) {
  7168. bl_count[bits] = 0;
  7169. }
  7170. n = 0;
  7171. while (n <= 143) {
  7172. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  7173. n++;
  7174. bl_count[8]++;
  7175. }
  7176. while (n <= 255) {
  7177. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  7178. n++;
  7179. bl_count[9]++;
  7180. }
  7181. while (n <= 279) {
  7182. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  7183. n++;
  7184. bl_count[7]++;
  7185. }
  7186. while (n <= 287) {
  7187. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  7188. n++;
  7189. bl_count[8]++;
  7190. }
  7191. /* Codes 286 and 287 do not exist, but we must include them in the
  7192. * tree construction to get a canonical Huffman tree (longest code
  7193. * all ones)
  7194. */
  7195. gen_codes(static_ltree, L_CODES + 1, bl_count);
  7196. /* The static distance tree is trivial: */
  7197. for (n = 0; n < D_CODES; n++) {
  7198. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  7199. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  7200. }
  7201. // Now data ready and we can init static trees
  7202. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  7203. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  7204. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  7205. //static_init_done = true;
  7206. }
  7207. /* ===========================================================================
  7208. * Initialize a new block.
  7209. */
  7210. function init_block(s) {
  7211. var n; /* iterates over tree elements */
  7212. /* Initialize the trees. */
  7213. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  7214. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  7215. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  7216. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  7217. s.opt_len = s.static_len = 0;
  7218. s.last_lit = s.matches = 0;
  7219. }
  7220. /* ===========================================================================
  7221. * Flush the bit buffer and align the output on a byte boundary
  7222. */
  7223. function bi_windup(s)
  7224. {
  7225. if (s.bi_valid > 8) {
  7226. put_short(s, s.bi_buf);
  7227. } else if (s.bi_valid > 0) {
  7228. //put_byte(s, (Byte)s->bi_buf);
  7229. s.pending_buf[s.pending++] = s.bi_buf;
  7230. }
  7231. s.bi_buf = 0;
  7232. s.bi_valid = 0;
  7233. }
  7234. /* ===========================================================================
  7235. * Copy a stored block, storing first the length and its
  7236. * one's complement if requested.
  7237. */
  7238. function copy_block(s, buf, len, header)
  7239. //DeflateState *s;
  7240. //charf *buf; /* the input data */
  7241. //unsigned len; /* its length */
  7242. //int header; /* true if block header must be written */
  7243. {
  7244. bi_windup(s); /* align on byte boundary */
  7245. if (header) {
  7246. put_short(s, len);
  7247. put_short(s, ~len);
  7248. }
  7249. // while (len--) {
  7250. // put_byte(s, *buf++);
  7251. // }
  7252. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  7253. s.pending += len;
  7254. }
  7255. /* ===========================================================================
  7256. * Compares to subtrees, using the tree depth as tie breaker when
  7257. * the subtrees have equal frequency. This minimizes the worst case length.
  7258. */
  7259. function smaller(tree, n, m, depth) {
  7260. var _n2 = n * 2;
  7261. var _m2 = m * 2;
  7262. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  7263. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  7264. }
  7265. /* ===========================================================================
  7266. * Restore the heap property by moving down the tree starting at node k,
  7267. * exchanging a node with the smallest of its two sons if necessary, stopping
  7268. * when the heap property is re-established (each father smaller than its
  7269. * two sons).
  7270. */
  7271. function pqdownheap(s, tree, k)
  7272. // deflate_state *s;
  7273. // ct_data *tree; /* the tree to restore */
  7274. // int k; /* node to move down */
  7275. {
  7276. var v = s.heap[k];
  7277. var j = k << 1; /* left son of k */
  7278. while (j <= s.heap_len) {
  7279. /* Set j to the smallest of the two sons: */
  7280. if (j < s.heap_len &&
  7281. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  7282. j++;
  7283. }
  7284. /* Exit if v is smaller than both sons */
  7285. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  7286. /* Exchange v with the smallest son */
  7287. s.heap[k] = s.heap[j];
  7288. k = j;
  7289. /* And continue down the tree, setting j to the left son of k */
  7290. j <<= 1;
  7291. }
  7292. s.heap[k] = v;
  7293. }
  7294. // inlined manually
  7295. // var SMALLEST = 1;
  7296. /* ===========================================================================
  7297. * Send the block data compressed using the given Huffman trees
  7298. */
  7299. function compress_block(s, ltree, dtree)
  7300. // deflate_state *s;
  7301. // const ct_data *ltree; /* literal tree */
  7302. // const ct_data *dtree; /* distance tree */
  7303. {
  7304. var dist; /* distance of matched string */
  7305. var lc; /* match length or unmatched char (if dist == 0) */
  7306. var lx = 0; /* running index in l_buf */
  7307. var code; /* the code to send */
  7308. var extra; /* number of extra bits to send */
  7309. if (s.last_lit !== 0) {
  7310. do {
  7311. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  7312. lc = s.pending_buf[s.l_buf + lx];
  7313. lx++;
  7314. if (dist === 0) {
  7315. send_code(s, lc, ltree); /* send a literal byte */
  7316. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  7317. } else {
  7318. /* Here, lc is the match length - MIN_MATCH */
  7319. code = _length_code[lc];
  7320. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  7321. extra = extra_lbits[code];
  7322. if (extra !== 0) {
  7323. lc -= base_length[code];
  7324. send_bits(s, lc, extra); /* send the extra length bits */
  7325. }
  7326. dist--; /* dist is now the match distance - 1 */
  7327. code = d_code(dist);
  7328. //Assert (code < D_CODES, "bad d_code");
  7329. send_code(s, code, dtree); /* send the distance code */
  7330. extra = extra_dbits[code];
  7331. if (extra !== 0) {
  7332. dist -= base_dist[code];
  7333. send_bits(s, dist, extra); /* send the extra distance bits */
  7334. }
  7335. } /* literal or match pair ? */
  7336. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  7337. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  7338. // "pendingBuf overflow");
  7339. } while (lx < s.last_lit);
  7340. }
  7341. send_code(s, END_BLOCK, ltree);
  7342. }
  7343. /* ===========================================================================
  7344. * Construct one Huffman tree and assigns the code bit strings and lengths.
  7345. * Update the total bit length for the current block.
  7346. * IN assertion: the field freq is set for all tree elements.
  7347. * OUT assertions: the fields len and code are set to the optimal bit length
  7348. * and corresponding code. The length opt_len is updated; static_len is
  7349. * also updated if stree is not null. The field max_code is set.
  7350. */
  7351. function build_tree(s, desc)
  7352. // deflate_state *s;
  7353. // tree_desc *desc; /* the tree descriptor */
  7354. {
  7355. var tree = desc.dyn_tree;
  7356. var stree = desc.stat_desc.static_tree;
  7357. var has_stree = desc.stat_desc.has_stree;
  7358. var elems = desc.stat_desc.elems;
  7359. var n, m; /* iterate over heap elements */
  7360. var max_code = -1; /* largest code with non zero frequency */
  7361. var node; /* new node being created */
  7362. /* Construct the initial heap, with least frequent element in
  7363. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  7364. * heap[0] is not used.
  7365. */
  7366. s.heap_len = 0;
  7367. s.heap_max = HEAP_SIZE;
  7368. for (n = 0; n < elems; n++) {
  7369. if (tree[n * 2]/*.Freq*/ !== 0) {
  7370. s.heap[++s.heap_len] = max_code = n;
  7371. s.depth[n] = 0;
  7372. } else {
  7373. tree[n * 2 + 1]/*.Len*/ = 0;
  7374. }
  7375. }
  7376. /* The pkzip format requires that at least one distance code exists,
  7377. * and that at least one bit should be sent even if there is only one
  7378. * possible code. So to avoid special checks later on we force at least
  7379. * two codes of non zero frequency.
  7380. */
  7381. while (s.heap_len < 2) {
  7382. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  7383. tree[node * 2]/*.Freq*/ = 1;
  7384. s.depth[node] = 0;
  7385. s.opt_len--;
  7386. if (has_stree) {
  7387. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  7388. }
  7389. /* node is 0 or 1 so it does not have extra bits */
  7390. }
  7391. desc.max_code = max_code;
  7392. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  7393. * establish sub-heaps of increasing lengths:
  7394. */
  7395. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  7396. /* Construct the Huffman tree by repeatedly combining the least two
  7397. * frequent nodes.
  7398. */
  7399. node = elems; /* next internal node of the tree */
  7400. do {
  7401. //pqremove(s, tree, n); /* n = node of least frequency */
  7402. /*** pqremove ***/
  7403. n = s.heap[1/*SMALLEST*/];
  7404. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  7405. pqdownheap(s, tree, 1/*SMALLEST*/);
  7406. /***/
  7407. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  7408. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  7409. s.heap[--s.heap_max] = m;
  7410. /* Create a new node father of n and m */
  7411. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  7412. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  7413. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  7414. /* and insert the new node in the heap */
  7415. s.heap[1/*SMALLEST*/] = node++;
  7416. pqdownheap(s, tree, 1/*SMALLEST*/);
  7417. } while (s.heap_len >= 2);
  7418. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  7419. /* At this point, the fields freq and dad are set. We can now
  7420. * generate the bit lengths.
  7421. */
  7422. gen_bitlen(s, desc);
  7423. /* The field len is now set, we can generate the bit codes */
  7424. gen_codes(tree, max_code, s.bl_count);
  7425. }
  7426. /* ===========================================================================
  7427. * Scan a literal or distance tree to determine the frequencies of the codes
  7428. * in the bit length tree.
  7429. */
  7430. function scan_tree(s, tree, max_code)
  7431. // deflate_state *s;
  7432. // ct_data *tree; /* the tree to be scanned */
  7433. // int max_code; /* and its largest code of non zero frequency */
  7434. {
  7435. var n; /* iterates over all tree elements */
  7436. var prevlen = -1; /* last emitted length */
  7437. var curlen; /* length of current code */
  7438. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  7439. var count = 0; /* repeat count of the current code */
  7440. var max_count = 7; /* max repeat count */
  7441. var min_count = 4; /* min repeat count */
  7442. if (nextlen === 0) {
  7443. max_count = 138;
  7444. min_count = 3;
  7445. }
  7446. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  7447. for (n = 0; n <= max_code; n++) {
  7448. curlen = nextlen;
  7449. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  7450. if (++count < max_count && curlen === nextlen) {
  7451. continue;
  7452. } else if (count < min_count) {
  7453. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  7454. } else if (curlen !== 0) {
  7455. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  7456. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  7457. } else if (count <= 10) {
  7458. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  7459. } else {
  7460. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  7461. }
  7462. count = 0;
  7463. prevlen = curlen;
  7464. if (nextlen === 0) {
  7465. max_count = 138;
  7466. min_count = 3;
  7467. } else if (curlen === nextlen) {
  7468. max_count = 6;
  7469. min_count = 3;
  7470. } else {
  7471. max_count = 7;
  7472. min_count = 4;
  7473. }
  7474. }
  7475. }
  7476. /* ===========================================================================
  7477. * Send a literal or distance tree in compressed form, using the codes in
  7478. * bl_tree.
  7479. */
  7480. function send_tree(s, tree, max_code)
  7481. // deflate_state *s;
  7482. // ct_data *tree; /* the tree to be scanned */
  7483. // int max_code; /* and its largest code of non zero frequency */
  7484. {
  7485. var n; /* iterates over all tree elements */
  7486. var prevlen = -1; /* last emitted length */
  7487. var curlen; /* length of current code */
  7488. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  7489. var count = 0; /* repeat count of the current code */
  7490. var max_count = 7; /* max repeat count */
  7491. var min_count = 4; /* min repeat count */
  7492. /* tree[max_code+1].Len = -1; */ /* guard already set */
  7493. if (nextlen === 0) {
  7494. max_count = 138;
  7495. min_count = 3;
  7496. }
  7497. for (n = 0; n <= max_code; n++) {
  7498. curlen = nextlen;
  7499. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  7500. if (++count < max_count && curlen === nextlen) {
  7501. continue;
  7502. } else if (count < min_count) {
  7503. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  7504. } else if (curlen !== 0) {
  7505. if (curlen !== prevlen) {
  7506. send_code(s, curlen, s.bl_tree);
  7507. count--;
  7508. }
  7509. //Assert(count >= 3 && count <= 6, " 3_6?");
  7510. send_code(s, REP_3_6, s.bl_tree);
  7511. send_bits(s, count - 3, 2);
  7512. } else if (count <= 10) {
  7513. send_code(s, REPZ_3_10, s.bl_tree);
  7514. send_bits(s, count - 3, 3);
  7515. } else {
  7516. send_code(s, REPZ_11_138, s.bl_tree);
  7517. send_bits(s, count - 11, 7);
  7518. }
  7519. count = 0;
  7520. prevlen = curlen;
  7521. if (nextlen === 0) {
  7522. max_count = 138;
  7523. min_count = 3;
  7524. } else if (curlen === nextlen) {
  7525. max_count = 6;
  7526. min_count = 3;
  7527. } else {
  7528. max_count = 7;
  7529. min_count = 4;
  7530. }
  7531. }
  7532. }
  7533. /* ===========================================================================
  7534. * Construct the Huffman tree for the bit lengths and return the index in
  7535. * bl_order of the last bit length code to send.
  7536. */
  7537. function build_bl_tree(s) {
  7538. var max_blindex; /* index of last bit length code of non zero freq */
  7539. /* Determine the bit length frequencies for literal and distance trees */
  7540. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  7541. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  7542. /* Build the bit length tree: */
  7543. build_tree(s, s.bl_desc);
  7544. /* opt_len now includes the length of the tree representations, except
  7545. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  7546. */
  7547. /* Determine the number of bit length codes to send. The pkzip format
  7548. * requires that at least 4 bit length codes be sent. (appnote.txt says
  7549. * 3 but the actual value used is 4.)
  7550. */
  7551. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  7552. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  7553. break;
  7554. }
  7555. }
  7556. /* Update opt_len to include the bit length tree and counts */
  7557. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  7558. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  7559. // s->opt_len, s->static_len));
  7560. return max_blindex;
  7561. }
  7562. /* ===========================================================================
  7563. * Send the header for a block using dynamic Huffman trees: the counts, the
  7564. * lengths of the bit length codes, the literal tree and the distance tree.
  7565. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  7566. */
  7567. function send_all_trees(s, lcodes, dcodes, blcodes)
  7568. // deflate_state *s;
  7569. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  7570. {
  7571. var rank; /* index in bl_order */
  7572. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  7573. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  7574. // "too many codes");
  7575. //Tracev((stderr, "\nbl counts: "));
  7576. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  7577. send_bits(s, dcodes - 1, 5);
  7578. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  7579. for (rank = 0; rank < blcodes; rank++) {
  7580. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  7581. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  7582. }
  7583. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  7584. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  7585. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  7586. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  7587. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  7588. }
  7589. /* ===========================================================================
  7590. * Check if the data type is TEXT or BINARY, using the following algorithm:
  7591. * - TEXT if the two conditions below are satisfied:
  7592. * a) There are no non-portable control characters belonging to the
  7593. * "black list" (0..6, 14..25, 28..31).
  7594. * b) There is at least one printable character belonging to the
  7595. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  7596. * - BINARY otherwise.
  7597. * - The following partially-portable control characters form a
  7598. * "gray list" that is ignored in this detection algorithm:
  7599. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  7600. * IN assertion: the fields Freq of dyn_ltree are set.
  7601. */
  7602. function detect_data_type(s) {
  7603. /* black_mask is the bit mask of black-listed bytes
  7604. * set bits 0..6, 14..25, and 28..31
  7605. * 0xf3ffc07f = binary 11110011111111111100000001111111
  7606. */
  7607. var black_mask = 0xf3ffc07f;
  7608. var n;
  7609. /* Check for non-textual ("black-listed") bytes. */
  7610. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  7611. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  7612. return Z_BINARY;
  7613. }
  7614. }
  7615. /* Check for textual ("white-listed") bytes. */
  7616. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  7617. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  7618. return Z_TEXT;
  7619. }
  7620. for (n = 32; n < LITERALS; n++) {
  7621. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  7622. return Z_TEXT;
  7623. }
  7624. }
  7625. /* There are no "black-listed" or "white-listed" bytes:
  7626. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  7627. */
  7628. return Z_BINARY;
  7629. }
  7630. var static_init_done = false;
  7631. /* ===========================================================================
  7632. * Initialize the tree data structures for a new zlib stream.
  7633. */
  7634. function _tr_init(s)
  7635. {
  7636. if (!static_init_done) {
  7637. tr_static_init();
  7638. static_init_done = true;
  7639. }
  7640. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  7641. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  7642. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  7643. s.bi_buf = 0;
  7644. s.bi_valid = 0;
  7645. /* Initialize the first block of the first file: */
  7646. init_block(s);
  7647. }
  7648. /* ===========================================================================
  7649. * Send a stored block
  7650. */
  7651. function _tr_stored_block(s, buf, stored_len, last)
  7652. //DeflateState *s;
  7653. //charf *buf; /* input block */
  7654. //ulg stored_len; /* length of input block */
  7655. //int last; /* one if this is the last block for a file */
  7656. {
  7657. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  7658. copy_block(s, buf, stored_len, true); /* with header */
  7659. }
  7660. /* ===========================================================================
  7661. * Send one empty static block to give enough lookahead for inflate.
  7662. * This takes 10 bits, of which 7 may remain in the bit buffer.
  7663. */
  7664. function _tr_align(s) {
  7665. send_bits(s, STATIC_TREES << 1, 3);
  7666. send_code(s, END_BLOCK, static_ltree);
  7667. bi_flush(s);
  7668. }
  7669. /* ===========================================================================
  7670. * Determine the best encoding for the current block: dynamic trees, static
  7671. * trees or store, and output the encoded block to the zip file.
  7672. */
  7673. function _tr_flush_block(s, buf, stored_len, last)
  7674. //DeflateState *s;
  7675. //charf *buf; /* input block, or NULL if too old */
  7676. //ulg stored_len; /* length of input block */
  7677. //int last; /* one if this is the last block for a file */
  7678. {
  7679. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  7680. var max_blindex = 0; /* index of last bit length code of non zero freq */
  7681. /* Build the Huffman trees unless a stored block is forced */
  7682. if (s.level > 0) {
  7683. /* Check if the file is binary or text */
  7684. if (s.strm.data_type === Z_UNKNOWN) {
  7685. s.strm.data_type = detect_data_type(s);
  7686. }
  7687. /* Construct the literal and distance trees */
  7688. build_tree(s, s.l_desc);
  7689. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  7690. // s->static_len));
  7691. build_tree(s, s.d_desc);
  7692. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  7693. // s->static_len));
  7694. /* At this point, opt_len and static_len are the total bit lengths of
  7695. * the compressed block data, excluding the tree representations.
  7696. */
  7697. /* Build the bit length tree for the above two trees, and get the index
  7698. * in bl_order of the last bit length code to send.
  7699. */
  7700. max_blindex = build_bl_tree(s);
  7701. /* Determine the best encoding. Compute the block lengths in bytes. */
  7702. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  7703. static_lenb = (s.static_len + 3 + 7) >>> 3;
  7704. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  7705. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  7706. // s->last_lit));
  7707. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  7708. } else {
  7709. // Assert(buf != (char*)0, "lost buf");
  7710. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  7711. }
  7712. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  7713. /* 4: two words for the lengths */
  7714. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  7715. * Otherwise we can't have processed more than WSIZE input bytes since
  7716. * the last block flush, because compression would have been
  7717. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  7718. * transform a block into a stored block.
  7719. */
  7720. _tr_stored_block(s, buf, stored_len, last);
  7721. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  7722. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  7723. compress_block(s, static_ltree, static_dtree);
  7724. } else {
  7725. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  7726. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  7727. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  7728. }
  7729. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  7730. /* The above check is made mod 2^32, for files larger than 512 MB
  7731. * and uLong implemented on 32 bits.
  7732. */
  7733. init_block(s);
  7734. if (last) {
  7735. bi_windup(s);
  7736. }
  7737. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  7738. // s->compressed_len-7*last));
  7739. }
  7740. /* ===========================================================================
  7741. * Save the match info and tally the frequency counts. Return true if
  7742. * the current block must be flushed.
  7743. */
  7744. function _tr_tally(s, dist, lc)
  7745. // deflate_state *s;
  7746. // unsigned dist; /* distance of matched string */
  7747. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  7748. {
  7749. //var out_length, in_length, dcode;
  7750. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  7751. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  7752. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  7753. s.last_lit++;
  7754. if (dist === 0) {
  7755. /* lc is the unmatched char */
  7756. s.dyn_ltree[lc * 2]/*.Freq*/++;
  7757. } else {
  7758. s.matches++;
  7759. /* Here, lc is the match length - MIN_MATCH */
  7760. dist--; /* dist = match distance - 1 */
  7761. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  7762. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  7763. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  7764. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  7765. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  7766. }
  7767. // (!) This block is disabled in zlib defaults,
  7768. // don't enable it for binary compatibility
  7769. //#ifdef TRUNCATE_BLOCK
  7770. // /* Try to guess if it is profitable to stop the current block here */
  7771. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  7772. // /* Compute an upper bound for the compressed length */
  7773. // out_length = s.last_lit*8;
  7774. // in_length = s.strstart - s.block_start;
  7775. //
  7776. // for (dcode = 0; dcode < D_CODES; dcode++) {
  7777. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  7778. // }
  7779. // out_length >>>= 3;
  7780. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  7781. // // s->last_lit, in_length, out_length,
  7782. // // 100L - out_length*100L/in_length));
  7783. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  7784. // return true;
  7785. // }
  7786. // }
  7787. //#endif
  7788. return (s.last_lit === s.lit_bufsize - 1);
  7789. /* We avoid equality with lit_bufsize because of wraparound at 64K
  7790. * on 16 bit machines and because stored blocks are restricted to
  7791. * 64K-1 bytes.
  7792. */
  7793. }
  7794. exports._tr_init = _tr_init;
  7795. exports._tr_stored_block = _tr_stored_block;
  7796. exports._tr_flush_block = _tr_flush_block;
  7797. exports._tr_tally = _tr_tally;
  7798. exports._tr_align = _tr_align;
  7799. },{"../utils/common":35}],45:[function(require,module,exports){
  7800. 'use strict';
  7801. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7802. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7803. //
  7804. // This software is provided 'as-is', without any express or implied
  7805. // warranty. In no event will the authors be held liable for any damages
  7806. // arising from the use of this software.
  7807. //
  7808. // Permission is granted to anyone to use this software for any purpose,
  7809. // including commercial applications, and to alter it and redistribute it
  7810. // freely, subject to the following restrictions:
  7811. //
  7812. // 1. The origin of this software must not be misrepresented; you must not
  7813. // claim that you wrote the original software. If you use this software
  7814. // in a product, an acknowledgment in the product documentation would be
  7815. // appreciated but is not required.
  7816. // 2. Altered source versions must be plainly marked as such, and must not be
  7817. // misrepresented as being the original software.
  7818. // 3. This notice may not be removed or altered from any source distribution.
  7819. function ZStream() {
  7820. /* next input byte */
  7821. this.input = null; // JS specific, because we have no pointers
  7822. this.next_in = 0;
  7823. /* number of bytes available at input */
  7824. this.avail_in = 0;
  7825. /* total number of input bytes read so far */
  7826. this.total_in = 0;
  7827. /* next output byte should be put there */
  7828. this.output = null; // JS specific, because we have no pointers
  7829. this.next_out = 0;
  7830. /* remaining free space at output */
  7831. this.avail_out = 0;
  7832. /* total number of bytes output so far */
  7833. this.total_out = 0;
  7834. /* last error message, NULL if no error */
  7835. this.msg = ''/*Z_NULL*/;
  7836. /* not visible by applications */
  7837. this.state = null;
  7838. /* best guess about the data type: binary or text */
  7839. this.data_type = 2/*Z_UNKNOWN*/;
  7840. /* adler32 value of the uncompressed data */
  7841. this.adler = 0;
  7842. }
  7843. module.exports = ZStream;
  7844. },{}],46:[function(require,module,exports){
  7845. arguments[4][32][0].apply(exports,arguments)
  7846. },{"dup":32}],47:[function(require,module,exports){
  7847. (function (Buffer){
  7848. /*!
  7849. * The buffer module from node.js, for the browser.
  7850. *
  7851. * @author Feross Aboukhadijeh <https://feross.org>
  7852. * @license MIT
  7853. */
  7854. /* eslint-disable no-proto */
  7855. 'use strict'
  7856. var base64 = require('base64-js')
  7857. var ieee754 = require('ieee754')
  7858. var customInspectSymbol =
  7859. (typeof Symbol === 'function' && typeof Symbol.for === 'function')
  7860. ? Symbol.for('nodejs.util.inspect.custom')
  7861. : null
  7862. exports.Buffer = Buffer
  7863. exports.SlowBuffer = SlowBuffer
  7864. exports.INSPECT_MAX_BYTES = 50
  7865. var K_MAX_LENGTH = 0x7fffffff
  7866. exports.kMaxLength = K_MAX_LENGTH
  7867. /**
  7868. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  7869. * === true Use Uint8Array implementation (fastest)
  7870. * === false Print warning and recommend using `buffer` v4.x which has an Object
  7871. * implementation (most compatible, even IE6)
  7872. *
  7873. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  7874. * Opera 11.6+, iOS 4.2+.
  7875. *
  7876. * We report that the browser does not support typed arrays if the are not subclassable
  7877. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  7878. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  7879. * for __proto__ and has a buggy typed array implementation.
  7880. */
  7881. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  7882. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  7883. typeof console.error === 'function') {
  7884. console.error(
  7885. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  7886. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  7887. )
  7888. }
  7889. function typedArraySupport () {
  7890. // Can typed array instances can be augmented?
  7891. try {
  7892. var arr = new Uint8Array(1)
  7893. var proto = { foo: function () { return 42 } }
  7894. Object.setPrototypeOf(proto, Uint8Array.prototype)
  7895. Object.setPrototypeOf(arr, proto)
  7896. return arr.foo() === 42
  7897. } catch (e) {
  7898. return false
  7899. }
  7900. }
  7901. Object.defineProperty(Buffer.prototype, 'parent', {
  7902. enumerable: true,
  7903. get: function () {
  7904. if (!Buffer.isBuffer(this)) return undefined
  7905. return this.buffer
  7906. }
  7907. })
  7908. Object.defineProperty(Buffer.prototype, 'offset', {
  7909. enumerable: true,
  7910. get: function () {
  7911. if (!Buffer.isBuffer(this)) return undefined
  7912. return this.byteOffset
  7913. }
  7914. })
  7915. function createBuffer (length) {
  7916. if (length > K_MAX_LENGTH) {
  7917. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  7918. }
  7919. // Return an augmented `Uint8Array` instance
  7920. var buf = new Uint8Array(length)
  7921. Object.setPrototypeOf(buf, Buffer.prototype)
  7922. return buf
  7923. }
  7924. /**
  7925. * The Buffer constructor returns instances of `Uint8Array` that have their
  7926. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  7927. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  7928. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  7929. * returns a single octet.
  7930. *
  7931. * The `Uint8Array` prototype remains unmodified.
  7932. */
  7933. function Buffer (arg, encodingOrOffset, length) {
  7934. // Common case.
  7935. if (typeof arg === 'number') {
  7936. if (typeof encodingOrOffset === 'string') {
  7937. throw new TypeError(
  7938. 'The "string" argument must be of type string. Received type number'
  7939. )
  7940. }
  7941. return allocUnsafe(arg)
  7942. }
  7943. return from(arg, encodingOrOffset, length)
  7944. }
  7945. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  7946. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  7947. Buffer[Symbol.species] === Buffer) {
  7948. Object.defineProperty(Buffer, Symbol.species, {
  7949. value: null,
  7950. configurable: true,
  7951. enumerable: false,
  7952. writable: false
  7953. })
  7954. }
  7955. Buffer.poolSize = 8192 // not used by this implementation
  7956. function from (value, encodingOrOffset, length) {
  7957. if (typeof value === 'string') {
  7958. return fromString(value, encodingOrOffset)
  7959. }
  7960. if (ArrayBuffer.isView(value)) {
  7961. return fromArrayLike(value)
  7962. }
  7963. if (value == null) {
  7964. throw new TypeError(
  7965. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  7966. 'or Array-like Object. Received type ' + (typeof value)
  7967. )
  7968. }
  7969. if (isInstance(value, ArrayBuffer) ||
  7970. (value && isInstance(value.buffer, ArrayBuffer))) {
  7971. return fromArrayBuffer(value, encodingOrOffset, length)
  7972. }
  7973. if (typeof value === 'number') {
  7974. throw new TypeError(
  7975. 'The "value" argument must not be of type number. Received type number'
  7976. )
  7977. }
  7978. var valueOf = value.valueOf && value.valueOf()
  7979. if (valueOf != null && valueOf !== value) {
  7980. return Buffer.from(valueOf, encodingOrOffset, length)
  7981. }
  7982. var b = fromObject(value)
  7983. if (b) return b
  7984. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  7985. typeof value[Symbol.toPrimitive] === 'function') {
  7986. return Buffer.from(
  7987. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  7988. )
  7989. }
  7990. throw new TypeError(
  7991. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  7992. 'or Array-like Object. Received type ' + (typeof value)
  7993. )
  7994. }
  7995. /**
  7996. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  7997. * if value is a number.
  7998. * Buffer.from(str[, encoding])
  7999. * Buffer.from(array)
  8000. * Buffer.from(buffer)
  8001. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  8002. **/
  8003. Buffer.from = function (value, encodingOrOffset, length) {
  8004. return from(value, encodingOrOffset, length)
  8005. }
  8006. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  8007. // https://github.com/feross/buffer/pull/148
  8008. Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
  8009. Object.setPrototypeOf(Buffer, Uint8Array)
  8010. function assertSize (size) {
  8011. if (typeof size !== 'number') {
  8012. throw new TypeError('"size" argument must be of type number')
  8013. } else if (size < 0) {
  8014. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  8015. }
  8016. }
  8017. function alloc (size, fill, encoding) {
  8018. assertSize(size)
  8019. if (size <= 0) {
  8020. return createBuffer(size)
  8021. }
  8022. if (fill !== undefined) {
  8023. // Only pay attention to encoding if it's a string. This
  8024. // prevents accidentally sending in a number that would
  8025. // be interpretted as a start offset.
  8026. return typeof encoding === 'string'
  8027. ? createBuffer(size).fill(fill, encoding)
  8028. : createBuffer(size).fill(fill)
  8029. }
  8030. return createBuffer(size)
  8031. }
  8032. /**
  8033. * Creates a new filled Buffer instance.
  8034. * alloc(size[, fill[, encoding]])
  8035. **/
  8036. Buffer.alloc = function (size, fill, encoding) {
  8037. return alloc(size, fill, encoding)
  8038. }
  8039. function allocUnsafe (size) {
  8040. assertSize(size)
  8041. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  8042. }
  8043. /**
  8044. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  8045. * */
  8046. Buffer.allocUnsafe = function (size) {
  8047. return allocUnsafe(size)
  8048. }
  8049. /**
  8050. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  8051. */
  8052. Buffer.allocUnsafeSlow = function (size) {
  8053. return allocUnsafe(size)
  8054. }
  8055. function fromString (string, encoding) {
  8056. if (typeof encoding !== 'string' || encoding === '') {
  8057. encoding = 'utf8'
  8058. }
  8059. if (!Buffer.isEncoding(encoding)) {
  8060. throw new TypeError('Unknown encoding: ' + encoding)
  8061. }
  8062. var length = byteLength(string, encoding) | 0
  8063. var buf = createBuffer(length)
  8064. var actual = buf.write(string, encoding)
  8065. if (actual !== length) {
  8066. // Writing a hex string, for example, that contains invalid characters will
  8067. // cause everything after the first invalid character to be ignored. (e.g.
  8068. // 'abxxcd' will be treated as 'ab')
  8069. buf = buf.slice(0, actual)
  8070. }
  8071. return buf
  8072. }
  8073. function fromArrayLike (array) {
  8074. var length = array.length < 0 ? 0 : checked(array.length) | 0
  8075. var buf = createBuffer(length)
  8076. for (var i = 0; i < length; i += 1) {
  8077. buf[i] = array[i] & 255
  8078. }
  8079. return buf
  8080. }
  8081. function fromArrayBuffer (array, byteOffset, length) {
  8082. if (byteOffset < 0 || array.byteLength < byteOffset) {
  8083. throw new RangeError('"offset" is outside of buffer bounds')
  8084. }
  8085. if (array.byteLength < byteOffset + (length || 0)) {
  8086. throw new RangeError('"length" is outside of buffer bounds')
  8087. }
  8088. var buf
  8089. if (byteOffset === undefined && length === undefined) {
  8090. buf = new Uint8Array(array)
  8091. } else if (length === undefined) {
  8092. buf = new Uint8Array(array, byteOffset)
  8093. } else {
  8094. buf = new Uint8Array(array, byteOffset, length)
  8095. }
  8096. // Return an augmented `Uint8Array` instance
  8097. Object.setPrototypeOf(buf, Buffer.prototype)
  8098. return buf
  8099. }
  8100. function fromObject (obj) {
  8101. if (Buffer.isBuffer(obj)) {
  8102. var len = checked(obj.length) | 0
  8103. var buf = createBuffer(len)
  8104. if (buf.length === 0) {
  8105. return buf
  8106. }
  8107. obj.copy(buf, 0, 0, len)
  8108. return buf
  8109. }
  8110. if (obj.length !== undefined) {
  8111. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  8112. return createBuffer(0)
  8113. }
  8114. return fromArrayLike(obj)
  8115. }
  8116. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  8117. return fromArrayLike(obj.data)
  8118. }
  8119. }
  8120. function checked (length) {
  8121. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  8122. // length is NaN (which is otherwise coerced to zero.)
  8123. if (length >= K_MAX_LENGTH) {
  8124. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  8125. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  8126. }
  8127. return length | 0
  8128. }
  8129. function SlowBuffer (length) {
  8130. if (+length != length) { // eslint-disable-line eqeqeq
  8131. length = 0
  8132. }
  8133. return Buffer.alloc(+length)
  8134. }
  8135. Buffer.isBuffer = function isBuffer (b) {
  8136. return b != null && b._isBuffer === true &&
  8137. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  8138. }
  8139. Buffer.compare = function compare (a, b) {
  8140. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  8141. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  8142. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  8143. throw new TypeError(
  8144. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  8145. )
  8146. }
  8147. if (a === b) return 0
  8148. var x = a.length
  8149. var y = b.length
  8150. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  8151. if (a[i] !== b[i]) {
  8152. x = a[i]
  8153. y = b[i]
  8154. break
  8155. }
  8156. }
  8157. if (x < y) return -1
  8158. if (y < x) return 1
  8159. return 0
  8160. }
  8161. Buffer.isEncoding = function isEncoding (encoding) {
  8162. switch (String(encoding).toLowerCase()) {
  8163. case 'hex':
  8164. case 'utf8':
  8165. case 'utf-8':
  8166. case 'ascii':
  8167. case 'latin1':
  8168. case 'binary':
  8169. case 'base64':
  8170. case 'ucs2':
  8171. case 'ucs-2':
  8172. case 'utf16le':
  8173. case 'utf-16le':
  8174. return true
  8175. default:
  8176. return false
  8177. }
  8178. }
  8179. Buffer.concat = function concat (list, length) {
  8180. if (!Array.isArray(list)) {
  8181. throw new TypeError('"list" argument must be an Array of Buffers')
  8182. }
  8183. if (list.length === 0) {
  8184. return Buffer.alloc(0)
  8185. }
  8186. var i
  8187. if (length === undefined) {
  8188. length = 0
  8189. for (i = 0; i < list.length; ++i) {
  8190. length += list[i].length
  8191. }
  8192. }
  8193. var buffer = Buffer.allocUnsafe(length)
  8194. var pos = 0
  8195. for (i = 0; i < list.length; ++i) {
  8196. var buf = list[i]
  8197. if (isInstance(buf, Uint8Array)) {
  8198. buf = Buffer.from(buf)
  8199. }
  8200. if (!Buffer.isBuffer(buf)) {
  8201. throw new TypeError('"list" argument must be an Array of Buffers')
  8202. }
  8203. buf.copy(buffer, pos)
  8204. pos += buf.length
  8205. }
  8206. return buffer
  8207. }
  8208. function byteLength (string, encoding) {
  8209. if (Buffer.isBuffer(string)) {
  8210. return string.length
  8211. }
  8212. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  8213. return string.byteLength
  8214. }
  8215. if (typeof string !== 'string') {
  8216. throw new TypeError(
  8217. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  8218. 'Received type ' + typeof string
  8219. )
  8220. }
  8221. var len = string.length
  8222. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  8223. if (!mustMatch && len === 0) return 0
  8224. // Use a for loop to avoid recursion
  8225. var loweredCase = false
  8226. for (;;) {
  8227. switch (encoding) {
  8228. case 'ascii':
  8229. case 'latin1':
  8230. case 'binary':
  8231. return len
  8232. case 'utf8':
  8233. case 'utf-8':
  8234. return utf8ToBytes(string).length
  8235. case 'ucs2':
  8236. case 'ucs-2':
  8237. case 'utf16le':
  8238. case 'utf-16le':
  8239. return len * 2
  8240. case 'hex':
  8241. return len >>> 1
  8242. case 'base64':
  8243. return base64ToBytes(string).length
  8244. default:
  8245. if (loweredCase) {
  8246. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  8247. }
  8248. encoding = ('' + encoding).toLowerCase()
  8249. loweredCase = true
  8250. }
  8251. }
  8252. }
  8253. Buffer.byteLength = byteLength
  8254. function slowToString (encoding, start, end) {
  8255. var loweredCase = false
  8256. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  8257. // property of a typed array.
  8258. // This behaves neither like String nor Uint8Array in that we set start/end
  8259. // to their upper/lower bounds if the value passed is out of range.
  8260. // undefined is handled specially as per ECMA-262 6th Edition,
  8261. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  8262. if (start === undefined || start < 0) {
  8263. start = 0
  8264. }
  8265. // Return early if start > this.length. Done here to prevent potential uint32
  8266. // coercion fail below.
  8267. if (start > this.length) {
  8268. return ''
  8269. }
  8270. if (end === undefined || end > this.length) {
  8271. end = this.length
  8272. }
  8273. if (end <= 0) {
  8274. return ''
  8275. }
  8276. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  8277. end >>>= 0
  8278. start >>>= 0
  8279. if (end <= start) {
  8280. return ''
  8281. }
  8282. if (!encoding) encoding = 'utf8'
  8283. while (true) {
  8284. switch (encoding) {
  8285. case 'hex':
  8286. return hexSlice(this, start, end)
  8287. case 'utf8':
  8288. case 'utf-8':
  8289. return utf8Slice(this, start, end)
  8290. case 'ascii':
  8291. return asciiSlice(this, start, end)
  8292. case 'latin1':
  8293. case 'binary':
  8294. return latin1Slice(this, start, end)
  8295. case 'base64':
  8296. return base64Slice(this, start, end)
  8297. case 'ucs2':
  8298. case 'ucs-2':
  8299. case 'utf16le':
  8300. case 'utf-16le':
  8301. return utf16leSlice(this, start, end)
  8302. default:
  8303. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8304. encoding = (encoding + '').toLowerCase()
  8305. loweredCase = true
  8306. }
  8307. }
  8308. }
  8309. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  8310. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  8311. // reliably in a browserify context because there could be multiple different
  8312. // copies of the 'buffer' package in use. This method works even for Buffer
  8313. // instances that were created from another copy of the `buffer` package.
  8314. // See: https://github.com/feross/buffer/issues/154
  8315. Buffer.prototype._isBuffer = true
  8316. function swap (b, n, m) {
  8317. var i = b[n]
  8318. b[n] = b[m]
  8319. b[m] = i
  8320. }
  8321. Buffer.prototype.swap16 = function swap16 () {
  8322. var len = this.length
  8323. if (len % 2 !== 0) {
  8324. throw new RangeError('Buffer size must be a multiple of 16-bits')
  8325. }
  8326. for (var i = 0; i < len; i += 2) {
  8327. swap(this, i, i + 1)
  8328. }
  8329. return this
  8330. }
  8331. Buffer.prototype.swap32 = function swap32 () {
  8332. var len = this.length
  8333. if (len % 4 !== 0) {
  8334. throw new RangeError('Buffer size must be a multiple of 32-bits')
  8335. }
  8336. for (var i = 0; i < len; i += 4) {
  8337. swap(this, i, i + 3)
  8338. swap(this, i + 1, i + 2)
  8339. }
  8340. return this
  8341. }
  8342. Buffer.prototype.swap64 = function swap64 () {
  8343. var len = this.length
  8344. if (len % 8 !== 0) {
  8345. throw new RangeError('Buffer size must be a multiple of 64-bits')
  8346. }
  8347. for (var i = 0; i < len; i += 8) {
  8348. swap(this, i, i + 7)
  8349. swap(this, i + 1, i + 6)
  8350. swap(this, i + 2, i + 5)
  8351. swap(this, i + 3, i + 4)
  8352. }
  8353. return this
  8354. }
  8355. Buffer.prototype.toString = function toString () {
  8356. var length = this.length
  8357. if (length === 0) return ''
  8358. if (arguments.length === 0) return utf8Slice(this, 0, length)
  8359. return slowToString.apply(this, arguments)
  8360. }
  8361. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  8362. Buffer.prototype.equals = function equals (b) {
  8363. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  8364. if (this === b) return true
  8365. return Buffer.compare(this, b) === 0
  8366. }
  8367. Buffer.prototype.inspect = function inspect () {
  8368. var str = ''
  8369. var max = exports.INSPECT_MAX_BYTES
  8370. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  8371. if (this.length > max) str += ' ... '
  8372. return '<Buffer ' + str + '>'
  8373. }
  8374. if (customInspectSymbol) {
  8375. Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
  8376. }
  8377. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  8378. if (isInstance(target, Uint8Array)) {
  8379. target = Buffer.from(target, target.offset, target.byteLength)
  8380. }
  8381. if (!Buffer.isBuffer(target)) {
  8382. throw new TypeError(
  8383. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  8384. 'Received type ' + (typeof target)
  8385. )
  8386. }
  8387. if (start === undefined) {
  8388. start = 0
  8389. }
  8390. if (end === undefined) {
  8391. end = target ? target.length : 0
  8392. }
  8393. if (thisStart === undefined) {
  8394. thisStart = 0
  8395. }
  8396. if (thisEnd === undefined) {
  8397. thisEnd = this.length
  8398. }
  8399. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  8400. throw new RangeError('out of range index')
  8401. }
  8402. if (thisStart >= thisEnd && start >= end) {
  8403. return 0
  8404. }
  8405. if (thisStart >= thisEnd) {
  8406. return -1
  8407. }
  8408. if (start >= end) {
  8409. return 1
  8410. }
  8411. start >>>= 0
  8412. end >>>= 0
  8413. thisStart >>>= 0
  8414. thisEnd >>>= 0
  8415. if (this === target) return 0
  8416. var x = thisEnd - thisStart
  8417. var y = end - start
  8418. var len = Math.min(x, y)
  8419. var thisCopy = this.slice(thisStart, thisEnd)
  8420. var targetCopy = target.slice(start, end)
  8421. for (var i = 0; i < len; ++i) {
  8422. if (thisCopy[i] !== targetCopy[i]) {
  8423. x = thisCopy[i]
  8424. y = targetCopy[i]
  8425. break
  8426. }
  8427. }
  8428. if (x < y) return -1
  8429. if (y < x) return 1
  8430. return 0
  8431. }
  8432. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  8433. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  8434. //
  8435. // Arguments:
  8436. // - buffer - a Buffer to search
  8437. // - val - a string, Buffer, or number
  8438. // - byteOffset - an index into `buffer`; will be clamped to an int32
  8439. // - encoding - an optional encoding, relevant is val is a string
  8440. // - dir - true for indexOf, false for lastIndexOf
  8441. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  8442. // Empty buffer means no match
  8443. if (buffer.length === 0) return -1
  8444. // Normalize byteOffset
  8445. if (typeof byteOffset === 'string') {
  8446. encoding = byteOffset
  8447. byteOffset = 0
  8448. } else if (byteOffset > 0x7fffffff) {
  8449. byteOffset = 0x7fffffff
  8450. } else if (byteOffset < -0x80000000) {
  8451. byteOffset = -0x80000000
  8452. }
  8453. byteOffset = +byteOffset // Coerce to Number.
  8454. if (numberIsNaN(byteOffset)) {
  8455. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  8456. byteOffset = dir ? 0 : (buffer.length - 1)
  8457. }
  8458. // Normalize byteOffset: negative offsets start from the end of the buffer
  8459. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  8460. if (byteOffset >= buffer.length) {
  8461. if (dir) return -1
  8462. else byteOffset = buffer.length - 1
  8463. } else if (byteOffset < 0) {
  8464. if (dir) byteOffset = 0
  8465. else return -1
  8466. }
  8467. // Normalize val
  8468. if (typeof val === 'string') {
  8469. val = Buffer.from(val, encoding)
  8470. }
  8471. // Finally, search either indexOf (if dir is true) or lastIndexOf
  8472. if (Buffer.isBuffer(val)) {
  8473. // Special case: looking for empty string/buffer always fails
  8474. if (val.length === 0) {
  8475. return -1
  8476. }
  8477. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  8478. } else if (typeof val === 'number') {
  8479. val = val & 0xFF // Search for a byte value [0-255]
  8480. if (typeof Uint8Array.prototype.indexOf === 'function') {
  8481. if (dir) {
  8482. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  8483. } else {
  8484. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  8485. }
  8486. }
  8487. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  8488. }
  8489. throw new TypeError('val must be string, number or Buffer')
  8490. }
  8491. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  8492. var indexSize = 1
  8493. var arrLength = arr.length
  8494. var valLength = val.length
  8495. if (encoding !== undefined) {
  8496. encoding = String(encoding).toLowerCase()
  8497. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  8498. encoding === 'utf16le' || encoding === 'utf-16le') {
  8499. if (arr.length < 2 || val.length < 2) {
  8500. return -1
  8501. }
  8502. indexSize = 2
  8503. arrLength /= 2
  8504. valLength /= 2
  8505. byteOffset /= 2
  8506. }
  8507. }
  8508. function read (buf, i) {
  8509. if (indexSize === 1) {
  8510. return buf[i]
  8511. } else {
  8512. return buf.readUInt16BE(i * indexSize)
  8513. }
  8514. }
  8515. var i
  8516. if (dir) {
  8517. var foundIndex = -1
  8518. for (i = byteOffset; i < arrLength; i++) {
  8519. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  8520. if (foundIndex === -1) foundIndex = i
  8521. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  8522. } else {
  8523. if (foundIndex !== -1) i -= i - foundIndex
  8524. foundIndex = -1
  8525. }
  8526. }
  8527. } else {
  8528. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  8529. for (i = byteOffset; i >= 0; i--) {
  8530. var found = true
  8531. for (var j = 0; j < valLength; j++) {
  8532. if (read(arr, i + j) !== read(val, j)) {
  8533. found = false
  8534. break
  8535. }
  8536. }
  8537. if (found) return i
  8538. }
  8539. }
  8540. return -1
  8541. }
  8542. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  8543. return this.indexOf(val, byteOffset, encoding) !== -1
  8544. }
  8545. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  8546. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  8547. }
  8548. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  8549. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  8550. }
  8551. function hexWrite (buf, string, offset, length) {
  8552. offset = Number(offset) || 0
  8553. var remaining = buf.length - offset
  8554. if (!length) {
  8555. length = remaining
  8556. } else {
  8557. length = Number(length)
  8558. if (length > remaining) {
  8559. length = remaining
  8560. }
  8561. }
  8562. var strLen = string.length
  8563. if (length > strLen / 2) {
  8564. length = strLen / 2
  8565. }
  8566. for (var i = 0; i < length; ++i) {
  8567. var parsed = parseInt(string.substr(i * 2, 2), 16)
  8568. if (numberIsNaN(parsed)) return i
  8569. buf[offset + i] = parsed
  8570. }
  8571. return i
  8572. }
  8573. function utf8Write (buf, string, offset, length) {
  8574. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  8575. }
  8576. function asciiWrite (buf, string, offset, length) {
  8577. return blitBuffer(asciiToBytes(string), buf, offset, length)
  8578. }
  8579. function latin1Write (buf, string, offset, length) {
  8580. return asciiWrite(buf, string, offset, length)
  8581. }
  8582. function base64Write (buf, string, offset, length) {
  8583. return blitBuffer(base64ToBytes(string), buf, offset, length)
  8584. }
  8585. function ucs2Write (buf, string, offset, length) {
  8586. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  8587. }
  8588. Buffer.prototype.write = function write (string, offset, length, encoding) {
  8589. // Buffer#write(string)
  8590. if (offset === undefined) {
  8591. encoding = 'utf8'
  8592. length = this.length
  8593. offset = 0
  8594. // Buffer#write(string, encoding)
  8595. } else if (length === undefined && typeof offset === 'string') {
  8596. encoding = offset
  8597. length = this.length
  8598. offset = 0
  8599. // Buffer#write(string, offset[, length][, encoding])
  8600. } else if (isFinite(offset)) {
  8601. offset = offset >>> 0
  8602. if (isFinite(length)) {
  8603. length = length >>> 0
  8604. if (encoding === undefined) encoding = 'utf8'
  8605. } else {
  8606. encoding = length
  8607. length = undefined
  8608. }
  8609. } else {
  8610. throw new Error(
  8611. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  8612. )
  8613. }
  8614. var remaining = this.length - offset
  8615. if (length === undefined || length > remaining) length = remaining
  8616. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  8617. throw new RangeError('Attempt to write outside buffer bounds')
  8618. }
  8619. if (!encoding) encoding = 'utf8'
  8620. var loweredCase = false
  8621. for (;;) {
  8622. switch (encoding) {
  8623. case 'hex':
  8624. return hexWrite(this, string, offset, length)
  8625. case 'utf8':
  8626. case 'utf-8':
  8627. return utf8Write(this, string, offset, length)
  8628. case 'ascii':
  8629. return asciiWrite(this, string, offset, length)
  8630. case 'latin1':
  8631. case 'binary':
  8632. return latin1Write(this, string, offset, length)
  8633. case 'base64':
  8634. // Warning: maxLength not taken into account in base64Write
  8635. return base64Write(this, string, offset, length)
  8636. case 'ucs2':
  8637. case 'ucs-2':
  8638. case 'utf16le':
  8639. case 'utf-16le':
  8640. return ucs2Write(this, string, offset, length)
  8641. default:
  8642. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8643. encoding = ('' + encoding).toLowerCase()
  8644. loweredCase = true
  8645. }
  8646. }
  8647. }
  8648. Buffer.prototype.toJSON = function toJSON () {
  8649. return {
  8650. type: 'Buffer',
  8651. data: Array.prototype.slice.call(this._arr || this, 0)
  8652. }
  8653. }
  8654. function base64Slice (buf, start, end) {
  8655. if (start === 0 && end === buf.length) {
  8656. return base64.fromByteArray(buf)
  8657. } else {
  8658. return base64.fromByteArray(buf.slice(start, end))
  8659. }
  8660. }
  8661. function utf8Slice (buf, start, end) {
  8662. end = Math.min(buf.length, end)
  8663. var res = []
  8664. var i = start
  8665. while (i < end) {
  8666. var firstByte = buf[i]
  8667. var codePoint = null
  8668. var bytesPerSequence = (firstByte > 0xEF) ? 4
  8669. : (firstByte > 0xDF) ? 3
  8670. : (firstByte > 0xBF) ? 2
  8671. : 1
  8672. if (i + bytesPerSequence <= end) {
  8673. var secondByte, thirdByte, fourthByte, tempCodePoint
  8674. switch (bytesPerSequence) {
  8675. case 1:
  8676. if (firstByte < 0x80) {
  8677. codePoint = firstByte
  8678. }
  8679. break
  8680. case 2:
  8681. secondByte = buf[i + 1]
  8682. if ((secondByte & 0xC0) === 0x80) {
  8683. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  8684. if (tempCodePoint > 0x7F) {
  8685. codePoint = tempCodePoint
  8686. }
  8687. }
  8688. break
  8689. case 3:
  8690. secondByte = buf[i + 1]
  8691. thirdByte = buf[i + 2]
  8692. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  8693. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  8694. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  8695. codePoint = tempCodePoint
  8696. }
  8697. }
  8698. break
  8699. case 4:
  8700. secondByte = buf[i + 1]
  8701. thirdByte = buf[i + 2]
  8702. fourthByte = buf[i + 3]
  8703. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  8704. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  8705. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  8706. codePoint = tempCodePoint
  8707. }
  8708. }
  8709. }
  8710. }
  8711. if (codePoint === null) {
  8712. // we did not generate a valid codePoint so insert a
  8713. // replacement char (U+FFFD) and advance only 1 byte
  8714. codePoint = 0xFFFD
  8715. bytesPerSequence = 1
  8716. } else if (codePoint > 0xFFFF) {
  8717. // encode to utf16 (surrogate pair dance)
  8718. codePoint -= 0x10000
  8719. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  8720. codePoint = 0xDC00 | codePoint & 0x3FF
  8721. }
  8722. res.push(codePoint)
  8723. i += bytesPerSequence
  8724. }
  8725. return decodeCodePointsArray(res)
  8726. }
  8727. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  8728. // the lowest limit is Chrome, with 0x10000 args.
  8729. // We go 1 magnitude less, for safety
  8730. var MAX_ARGUMENTS_LENGTH = 0x1000
  8731. function decodeCodePointsArray (codePoints) {
  8732. var len = codePoints.length
  8733. if (len <= MAX_ARGUMENTS_LENGTH) {
  8734. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  8735. }
  8736. // Decode in chunks to avoid "call stack size exceeded".
  8737. var res = ''
  8738. var i = 0
  8739. while (i < len) {
  8740. res += String.fromCharCode.apply(
  8741. String,
  8742. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  8743. )
  8744. }
  8745. return res
  8746. }
  8747. function asciiSlice (buf, start, end) {
  8748. var ret = ''
  8749. end = Math.min(buf.length, end)
  8750. for (var i = start; i < end; ++i) {
  8751. ret += String.fromCharCode(buf[i] & 0x7F)
  8752. }
  8753. return ret
  8754. }
  8755. function latin1Slice (buf, start, end) {
  8756. var ret = ''
  8757. end = Math.min(buf.length, end)
  8758. for (var i = start; i < end; ++i) {
  8759. ret += String.fromCharCode(buf[i])
  8760. }
  8761. return ret
  8762. }
  8763. function hexSlice (buf, start, end) {
  8764. var len = buf.length
  8765. if (!start || start < 0) start = 0
  8766. if (!end || end < 0 || end > len) end = len
  8767. var out = ''
  8768. for (var i = start; i < end; ++i) {
  8769. out += hexSliceLookupTable[buf[i]]
  8770. }
  8771. return out
  8772. }
  8773. function utf16leSlice (buf, start, end) {
  8774. var bytes = buf.slice(start, end)
  8775. var res = ''
  8776. for (var i = 0; i < bytes.length; i += 2) {
  8777. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  8778. }
  8779. return res
  8780. }
  8781. Buffer.prototype.slice = function slice (start, end) {
  8782. var len = this.length
  8783. start = ~~start
  8784. end = end === undefined ? len : ~~end
  8785. if (start < 0) {
  8786. start += len
  8787. if (start < 0) start = 0
  8788. } else if (start > len) {
  8789. start = len
  8790. }
  8791. if (end < 0) {
  8792. end += len
  8793. if (end < 0) end = 0
  8794. } else if (end > len) {
  8795. end = len
  8796. }
  8797. if (end < start) end = start
  8798. var newBuf = this.subarray(start, end)
  8799. // Return an augmented `Uint8Array` instance
  8800. Object.setPrototypeOf(newBuf, Buffer.prototype)
  8801. return newBuf
  8802. }
  8803. /*
  8804. * Need to make sure that buffer isn't trying to write out of bounds.
  8805. */
  8806. function checkOffset (offset, ext, length) {
  8807. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  8808. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  8809. }
  8810. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  8811. offset = offset >>> 0
  8812. byteLength = byteLength >>> 0
  8813. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8814. var val = this[offset]
  8815. var mul = 1
  8816. var i = 0
  8817. while (++i < byteLength && (mul *= 0x100)) {
  8818. val += this[offset + i] * mul
  8819. }
  8820. return val
  8821. }
  8822. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  8823. offset = offset >>> 0
  8824. byteLength = byteLength >>> 0
  8825. if (!noAssert) {
  8826. checkOffset(offset, byteLength, this.length)
  8827. }
  8828. var val = this[offset + --byteLength]
  8829. var mul = 1
  8830. while (byteLength > 0 && (mul *= 0x100)) {
  8831. val += this[offset + --byteLength] * mul
  8832. }
  8833. return val
  8834. }
  8835. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  8836. offset = offset >>> 0
  8837. if (!noAssert) checkOffset(offset, 1, this.length)
  8838. return this[offset]
  8839. }
  8840. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  8841. offset = offset >>> 0
  8842. if (!noAssert) checkOffset(offset, 2, this.length)
  8843. return this[offset] | (this[offset + 1] << 8)
  8844. }
  8845. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  8846. offset = offset >>> 0
  8847. if (!noAssert) checkOffset(offset, 2, this.length)
  8848. return (this[offset] << 8) | this[offset + 1]
  8849. }
  8850. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  8851. offset = offset >>> 0
  8852. if (!noAssert) checkOffset(offset, 4, this.length)
  8853. return ((this[offset]) |
  8854. (this[offset + 1] << 8) |
  8855. (this[offset + 2] << 16)) +
  8856. (this[offset + 3] * 0x1000000)
  8857. }
  8858. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  8859. offset = offset >>> 0
  8860. if (!noAssert) checkOffset(offset, 4, this.length)
  8861. return (this[offset] * 0x1000000) +
  8862. ((this[offset + 1] << 16) |
  8863. (this[offset + 2] << 8) |
  8864. this[offset + 3])
  8865. }
  8866. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  8867. offset = offset >>> 0
  8868. byteLength = byteLength >>> 0
  8869. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8870. var val = this[offset]
  8871. var mul = 1
  8872. var i = 0
  8873. while (++i < byteLength && (mul *= 0x100)) {
  8874. val += this[offset + i] * mul
  8875. }
  8876. mul *= 0x80
  8877. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8878. return val
  8879. }
  8880. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  8881. offset = offset >>> 0
  8882. byteLength = byteLength >>> 0
  8883. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8884. var i = byteLength
  8885. var mul = 1
  8886. var val = this[offset + --i]
  8887. while (i > 0 && (mul *= 0x100)) {
  8888. val += this[offset + --i] * mul
  8889. }
  8890. mul *= 0x80
  8891. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8892. return val
  8893. }
  8894. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  8895. offset = offset >>> 0
  8896. if (!noAssert) checkOffset(offset, 1, this.length)
  8897. if (!(this[offset] & 0x80)) return (this[offset])
  8898. return ((0xff - this[offset] + 1) * -1)
  8899. }
  8900. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  8901. offset = offset >>> 0
  8902. if (!noAssert) checkOffset(offset, 2, this.length)
  8903. var val = this[offset] | (this[offset + 1] << 8)
  8904. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8905. }
  8906. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  8907. offset = offset >>> 0
  8908. if (!noAssert) checkOffset(offset, 2, this.length)
  8909. var val = this[offset + 1] | (this[offset] << 8)
  8910. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8911. }
  8912. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  8913. offset = offset >>> 0
  8914. if (!noAssert) checkOffset(offset, 4, this.length)
  8915. return (this[offset]) |
  8916. (this[offset + 1] << 8) |
  8917. (this[offset + 2] << 16) |
  8918. (this[offset + 3] << 24)
  8919. }
  8920. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  8921. offset = offset >>> 0
  8922. if (!noAssert) checkOffset(offset, 4, this.length)
  8923. return (this[offset] << 24) |
  8924. (this[offset + 1] << 16) |
  8925. (this[offset + 2] << 8) |
  8926. (this[offset + 3])
  8927. }
  8928. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  8929. offset = offset >>> 0
  8930. if (!noAssert) checkOffset(offset, 4, this.length)
  8931. return ieee754.read(this, offset, true, 23, 4)
  8932. }
  8933. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  8934. offset = offset >>> 0
  8935. if (!noAssert) checkOffset(offset, 4, this.length)
  8936. return ieee754.read(this, offset, false, 23, 4)
  8937. }
  8938. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  8939. offset = offset >>> 0
  8940. if (!noAssert) checkOffset(offset, 8, this.length)
  8941. return ieee754.read(this, offset, true, 52, 8)
  8942. }
  8943. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  8944. offset = offset >>> 0
  8945. if (!noAssert) checkOffset(offset, 8, this.length)
  8946. return ieee754.read(this, offset, false, 52, 8)
  8947. }
  8948. function checkInt (buf, value, offset, ext, max, min) {
  8949. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  8950. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  8951. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  8952. }
  8953. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  8954. value = +value
  8955. offset = offset >>> 0
  8956. byteLength = byteLength >>> 0
  8957. if (!noAssert) {
  8958. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8959. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8960. }
  8961. var mul = 1
  8962. var i = 0
  8963. this[offset] = value & 0xFF
  8964. while (++i < byteLength && (mul *= 0x100)) {
  8965. this[offset + i] = (value / mul) & 0xFF
  8966. }
  8967. return offset + byteLength
  8968. }
  8969. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  8970. value = +value
  8971. offset = offset >>> 0
  8972. byteLength = byteLength >>> 0
  8973. if (!noAssert) {
  8974. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8975. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8976. }
  8977. var i = byteLength - 1
  8978. var mul = 1
  8979. this[offset + i] = value & 0xFF
  8980. while (--i >= 0 && (mul *= 0x100)) {
  8981. this[offset + i] = (value / mul) & 0xFF
  8982. }
  8983. return offset + byteLength
  8984. }
  8985. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  8986. value = +value
  8987. offset = offset >>> 0
  8988. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  8989. this[offset] = (value & 0xff)
  8990. return offset + 1
  8991. }
  8992. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  8993. value = +value
  8994. offset = offset >>> 0
  8995. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  8996. this[offset] = (value & 0xff)
  8997. this[offset + 1] = (value >>> 8)
  8998. return offset + 2
  8999. }
  9000. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  9001. value = +value
  9002. offset = offset >>> 0
  9003. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  9004. this[offset] = (value >>> 8)
  9005. this[offset + 1] = (value & 0xff)
  9006. return offset + 2
  9007. }
  9008. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  9009. value = +value
  9010. offset = offset >>> 0
  9011. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  9012. this[offset + 3] = (value >>> 24)
  9013. this[offset + 2] = (value >>> 16)
  9014. this[offset + 1] = (value >>> 8)
  9015. this[offset] = (value & 0xff)
  9016. return offset + 4
  9017. }
  9018. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  9019. value = +value
  9020. offset = offset >>> 0
  9021. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  9022. this[offset] = (value >>> 24)
  9023. this[offset + 1] = (value >>> 16)
  9024. this[offset + 2] = (value >>> 8)
  9025. this[offset + 3] = (value & 0xff)
  9026. return offset + 4
  9027. }
  9028. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  9029. value = +value
  9030. offset = offset >>> 0
  9031. if (!noAssert) {
  9032. var limit = Math.pow(2, (8 * byteLength) - 1)
  9033. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  9034. }
  9035. var i = 0
  9036. var mul = 1
  9037. var sub = 0
  9038. this[offset] = value & 0xFF
  9039. while (++i < byteLength && (mul *= 0x100)) {
  9040. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  9041. sub = 1
  9042. }
  9043. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  9044. }
  9045. return offset + byteLength
  9046. }
  9047. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  9048. value = +value
  9049. offset = offset >>> 0
  9050. if (!noAssert) {
  9051. var limit = Math.pow(2, (8 * byteLength) - 1)
  9052. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  9053. }
  9054. var i = byteLength - 1
  9055. var mul = 1
  9056. var sub = 0
  9057. this[offset + i] = value & 0xFF
  9058. while (--i >= 0 && (mul *= 0x100)) {
  9059. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  9060. sub = 1
  9061. }
  9062. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  9063. }
  9064. return offset + byteLength
  9065. }
  9066. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  9067. value = +value
  9068. offset = offset >>> 0
  9069. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  9070. if (value < 0) value = 0xff + value + 1
  9071. this[offset] = (value & 0xff)
  9072. return offset + 1
  9073. }
  9074. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  9075. value = +value
  9076. offset = offset >>> 0
  9077. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  9078. this[offset] = (value & 0xff)
  9079. this[offset + 1] = (value >>> 8)
  9080. return offset + 2
  9081. }
  9082. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  9083. value = +value
  9084. offset = offset >>> 0
  9085. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  9086. this[offset] = (value >>> 8)
  9087. this[offset + 1] = (value & 0xff)
  9088. return offset + 2
  9089. }
  9090. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  9091. value = +value
  9092. offset = offset >>> 0
  9093. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  9094. this[offset] = (value & 0xff)
  9095. this[offset + 1] = (value >>> 8)
  9096. this[offset + 2] = (value >>> 16)
  9097. this[offset + 3] = (value >>> 24)
  9098. return offset + 4
  9099. }
  9100. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  9101. value = +value
  9102. offset = offset >>> 0
  9103. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  9104. if (value < 0) value = 0xffffffff + value + 1
  9105. this[offset] = (value >>> 24)
  9106. this[offset + 1] = (value >>> 16)
  9107. this[offset + 2] = (value >>> 8)
  9108. this[offset + 3] = (value & 0xff)
  9109. return offset + 4
  9110. }
  9111. function checkIEEE754 (buf, value, offset, ext, max, min) {
  9112. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  9113. if (offset < 0) throw new RangeError('Index out of range')
  9114. }
  9115. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  9116. value = +value
  9117. offset = offset >>> 0
  9118. if (!noAssert) {
  9119. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  9120. }
  9121. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  9122. return offset + 4
  9123. }
  9124. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  9125. return writeFloat(this, value, offset, true, noAssert)
  9126. }
  9127. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  9128. return writeFloat(this, value, offset, false, noAssert)
  9129. }
  9130. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  9131. value = +value
  9132. offset = offset >>> 0
  9133. if (!noAssert) {
  9134. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  9135. }
  9136. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  9137. return offset + 8
  9138. }
  9139. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  9140. return writeDouble(this, value, offset, true, noAssert)
  9141. }
  9142. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  9143. return writeDouble(this, value, offset, false, noAssert)
  9144. }
  9145. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  9146. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  9147. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  9148. if (!start) start = 0
  9149. if (!end && end !== 0) end = this.length
  9150. if (targetStart >= target.length) targetStart = target.length
  9151. if (!targetStart) targetStart = 0
  9152. if (end > 0 && end < start) end = start
  9153. // Copy 0 bytes; we're done
  9154. if (end === start) return 0
  9155. if (target.length === 0 || this.length === 0) return 0
  9156. // Fatal error conditions
  9157. if (targetStart < 0) {
  9158. throw new RangeError('targetStart out of bounds')
  9159. }
  9160. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  9161. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  9162. // Are we oob?
  9163. if (end > this.length) end = this.length
  9164. if (target.length - targetStart < end - start) {
  9165. end = target.length - targetStart + start
  9166. }
  9167. var len = end - start
  9168. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  9169. // Use built-in when available, missing from IE11
  9170. this.copyWithin(targetStart, start, end)
  9171. } else if (this === target && start < targetStart && targetStart < end) {
  9172. // descending copy from end
  9173. for (var i = len - 1; i >= 0; --i) {
  9174. target[i + targetStart] = this[i + start]
  9175. }
  9176. } else {
  9177. Uint8Array.prototype.set.call(
  9178. target,
  9179. this.subarray(start, end),
  9180. targetStart
  9181. )
  9182. }
  9183. return len
  9184. }
  9185. // Usage:
  9186. // buffer.fill(number[, offset[, end]])
  9187. // buffer.fill(buffer[, offset[, end]])
  9188. // buffer.fill(string[, offset[, end]][, encoding])
  9189. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  9190. // Handle string cases:
  9191. if (typeof val === 'string') {
  9192. if (typeof start === 'string') {
  9193. encoding = start
  9194. start = 0
  9195. end = this.length
  9196. } else if (typeof end === 'string') {
  9197. encoding = end
  9198. end = this.length
  9199. }
  9200. if (encoding !== undefined && typeof encoding !== 'string') {
  9201. throw new TypeError('encoding must be a string')
  9202. }
  9203. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  9204. throw new TypeError('Unknown encoding: ' + encoding)
  9205. }
  9206. if (val.length === 1) {
  9207. var code = val.charCodeAt(0)
  9208. if ((encoding === 'utf8' && code < 128) ||
  9209. encoding === 'latin1') {
  9210. // Fast path: If `val` fits into a single byte, use that numeric value.
  9211. val = code
  9212. }
  9213. }
  9214. } else if (typeof val === 'number') {
  9215. val = val & 255
  9216. } else if (typeof val === 'boolean') {
  9217. val = Number(val)
  9218. }
  9219. // Invalid ranges are not set to a default, so can range check early.
  9220. if (start < 0 || this.length < start || this.length < end) {
  9221. throw new RangeError('Out of range index')
  9222. }
  9223. if (end <= start) {
  9224. return this
  9225. }
  9226. start = start >>> 0
  9227. end = end === undefined ? this.length : end >>> 0
  9228. if (!val) val = 0
  9229. var i
  9230. if (typeof val === 'number') {
  9231. for (i = start; i < end; ++i) {
  9232. this[i] = val
  9233. }
  9234. } else {
  9235. var bytes = Buffer.isBuffer(val)
  9236. ? val
  9237. : Buffer.from(val, encoding)
  9238. var len = bytes.length
  9239. if (len === 0) {
  9240. throw new TypeError('The value "' + val +
  9241. '" is invalid for argument "value"')
  9242. }
  9243. for (i = 0; i < end - start; ++i) {
  9244. this[i + start] = bytes[i % len]
  9245. }
  9246. }
  9247. return this
  9248. }
  9249. // HELPER FUNCTIONS
  9250. // ================
  9251. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  9252. function base64clean (str) {
  9253. // Node takes equal signs as end of the Base64 encoding
  9254. str = str.split('=')[0]
  9255. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  9256. str = str.trim().replace(INVALID_BASE64_RE, '')
  9257. // Node converts strings with length < 2 to ''
  9258. if (str.length < 2) return ''
  9259. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  9260. while (str.length % 4 !== 0) {
  9261. str = str + '='
  9262. }
  9263. return str
  9264. }
  9265. function utf8ToBytes (string, units) {
  9266. units = units || Infinity
  9267. var codePoint
  9268. var length = string.length
  9269. var leadSurrogate = null
  9270. var bytes = []
  9271. for (var i = 0; i < length; ++i) {
  9272. codePoint = string.charCodeAt(i)
  9273. // is surrogate component
  9274. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  9275. // last char was a lead
  9276. if (!leadSurrogate) {
  9277. // no lead yet
  9278. if (codePoint > 0xDBFF) {
  9279. // unexpected trail
  9280. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9281. continue
  9282. } else if (i + 1 === length) {
  9283. // unpaired lead
  9284. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9285. continue
  9286. }
  9287. // valid lead
  9288. leadSurrogate = codePoint
  9289. continue
  9290. }
  9291. // 2 leads in a row
  9292. if (codePoint < 0xDC00) {
  9293. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9294. leadSurrogate = codePoint
  9295. continue
  9296. }
  9297. // valid surrogate pair
  9298. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  9299. } else if (leadSurrogate) {
  9300. // valid bmp char, but last char was a lead
  9301. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9302. }
  9303. leadSurrogate = null
  9304. // encode utf8
  9305. if (codePoint < 0x80) {
  9306. if ((units -= 1) < 0) break
  9307. bytes.push(codePoint)
  9308. } else if (codePoint < 0x800) {
  9309. if ((units -= 2) < 0) break
  9310. bytes.push(
  9311. codePoint >> 0x6 | 0xC0,
  9312. codePoint & 0x3F | 0x80
  9313. )
  9314. } else if (codePoint < 0x10000) {
  9315. if ((units -= 3) < 0) break
  9316. bytes.push(
  9317. codePoint >> 0xC | 0xE0,
  9318. codePoint >> 0x6 & 0x3F | 0x80,
  9319. codePoint & 0x3F | 0x80
  9320. )
  9321. } else if (codePoint < 0x110000) {
  9322. if ((units -= 4) < 0) break
  9323. bytes.push(
  9324. codePoint >> 0x12 | 0xF0,
  9325. codePoint >> 0xC & 0x3F | 0x80,
  9326. codePoint >> 0x6 & 0x3F | 0x80,
  9327. codePoint & 0x3F | 0x80
  9328. )
  9329. } else {
  9330. throw new Error('Invalid code point')
  9331. }
  9332. }
  9333. return bytes
  9334. }
  9335. function asciiToBytes (str) {
  9336. var byteArray = []
  9337. for (var i = 0; i < str.length; ++i) {
  9338. // Node's code seems to be doing this and not & 0x7F..
  9339. byteArray.push(str.charCodeAt(i) & 0xFF)
  9340. }
  9341. return byteArray
  9342. }
  9343. function utf16leToBytes (str, units) {
  9344. var c, hi, lo
  9345. var byteArray = []
  9346. for (var i = 0; i < str.length; ++i) {
  9347. if ((units -= 2) < 0) break
  9348. c = str.charCodeAt(i)
  9349. hi = c >> 8
  9350. lo = c % 256
  9351. byteArray.push(lo)
  9352. byteArray.push(hi)
  9353. }
  9354. return byteArray
  9355. }
  9356. function base64ToBytes (str) {
  9357. return base64.toByteArray(base64clean(str))
  9358. }
  9359. function blitBuffer (src, dst, offset, length) {
  9360. for (var i = 0; i < length; ++i) {
  9361. if ((i + offset >= dst.length) || (i >= src.length)) break
  9362. dst[i + offset] = src[i]
  9363. }
  9364. return i
  9365. }
  9366. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  9367. // the `instanceof` check but they should be treated as of that type.
  9368. // See: https://github.com/feross/buffer/issues/166
  9369. function isInstance (obj, type) {
  9370. return obj instanceof type ||
  9371. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  9372. obj.constructor.name === type.name)
  9373. }
  9374. function numberIsNaN (obj) {
  9375. // For IE11 support
  9376. return obj !== obj // eslint-disable-line no-self-compare
  9377. }
  9378. // Create lookup table for `toString('hex')`
  9379. // See: https://github.com/feross/buffer/issues/219
  9380. var hexSliceLookupTable = (function () {
  9381. var alphabet = '0123456789abcdef'
  9382. var table = new Array(256)
  9383. for (var i = 0; i < 16; ++i) {
  9384. var i16 = i * 16
  9385. for (var j = 0; j < 16; ++j) {
  9386. table[i16 + j] = alphabet[i] + alphabet[j]
  9387. }
  9388. }
  9389. return table
  9390. })()
  9391. }).call(this,require("buffer").Buffer)
  9392. },{"base64-js":28,"buffer":47,"ieee754":253}],48:[function(require,module,exports){
  9393. var Buffer = require('buffer').Buffer; // for use with browserify
  9394. module.exports = function (a, b) {
  9395. if (!Buffer.isBuffer(a)) return undefined;
  9396. if (!Buffer.isBuffer(b)) return undefined;
  9397. if (typeof a.equals === 'function') return a.equals(b);
  9398. if (a.length !== b.length) return false;
  9399. for (var i = 0; i < a.length; i++) {
  9400. if (a[i] !== b[i]) return false;
  9401. }
  9402. return true;
  9403. };
  9404. },{"buffer":47}],49:[function(require,module,exports){
  9405. module.exports = {
  9406. "100": "Continue",
  9407. "101": "Switching Protocols",
  9408. "102": "Processing",
  9409. "200": "OK",
  9410. "201": "Created",
  9411. "202": "Accepted",
  9412. "203": "Non-Authoritative Information",
  9413. "204": "No Content",
  9414. "205": "Reset Content",
  9415. "206": "Partial Content",
  9416. "207": "Multi-Status",
  9417. "208": "Already Reported",
  9418. "226": "IM Used",
  9419. "300": "Multiple Choices",
  9420. "301": "Moved Permanently",
  9421. "302": "Found",
  9422. "303": "See Other",
  9423. "304": "Not Modified",
  9424. "305": "Use Proxy",
  9425. "307": "Temporary Redirect",
  9426. "308": "Permanent Redirect",
  9427. "400": "Bad Request",
  9428. "401": "Unauthorized",
  9429. "402": "Payment Required",
  9430. "403": "Forbidden",
  9431. "404": "Not Found",
  9432. "405": "Method Not Allowed",
  9433. "406": "Not Acceptable",
  9434. "407": "Proxy Authentication Required",
  9435. "408": "Request Timeout",
  9436. "409": "Conflict",
  9437. "410": "Gone",
  9438. "411": "Length Required",
  9439. "412": "Precondition Failed",
  9440. "413": "Payload Too Large",
  9441. "414": "URI Too Long",
  9442. "415": "Unsupported Media Type",
  9443. "416": "Range Not Satisfiable",
  9444. "417": "Expectation Failed",
  9445. "418": "I'm a teapot",
  9446. "421": "Misdirected Request",
  9447. "422": "Unprocessable Entity",
  9448. "423": "Locked",
  9449. "424": "Failed Dependency",
  9450. "425": "Unordered Collection",
  9451. "426": "Upgrade Required",
  9452. "428": "Precondition Required",
  9453. "429": "Too Many Requests",
  9454. "431": "Request Header Fields Too Large",
  9455. "451": "Unavailable For Legal Reasons",
  9456. "500": "Internal Server Error",
  9457. "501": "Not Implemented",
  9458. "502": "Bad Gateway",
  9459. "503": "Service Unavailable",
  9460. "504": "Gateway Timeout",
  9461. "505": "HTTP Version Not Supported",
  9462. "506": "Variant Also Negotiates",
  9463. "507": "Insufficient Storage",
  9464. "508": "Loop Detected",
  9465. "509": "Bandwidth Limit Exceeded",
  9466. "510": "Not Extended",
  9467. "511": "Network Authentication Required"
  9468. }
  9469. },{}],50:[function(require,module,exports){
  9470. module.exports = function (it) {
  9471. if (typeof it != 'function') {
  9472. throw TypeError(String(it) + ' is not a function');
  9473. } return it;
  9474. };
  9475. },{}],51:[function(require,module,exports){
  9476. var isObject = require('../internals/is-object');
  9477. module.exports = function (it) {
  9478. if (!isObject(it) && it !== null) {
  9479. throw TypeError("Can't set " + String(it) + ' as a prototype');
  9480. } return it;
  9481. };
  9482. },{"../internals/is-object":105}],52:[function(require,module,exports){
  9483. var wellKnownSymbol = require('../internals/well-known-symbol');
  9484. var create = require('../internals/object-create');
  9485. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  9486. var UNSCOPABLES = wellKnownSymbol('unscopables');
  9487. var ArrayPrototype = Array.prototype;
  9488. // Array.prototype[@@unscopables]
  9489. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  9490. if (ArrayPrototype[UNSCOPABLES] == undefined) {
  9491. createNonEnumerableProperty(ArrayPrototype, UNSCOPABLES, create(null));
  9492. }
  9493. // add a key to Array.prototype[@@unscopables]
  9494. module.exports = function (key) {
  9495. ArrayPrototype[UNSCOPABLES][key] = true;
  9496. };
  9497. },{"../internals/create-non-enumerable-property":76,"../internals/object-create":118,"../internals/well-known-symbol":169}],53:[function(require,module,exports){
  9498. 'use strict';
  9499. var charAt = require('../internals/string-multibyte').charAt;
  9500. // `AdvanceStringIndex` abstract operation
  9501. // https://tc39.github.io/ecma262/#sec-advancestringindex
  9502. module.exports = function (S, index, unicode) {
  9503. return index + (unicode ? charAt(S, index).length : 1);
  9504. };
  9505. },{"../internals/string-multibyte":151}],54:[function(require,module,exports){
  9506. module.exports = function (it, Constructor, name) {
  9507. if (!(it instanceof Constructor)) {
  9508. throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
  9509. } return it;
  9510. };
  9511. },{}],55:[function(require,module,exports){
  9512. var isObject = require('../internals/is-object');
  9513. module.exports = function (it) {
  9514. if (!isObject(it)) {
  9515. throw TypeError(String(it) + ' is not an object');
  9516. } return it;
  9517. };
  9518. },{"../internals/is-object":105}],56:[function(require,module,exports){
  9519. 'use strict';
  9520. var DESCRIPTORS = require('../internals/descriptors');
  9521. var global = require('../internals/global');
  9522. var isObject = require('../internals/is-object');
  9523. var has = require('../internals/has');
  9524. var classof = require('../internals/classof');
  9525. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  9526. var redefine = require('../internals/redefine');
  9527. var defineProperty = require('../internals/object-define-property').f;
  9528. var getPrototypeOf = require('../internals/object-get-prototype-of');
  9529. var setPrototypeOf = require('../internals/object-set-prototype-of');
  9530. var wellKnownSymbol = require('../internals/well-known-symbol');
  9531. var uid = require('../internals/uid');
  9532. var DataView = global.DataView;
  9533. var DataViewPrototype = DataView && DataView.prototype;
  9534. var Int8Array = global.Int8Array;
  9535. var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
  9536. var Uint8ClampedArray = global.Uint8ClampedArray;
  9537. var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
  9538. var TypedArray = Int8Array && getPrototypeOf(Int8Array);
  9539. var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
  9540. var ObjectPrototype = Object.prototype;
  9541. var isPrototypeOf = ObjectPrototype.isPrototypeOf;
  9542. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  9543. var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
  9544. var NATIVE_ARRAY_BUFFER = !!(global.ArrayBuffer && DataView);
  9545. // Fixing native typed arrays in Opera Presto crashes the browser, see #595
  9546. var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
  9547. var TYPED_ARRAY_TAG_REQIRED = false;
  9548. var NAME;
  9549. var TypedArrayConstructorsList = {
  9550. Int8Array: 1,
  9551. Uint8Array: 1,
  9552. Uint8ClampedArray: 1,
  9553. Int16Array: 2,
  9554. Uint16Array: 2,
  9555. Int32Array: 4,
  9556. Uint32Array: 4,
  9557. Float32Array: 4,
  9558. Float64Array: 8
  9559. };
  9560. var isView = function isView(it) {
  9561. var klass = classof(it);
  9562. return klass === 'DataView' || has(TypedArrayConstructorsList, klass);
  9563. };
  9564. var isTypedArray = function (it) {
  9565. return isObject(it) && has(TypedArrayConstructorsList, classof(it));
  9566. };
  9567. var aTypedArray = function (it) {
  9568. if (isTypedArray(it)) return it;
  9569. throw TypeError('Target is not a typed array');
  9570. };
  9571. var aTypedArrayConstructor = function (C) {
  9572. if (setPrototypeOf) {
  9573. if (isPrototypeOf.call(TypedArray, C)) return C;
  9574. } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {
  9575. var TypedArrayConstructor = global[ARRAY];
  9576. if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {
  9577. return C;
  9578. }
  9579. } throw TypeError('Target is not a typed array constructor');
  9580. };
  9581. var exportProto = function (KEY, property, forced) {
  9582. if (!DESCRIPTORS) return;
  9583. if (forced) for (var ARRAY in TypedArrayConstructorsList) {
  9584. var TypedArrayConstructor = global[ARRAY];
  9585. if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {
  9586. delete TypedArrayConstructor.prototype[KEY];
  9587. }
  9588. }
  9589. if (!TypedArrayPrototype[KEY] || forced) {
  9590. redefine(TypedArrayPrototype, KEY, forced ? property
  9591. : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);
  9592. }
  9593. };
  9594. var exportStatic = function (KEY, property, forced) {
  9595. var ARRAY, TypedArrayConstructor;
  9596. if (!DESCRIPTORS) return;
  9597. if (setPrototypeOf) {
  9598. if (forced) for (ARRAY in TypedArrayConstructorsList) {
  9599. TypedArrayConstructor = global[ARRAY];
  9600. if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {
  9601. delete TypedArrayConstructor[KEY];
  9602. }
  9603. }
  9604. if (!TypedArray[KEY] || forced) {
  9605. // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
  9606. try {
  9607. return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);
  9608. } catch (error) { /* empty */ }
  9609. } else return;
  9610. }
  9611. for (ARRAY in TypedArrayConstructorsList) {
  9612. TypedArrayConstructor = global[ARRAY];
  9613. if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
  9614. redefine(TypedArrayConstructor, KEY, property);
  9615. }
  9616. }
  9617. };
  9618. for (NAME in TypedArrayConstructorsList) {
  9619. if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;
  9620. }
  9621. // WebKit bug - typed arrays constructors prototype is Object.prototype
  9622. if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {
  9623. // eslint-disable-next-line no-shadow
  9624. TypedArray = function TypedArray() {
  9625. throw TypeError('Incorrect invocation');
  9626. };
  9627. if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
  9628. if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
  9629. }
  9630. }
  9631. if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
  9632. TypedArrayPrototype = TypedArray.prototype;
  9633. if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
  9634. if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
  9635. }
  9636. }
  9637. // WebKit bug - one more object in Uint8ClampedArray prototype chain
  9638. if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
  9639. setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
  9640. }
  9641. if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {
  9642. TYPED_ARRAY_TAG_REQIRED = true;
  9643. defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
  9644. return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
  9645. } });
  9646. for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
  9647. createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
  9648. }
  9649. }
  9650. // WebKit bug - the same parent prototype for typed arrays and data view
  9651. if (NATIVE_ARRAY_BUFFER && setPrototypeOf && getPrototypeOf(DataViewPrototype) !== ObjectPrototype) {
  9652. setPrototypeOf(DataViewPrototype, ObjectPrototype);
  9653. }
  9654. module.exports = {
  9655. NATIVE_ARRAY_BUFFER: NATIVE_ARRAY_BUFFER,
  9656. NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
  9657. TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
  9658. aTypedArray: aTypedArray,
  9659. aTypedArrayConstructor: aTypedArrayConstructor,
  9660. exportProto: exportProto,
  9661. exportStatic: exportStatic,
  9662. isView: isView,
  9663. isTypedArray: isTypedArray,
  9664. TypedArray: TypedArray,
  9665. TypedArrayPrototype: TypedArrayPrototype
  9666. };
  9667. },{"../internals/classof":71,"../internals/create-non-enumerable-property":76,"../internals/descriptors":81,"../internals/global":92,"../internals/has":93,"../internals/is-object":105,"../internals/object-define-property":120,"../internals/object-get-prototype-of":125,"../internals/object-set-prototype-of":129,"../internals/redefine":138,"../internals/uid":166,"../internals/well-known-symbol":169}],57:[function(require,module,exports){
  9668. 'use strict';
  9669. var global = require('../internals/global');
  9670. var DESCRIPTORS = require('../internals/descriptors');
  9671. var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER;
  9672. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  9673. var redefineAll = require('../internals/redefine-all');
  9674. var fails = require('../internals/fails');
  9675. var anInstance = require('../internals/an-instance');
  9676. var toInteger = require('../internals/to-integer');
  9677. var toLength = require('../internals/to-length');
  9678. var toIndex = require('../internals/to-index');
  9679. var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
  9680. var defineProperty = require('../internals/object-define-property').f;
  9681. var arrayFill = require('../internals/array-fill');
  9682. var setToStringTag = require('../internals/set-to-string-tag');
  9683. var InternalStateModule = require('../internals/internal-state');
  9684. var getInternalState = InternalStateModule.get;
  9685. var setInternalState = InternalStateModule.set;
  9686. var ARRAY_BUFFER = 'ArrayBuffer';
  9687. var DATA_VIEW = 'DataView';
  9688. var PROTOTYPE = 'prototype';
  9689. var WRONG_LENGTH = 'Wrong length';
  9690. var WRONG_INDEX = 'Wrong index';
  9691. var NativeArrayBuffer = global[ARRAY_BUFFER];
  9692. var $ArrayBuffer = NativeArrayBuffer;
  9693. var $DataView = global[DATA_VIEW];
  9694. var Math = global.Math;
  9695. var RangeError = global.RangeError;
  9696. // eslint-disable-next-line no-shadow-restricted-names
  9697. var Infinity = 1 / 0;
  9698. var abs = Math.abs;
  9699. var pow = Math.pow;
  9700. var floor = Math.floor;
  9701. var log = Math.log;
  9702. var LN2 = Math.LN2;
  9703. // IEEE754 conversions based on https://github.com/feross/ieee754
  9704. var packIEEE754 = function (number, mantissaLength, bytes) {
  9705. var buffer = new Array(bytes);
  9706. var exponentLength = bytes * 8 - mantissaLength - 1;
  9707. var eMax = (1 << exponentLength) - 1;
  9708. var eBias = eMax >> 1;
  9709. var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;
  9710. var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;
  9711. var index = 0;
  9712. var exponent, mantissa, c;
  9713. number = abs(number);
  9714. // eslint-disable-next-line no-self-compare
  9715. if (number != number || number === Infinity) {
  9716. // eslint-disable-next-line no-self-compare
  9717. mantissa = number != number ? 1 : 0;
  9718. exponent = eMax;
  9719. } else {
  9720. exponent = floor(log(number) / LN2);
  9721. if (number * (c = pow(2, -exponent)) < 1) {
  9722. exponent--;
  9723. c *= 2;
  9724. }
  9725. if (exponent + eBias >= 1) {
  9726. number += rt / c;
  9727. } else {
  9728. number += rt * pow(2, 1 - eBias);
  9729. }
  9730. if (number * c >= 2) {
  9731. exponent++;
  9732. c /= 2;
  9733. }
  9734. if (exponent + eBias >= eMax) {
  9735. mantissa = 0;
  9736. exponent = eMax;
  9737. } else if (exponent + eBias >= 1) {
  9738. mantissa = (number * c - 1) * pow(2, mantissaLength);
  9739. exponent = exponent + eBias;
  9740. } else {
  9741. mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);
  9742. exponent = 0;
  9743. }
  9744. }
  9745. for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8);
  9746. exponent = exponent << mantissaLength | mantissa;
  9747. exponentLength += mantissaLength;
  9748. for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8);
  9749. buffer[--index] |= sign * 128;
  9750. return buffer;
  9751. };
  9752. var unpackIEEE754 = function (buffer, mantissaLength) {
  9753. var bytes = buffer.length;
  9754. var exponentLength = bytes * 8 - mantissaLength - 1;
  9755. var eMax = (1 << exponentLength) - 1;
  9756. var eBias = eMax >> 1;
  9757. var nBits = exponentLength - 7;
  9758. var index = bytes - 1;
  9759. var sign = buffer[index--];
  9760. var exponent = sign & 127;
  9761. var mantissa;
  9762. sign >>= 7;
  9763. for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8);
  9764. mantissa = exponent & (1 << -nBits) - 1;
  9765. exponent >>= -nBits;
  9766. nBits += mantissaLength;
  9767. for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8);
  9768. if (exponent === 0) {
  9769. exponent = 1 - eBias;
  9770. } else if (exponent === eMax) {
  9771. return mantissa ? NaN : sign ? -Infinity : Infinity;
  9772. } else {
  9773. mantissa = mantissa + pow(2, mantissaLength);
  9774. exponent = exponent - eBias;
  9775. } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);
  9776. };
  9777. var unpackInt32 = function (buffer) {
  9778. return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  9779. };
  9780. var packInt8 = function (number) {
  9781. return [number & 0xFF];
  9782. };
  9783. var packInt16 = function (number) {
  9784. return [number & 0xFF, number >> 8 & 0xFF];
  9785. };
  9786. var packInt32 = function (number) {
  9787. return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];
  9788. };
  9789. var packFloat32 = function (number) {
  9790. return packIEEE754(number, 23, 4);
  9791. };
  9792. var packFloat64 = function (number) {
  9793. return packIEEE754(number, 52, 8);
  9794. };
  9795. var addGetter = function (Constructor, key) {
  9796. defineProperty(Constructor[PROTOTYPE], key, { get: function () { return getInternalState(this)[key]; } });
  9797. };
  9798. var get = function (view, count, index, isLittleEndian) {
  9799. var numIndex = +index;
  9800. var intIndex = toIndex(numIndex);
  9801. var store = getInternalState(view);
  9802. if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
  9803. var bytes = getInternalState(store.buffer).bytes;
  9804. var start = intIndex + store.byteOffset;
  9805. var pack = bytes.slice(start, start + count);
  9806. return isLittleEndian ? pack : pack.reverse();
  9807. };
  9808. var set = function (view, count, index, conversion, value, isLittleEndian) {
  9809. var numIndex = +index;
  9810. var intIndex = toIndex(numIndex);
  9811. var store = getInternalState(view);
  9812. if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
  9813. var bytes = getInternalState(store.buffer).bytes;
  9814. var start = intIndex + store.byteOffset;
  9815. var pack = conversion(+value);
  9816. for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1];
  9817. };
  9818. if (!NATIVE_ARRAY_BUFFER) {
  9819. $ArrayBuffer = function ArrayBuffer(length) {
  9820. anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
  9821. var byteLength = toIndex(length);
  9822. setInternalState(this, {
  9823. bytes: arrayFill.call(new Array(byteLength), 0),
  9824. byteLength: byteLength
  9825. });
  9826. if (!DESCRIPTORS) this.byteLength = byteLength;
  9827. };
  9828. $DataView = function DataView(buffer, byteOffset, byteLength) {
  9829. anInstance(this, $DataView, DATA_VIEW);
  9830. anInstance(buffer, $ArrayBuffer, DATA_VIEW);
  9831. var bufferLength = getInternalState(buffer).byteLength;
  9832. var offset = toInteger(byteOffset);
  9833. if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset');
  9834. byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
  9835. if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
  9836. setInternalState(this, {
  9837. buffer: buffer,
  9838. byteLength: byteLength,
  9839. byteOffset: offset
  9840. });
  9841. if (!DESCRIPTORS) {
  9842. this.buffer = buffer;
  9843. this.byteLength = byteLength;
  9844. this.byteOffset = offset;
  9845. }
  9846. };
  9847. if (DESCRIPTORS) {
  9848. addGetter($ArrayBuffer, 'byteLength');
  9849. addGetter($DataView, 'buffer');
  9850. addGetter($DataView, 'byteLength');
  9851. addGetter($DataView, 'byteOffset');
  9852. }
  9853. redefineAll($DataView[PROTOTYPE], {
  9854. getInt8: function getInt8(byteOffset) {
  9855. return get(this, 1, byteOffset)[0] << 24 >> 24;
  9856. },
  9857. getUint8: function getUint8(byteOffset) {
  9858. return get(this, 1, byteOffset)[0];
  9859. },
  9860. getInt16: function getInt16(byteOffset /* , littleEndian */) {
  9861. var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
  9862. return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
  9863. },
  9864. getUint16: function getUint16(byteOffset /* , littleEndian */) {
  9865. var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
  9866. return bytes[1] << 8 | bytes[0];
  9867. },
  9868. getInt32: function getInt32(byteOffset /* , littleEndian */) {
  9869. return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined));
  9870. },
  9871. getUint32: function getUint32(byteOffset /* , littleEndian */) {
  9872. return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0;
  9873. },
  9874. getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
  9875. return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23);
  9876. },
  9877. getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
  9878. return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52);
  9879. },
  9880. setInt8: function setInt8(byteOffset, value) {
  9881. set(this, 1, byteOffset, packInt8, value);
  9882. },
  9883. setUint8: function setUint8(byteOffset, value) {
  9884. set(this, 1, byteOffset, packInt8, value);
  9885. },
  9886. setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
  9887. set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
  9888. },
  9889. setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
  9890. set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
  9891. },
  9892. setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
  9893. set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
  9894. },
  9895. setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
  9896. set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
  9897. },
  9898. setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
  9899. set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined);
  9900. },
  9901. setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
  9902. set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined);
  9903. }
  9904. });
  9905. } else {
  9906. if (!fails(function () {
  9907. NativeArrayBuffer(1);
  9908. }) || !fails(function () {
  9909. new NativeArrayBuffer(-1); // eslint-disable-line no-new
  9910. }) || fails(function () {
  9911. new NativeArrayBuffer(); // eslint-disable-line no-new
  9912. new NativeArrayBuffer(1.5); // eslint-disable-line no-new
  9913. new NativeArrayBuffer(NaN); // eslint-disable-line no-new
  9914. return NativeArrayBuffer.name != ARRAY_BUFFER;
  9915. })) {
  9916. $ArrayBuffer = function ArrayBuffer(length) {
  9917. anInstance(this, $ArrayBuffer);
  9918. return new NativeArrayBuffer(toIndex(length));
  9919. };
  9920. var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE];
  9921. for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j;) {
  9922. if (!((key = keys[j++]) in $ArrayBuffer)) {
  9923. createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]);
  9924. }
  9925. }
  9926. ArrayBufferPrototype.constructor = $ArrayBuffer;
  9927. }
  9928. // iOS Safari 7.x bug
  9929. var testView = new $DataView(new $ArrayBuffer(2));
  9930. var nativeSetInt8 = $DataView[PROTOTYPE].setInt8;
  9931. testView.setInt8(0, 2147483648);
  9932. testView.setInt8(1, 2147483649);
  9933. if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
  9934. setInt8: function setInt8(byteOffset, value) {
  9935. nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
  9936. },
  9937. setUint8: function setUint8(byteOffset, value) {
  9938. nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
  9939. }
  9940. }, { unsafe: true });
  9941. }
  9942. setToStringTag($ArrayBuffer, ARRAY_BUFFER);
  9943. setToStringTag($DataView, DATA_VIEW);
  9944. module.exports = {
  9945. ArrayBuffer: $ArrayBuffer,
  9946. DataView: $DataView
  9947. };
  9948. },{"../internals/an-instance":54,"../internals/array-buffer-view-core":56,"../internals/array-fill":59,"../internals/create-non-enumerable-property":76,"../internals/descriptors":81,"../internals/fails":86,"../internals/global":92,"../internals/internal-state":100,"../internals/object-define-property":120,"../internals/object-get-own-property-names":123,"../internals/redefine-all":137,"../internals/set-to-string-tag":145,"../internals/to-index":155,"../internals/to-integer":157,"../internals/to-length":158}],58:[function(require,module,exports){
  9949. 'use strict';
  9950. var toObject = require('../internals/to-object');
  9951. var toAbsoluteIndex = require('../internals/to-absolute-index');
  9952. var toLength = require('../internals/to-length');
  9953. var min = Math.min;
  9954. // `Array.prototype.copyWithin` method implementation
  9955. // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
  9956. module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
  9957. var O = toObject(this);
  9958. var len = toLength(O.length);
  9959. var to = toAbsoluteIndex(target, len);
  9960. var from = toAbsoluteIndex(start, len);
  9961. var end = arguments.length > 2 ? arguments[2] : undefined;
  9962. var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
  9963. var inc = 1;
  9964. if (from < to && to < from + count) {
  9965. inc = -1;
  9966. from += count - 1;
  9967. to += count - 1;
  9968. }
  9969. while (count-- > 0) {
  9970. if (from in O) O[to] = O[from];
  9971. else delete O[to];
  9972. to += inc;
  9973. from += inc;
  9974. } return O;
  9975. };
  9976. },{"../internals/to-absolute-index":154,"../internals/to-length":158,"../internals/to-object":159}],59:[function(require,module,exports){
  9977. 'use strict';
  9978. var toObject = require('../internals/to-object');
  9979. var toAbsoluteIndex = require('../internals/to-absolute-index');
  9980. var toLength = require('../internals/to-length');
  9981. // `Array.prototype.fill` method implementation
  9982. // https://tc39.github.io/ecma262/#sec-array.prototype.fill
  9983. module.exports = function fill(value /* , start = 0, end = @length */) {
  9984. var O = toObject(this);
  9985. var length = toLength(O.length);
  9986. var argumentsLength = arguments.length;
  9987. var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
  9988. var end = argumentsLength > 2 ? arguments[2] : undefined;
  9989. var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
  9990. while (endPos > index) O[index++] = value;
  9991. return O;
  9992. };
  9993. },{"../internals/to-absolute-index":154,"../internals/to-length":158,"../internals/to-object":159}],60:[function(require,module,exports){
  9994. 'use strict';
  9995. var $forEach = require('../internals/array-iteration').forEach;
  9996. var sloppyArrayMethod = require('../internals/sloppy-array-method');
  9997. // `Array.prototype.forEach` method implementation
  9998. // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
  9999. module.exports = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) {
  10000. return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  10001. } : [].forEach;
  10002. },{"../internals/array-iteration":62,"../internals/sloppy-array-method":149}],61:[function(require,module,exports){
  10003. var toIndexedObject = require('../internals/to-indexed-object');
  10004. var toLength = require('../internals/to-length');
  10005. var toAbsoluteIndex = require('../internals/to-absolute-index');
  10006. // `Array.prototype.{ indexOf, includes }` methods implementation
  10007. var createMethod = function (IS_INCLUDES) {
  10008. return function ($this, el, fromIndex) {
  10009. var O = toIndexedObject($this);
  10010. var length = toLength(O.length);
  10011. var index = toAbsoluteIndex(fromIndex, length);
  10012. var value;
  10013. // Array#includes uses SameValueZero equality algorithm
  10014. // eslint-disable-next-line no-self-compare
  10015. if (IS_INCLUDES && el != el) while (length > index) {
  10016. value = O[index++];
  10017. // eslint-disable-next-line no-self-compare
  10018. if (value != value) return true;
  10019. // Array#indexOf ignores holes, Array#includes - not
  10020. } else for (;length > index; index++) {
  10021. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  10022. } return !IS_INCLUDES && -1;
  10023. };
  10024. };
  10025. module.exports = {
  10026. // `Array.prototype.includes` method
  10027. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  10028. includes: createMethod(true),
  10029. // `Array.prototype.indexOf` method
  10030. // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
  10031. indexOf: createMethod(false)
  10032. };
  10033. },{"../internals/to-absolute-index":154,"../internals/to-indexed-object":156,"../internals/to-length":158}],62:[function(require,module,exports){
  10034. var bind = require('../internals/bind-context');
  10035. var IndexedObject = require('../internals/indexed-object');
  10036. var toObject = require('../internals/to-object');
  10037. var toLength = require('../internals/to-length');
  10038. var arraySpeciesCreate = require('../internals/array-species-create');
  10039. var push = [].push;
  10040. // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
  10041. var createMethod = function (TYPE) {
  10042. var IS_MAP = TYPE == 1;
  10043. var IS_FILTER = TYPE == 2;
  10044. var IS_SOME = TYPE == 3;
  10045. var IS_EVERY = TYPE == 4;
  10046. var IS_FIND_INDEX = TYPE == 6;
  10047. var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
  10048. return function ($this, callbackfn, that, specificCreate) {
  10049. var O = toObject($this);
  10050. var self = IndexedObject(O);
  10051. var boundFunction = bind(callbackfn, that, 3);
  10052. var length = toLength(self.length);
  10053. var index = 0;
  10054. var create = specificCreate || arraySpeciesCreate;
  10055. var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
  10056. var value, result;
  10057. for (;length > index; index++) if (NO_HOLES || index in self) {
  10058. value = self[index];
  10059. result = boundFunction(value, index, O);
  10060. if (TYPE) {
  10061. if (IS_MAP) target[index] = result; // map
  10062. else if (result) switch (TYPE) {
  10063. case 3: return true; // some
  10064. case 5: return value; // find
  10065. case 6: return index; // findIndex
  10066. case 2: push.call(target, value); // filter
  10067. } else if (IS_EVERY) return false; // every
  10068. }
  10069. }
  10070. return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
  10071. };
  10072. };
  10073. module.exports = {
  10074. // `Array.prototype.forEach` method
  10075. // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
  10076. forEach: createMethod(0),
  10077. // `Array.prototype.map` method
  10078. // https://tc39.github.io/ecma262/#sec-array.prototype.map
  10079. map: createMethod(1),
  10080. // `Array.prototype.filter` method
  10081. // https://tc39.github.io/ecma262/#sec-array.prototype.filter
  10082. filter: createMethod(2),
  10083. // `Array.prototype.some` method
  10084. // https://tc39.github.io/ecma262/#sec-array.prototype.some
  10085. some: createMethod(3),
  10086. // `Array.prototype.every` method
  10087. // https://tc39.github.io/ecma262/#sec-array.prototype.every
  10088. every: createMethod(4),
  10089. // `Array.prototype.find` method
  10090. // https://tc39.github.io/ecma262/#sec-array.prototype.find
  10091. find: createMethod(5),
  10092. // `Array.prototype.findIndex` method
  10093. // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
  10094. findIndex: createMethod(6)
  10095. };
  10096. },{"../internals/array-species-create":66,"../internals/bind-context":67,"../internals/indexed-object":98,"../internals/to-length":158,"../internals/to-object":159}],63:[function(require,module,exports){
  10097. 'use strict';
  10098. var toIndexedObject = require('../internals/to-indexed-object');
  10099. var toInteger = require('../internals/to-integer');
  10100. var toLength = require('../internals/to-length');
  10101. var sloppyArrayMethod = require('../internals/sloppy-array-method');
  10102. var min = Math.min;
  10103. var nativeLastIndexOf = [].lastIndexOf;
  10104. var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
  10105. var SLOPPY_METHOD = sloppyArrayMethod('lastIndexOf');
  10106. // `Array.prototype.lastIndexOf` method implementation
  10107. // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
  10108. module.exports = (NEGATIVE_ZERO || SLOPPY_METHOD) ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
  10109. // convert -0 to +0
  10110. if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0;
  10111. var O = toIndexedObject(this);
  10112. var length = toLength(O.length);
  10113. var index = length - 1;
  10114. if (arguments.length > 1) index = min(index, toInteger(arguments[1]));
  10115. if (index < 0) index = length + index;
  10116. for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
  10117. return -1;
  10118. } : nativeLastIndexOf;
  10119. },{"../internals/sloppy-array-method":149,"../internals/to-indexed-object":156,"../internals/to-integer":157,"../internals/to-length":158}],64:[function(require,module,exports){
  10120. var fails = require('../internals/fails');
  10121. var wellKnownSymbol = require('../internals/well-known-symbol');
  10122. var V8_VERSION = require('../internals/v8-version');
  10123. var SPECIES = wellKnownSymbol('species');
  10124. module.exports = function (METHOD_NAME) {
  10125. // We can't use this feature detection in V8 since it causes
  10126. // deoptimization and serious performance degradation
  10127. // https://github.com/zloirock/core-js/issues/677
  10128. return V8_VERSION >= 51 || !fails(function () {
  10129. var array = [];
  10130. var constructor = array.constructor = {};
  10131. constructor[SPECIES] = function () {
  10132. return { foo: 1 };
  10133. };
  10134. return array[METHOD_NAME](Boolean).foo !== 1;
  10135. });
  10136. };
  10137. },{"../internals/fails":86,"../internals/v8-version":168,"../internals/well-known-symbol":169}],65:[function(require,module,exports){
  10138. var aFunction = require('../internals/a-function');
  10139. var toObject = require('../internals/to-object');
  10140. var IndexedObject = require('../internals/indexed-object');
  10141. var toLength = require('../internals/to-length');
  10142. // `Array.prototype.{ reduce, reduceRight }` methods implementation
  10143. var createMethod = function (IS_RIGHT) {
  10144. return function (that, callbackfn, argumentsLength, memo) {
  10145. aFunction(callbackfn);
  10146. var O = toObject(that);
  10147. var self = IndexedObject(O);
  10148. var length = toLength(O.length);
  10149. var index = IS_RIGHT ? length - 1 : 0;
  10150. var i = IS_RIGHT ? -1 : 1;
  10151. if (argumentsLength < 2) while (true) {
  10152. if (index in self) {
  10153. memo = self[index];
  10154. index += i;
  10155. break;
  10156. }
  10157. index += i;
  10158. if (IS_RIGHT ? index < 0 : length <= index) {
  10159. throw TypeError('Reduce of empty array with no initial value');
  10160. }
  10161. }
  10162. for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
  10163. memo = callbackfn(memo, self[index], index, O);
  10164. }
  10165. return memo;
  10166. };
  10167. };
  10168. module.exports = {
  10169. // `Array.prototype.reduce` method
  10170. // https://tc39.github.io/ecma262/#sec-array.prototype.reduce
  10171. left: createMethod(false),
  10172. // `Array.prototype.reduceRight` method
  10173. // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
  10174. right: createMethod(true)
  10175. };
  10176. },{"../internals/a-function":50,"../internals/indexed-object":98,"../internals/to-length":158,"../internals/to-object":159}],66:[function(require,module,exports){
  10177. var isObject = require('../internals/is-object');
  10178. var isArray = require('../internals/is-array');
  10179. var wellKnownSymbol = require('../internals/well-known-symbol');
  10180. var SPECIES = wellKnownSymbol('species');
  10181. // `ArraySpeciesCreate` abstract operation
  10182. // https://tc39.github.io/ecma262/#sec-arrayspeciescreate
  10183. module.exports = function (originalArray, length) {
  10184. var C;
  10185. if (isArray(originalArray)) {
  10186. C = originalArray.constructor;
  10187. // cross-realm fallback
  10188. if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
  10189. else if (isObject(C)) {
  10190. C = C[SPECIES];
  10191. if (C === null) C = undefined;
  10192. }
  10193. } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
  10194. };
  10195. },{"../internals/is-array":102,"../internals/is-object":105,"../internals/well-known-symbol":169}],67:[function(require,module,exports){
  10196. var aFunction = require('../internals/a-function');
  10197. // optional / simple context binding
  10198. module.exports = function (fn, that, length) {
  10199. aFunction(fn);
  10200. if (that === undefined) return fn;
  10201. switch (length) {
  10202. case 0: return function () {
  10203. return fn.call(that);
  10204. };
  10205. case 1: return function (a) {
  10206. return fn.call(that, a);
  10207. };
  10208. case 2: return function (a, b) {
  10209. return fn.call(that, a, b);
  10210. };
  10211. case 3: return function (a, b, c) {
  10212. return fn.call(that, a, b, c);
  10213. };
  10214. }
  10215. return function (/* ...args */) {
  10216. return fn.apply(that, arguments);
  10217. };
  10218. };
  10219. },{"../internals/a-function":50}],68:[function(require,module,exports){
  10220. var anObject = require('../internals/an-object');
  10221. // call something on iterator step with safe closing on error
  10222. module.exports = function (iterator, fn, value, ENTRIES) {
  10223. try {
  10224. return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
  10225. // 7.4.6 IteratorClose(iterator, completion)
  10226. } catch (error) {
  10227. var returnMethod = iterator['return'];
  10228. if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
  10229. throw error;
  10230. }
  10231. };
  10232. },{"../internals/an-object":55}],69:[function(require,module,exports){
  10233. var wellKnownSymbol = require('../internals/well-known-symbol');
  10234. var ITERATOR = wellKnownSymbol('iterator');
  10235. var SAFE_CLOSING = false;
  10236. try {
  10237. var called = 0;
  10238. var iteratorWithReturn = {
  10239. next: function () {
  10240. return { done: !!called++ };
  10241. },
  10242. 'return': function () {
  10243. SAFE_CLOSING = true;
  10244. }
  10245. };
  10246. iteratorWithReturn[ITERATOR] = function () {
  10247. return this;
  10248. };
  10249. // eslint-disable-next-line no-throw-literal
  10250. Array.from(iteratorWithReturn, function () { throw 2; });
  10251. } catch (error) { /* empty */ }
  10252. module.exports = function (exec, SKIP_CLOSING) {
  10253. if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
  10254. var ITERATION_SUPPORT = false;
  10255. try {
  10256. var object = {};
  10257. object[ITERATOR] = function () {
  10258. return {
  10259. next: function () {
  10260. return { done: ITERATION_SUPPORT = true };
  10261. }
  10262. };
  10263. };
  10264. exec(object);
  10265. } catch (error) { /* empty */ }
  10266. return ITERATION_SUPPORT;
  10267. };
  10268. },{"../internals/well-known-symbol":169}],70:[function(require,module,exports){
  10269. var toString = {}.toString;
  10270. module.exports = function (it) {
  10271. return toString.call(it).slice(8, -1);
  10272. };
  10273. },{}],71:[function(require,module,exports){
  10274. var classofRaw = require('../internals/classof-raw');
  10275. var wellKnownSymbol = require('../internals/well-known-symbol');
  10276. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  10277. // ES3 wrong here
  10278. var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
  10279. // fallback for IE11 Script Access Denied error
  10280. var tryGet = function (it, key) {
  10281. try {
  10282. return it[key];
  10283. } catch (error) { /* empty */ }
  10284. };
  10285. // getting tag from ES6+ `Object.prototype.toString`
  10286. module.exports = function (it) {
  10287. var O, tag, result;
  10288. return it === undefined ? 'Undefined' : it === null ? 'Null'
  10289. // @@toStringTag case
  10290. : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
  10291. // builtinTag case
  10292. : CORRECT_ARGUMENTS ? classofRaw(O)
  10293. // ES3 arguments fallback
  10294. : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
  10295. };
  10296. },{"../internals/classof-raw":70,"../internals/well-known-symbol":169}],72:[function(require,module,exports){
  10297. var has = require('../internals/has');
  10298. var ownKeys = require('../internals/own-keys');
  10299. var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
  10300. var definePropertyModule = require('../internals/object-define-property');
  10301. module.exports = function (target, source) {
  10302. var keys = ownKeys(source);
  10303. var defineProperty = definePropertyModule.f;
  10304. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  10305. for (var i = 0; i < keys.length; i++) {
  10306. var key = keys[i];
  10307. if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
  10308. }
  10309. };
  10310. },{"../internals/has":93,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/own-keys":132}],73:[function(require,module,exports){
  10311. var wellKnownSymbol = require('../internals/well-known-symbol');
  10312. var MATCH = wellKnownSymbol('match');
  10313. module.exports = function (METHOD_NAME) {
  10314. var regexp = /./;
  10315. try {
  10316. '/./'[METHOD_NAME](regexp);
  10317. } catch (e) {
  10318. try {
  10319. regexp[MATCH] = false;
  10320. return '/./'[METHOD_NAME](regexp);
  10321. } catch (f) { /* empty */ }
  10322. } return false;
  10323. };
  10324. },{"../internals/well-known-symbol":169}],74:[function(require,module,exports){
  10325. var fails = require('../internals/fails');
  10326. module.exports = !fails(function () {
  10327. function F() { /* empty */ }
  10328. F.prototype.constructor = null;
  10329. return Object.getPrototypeOf(new F()) !== F.prototype;
  10330. });
  10331. },{"../internals/fails":86}],75:[function(require,module,exports){
  10332. 'use strict';
  10333. var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;
  10334. var create = require('../internals/object-create');
  10335. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  10336. var setToStringTag = require('../internals/set-to-string-tag');
  10337. var Iterators = require('../internals/iterators');
  10338. var returnThis = function () { return this; };
  10339. module.exports = function (IteratorConstructor, NAME, next) {
  10340. var TO_STRING_TAG = NAME + ' Iterator';
  10341. IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });
  10342. setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
  10343. Iterators[TO_STRING_TAG] = returnThis;
  10344. return IteratorConstructor;
  10345. };
  10346. },{"../internals/create-property-descriptor":77,"../internals/iterators":110,"../internals/iterators-core":109,"../internals/object-create":118,"../internals/set-to-string-tag":145}],76:[function(require,module,exports){
  10347. var DESCRIPTORS = require('../internals/descriptors');
  10348. var definePropertyModule = require('../internals/object-define-property');
  10349. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  10350. module.exports = DESCRIPTORS ? function (object, key, value) {
  10351. return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
  10352. } : function (object, key, value) {
  10353. object[key] = value;
  10354. return object;
  10355. };
  10356. },{"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/object-define-property":120}],77:[function(require,module,exports){
  10357. module.exports = function (bitmap, value) {
  10358. return {
  10359. enumerable: !(bitmap & 1),
  10360. configurable: !(bitmap & 2),
  10361. writable: !(bitmap & 4),
  10362. value: value
  10363. };
  10364. };
  10365. },{}],78:[function(require,module,exports){
  10366. 'use strict';
  10367. var toPrimitive = require('../internals/to-primitive');
  10368. var definePropertyModule = require('../internals/object-define-property');
  10369. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  10370. module.exports = function (object, key, value) {
  10371. var propertyKey = toPrimitive(key);
  10372. if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
  10373. else object[propertyKey] = value;
  10374. };
  10375. },{"../internals/create-property-descriptor":77,"../internals/object-define-property":120,"../internals/to-primitive":162}],79:[function(require,module,exports){
  10376. 'use strict';
  10377. var $ = require('../internals/export');
  10378. var createIteratorConstructor = require('../internals/create-iterator-constructor');
  10379. var getPrototypeOf = require('../internals/object-get-prototype-of');
  10380. var setPrototypeOf = require('../internals/object-set-prototype-of');
  10381. var setToStringTag = require('../internals/set-to-string-tag');
  10382. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  10383. var redefine = require('../internals/redefine');
  10384. var wellKnownSymbol = require('../internals/well-known-symbol');
  10385. var IS_PURE = require('../internals/is-pure');
  10386. var Iterators = require('../internals/iterators');
  10387. var IteratorsCore = require('../internals/iterators-core');
  10388. var IteratorPrototype = IteratorsCore.IteratorPrototype;
  10389. var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
  10390. var ITERATOR = wellKnownSymbol('iterator');
  10391. var KEYS = 'keys';
  10392. var VALUES = 'values';
  10393. var ENTRIES = 'entries';
  10394. var returnThis = function () { return this; };
  10395. module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
  10396. createIteratorConstructor(IteratorConstructor, NAME, next);
  10397. var getIterationMethod = function (KIND) {
  10398. if (KIND === DEFAULT && defaultIterator) return defaultIterator;
  10399. if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
  10400. switch (KIND) {
  10401. case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
  10402. case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
  10403. case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
  10404. } return function () { return new IteratorConstructor(this); };
  10405. };
  10406. var TO_STRING_TAG = NAME + ' Iterator';
  10407. var INCORRECT_VALUES_NAME = false;
  10408. var IterablePrototype = Iterable.prototype;
  10409. var nativeIterator = IterablePrototype[ITERATOR]
  10410. || IterablePrototype['@@iterator']
  10411. || DEFAULT && IterablePrototype[DEFAULT];
  10412. var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
  10413. var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
  10414. var CurrentIteratorPrototype, methods, KEY;
  10415. // fix native
  10416. if (anyNativeIterator) {
  10417. CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
  10418. if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
  10419. if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
  10420. if (setPrototypeOf) {
  10421. setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
  10422. } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {
  10423. createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);
  10424. }
  10425. }
  10426. // Set @@toStringTag to native iterators
  10427. setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
  10428. if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
  10429. }
  10430. }
  10431. // fix Array#{values, @@iterator}.name in V8 / FF
  10432. if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
  10433. INCORRECT_VALUES_NAME = true;
  10434. defaultIterator = function values() { return nativeIterator.call(this); };
  10435. }
  10436. // define iterator
  10437. if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
  10438. createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);
  10439. }
  10440. Iterators[NAME] = defaultIterator;
  10441. // export additional methods
  10442. if (DEFAULT) {
  10443. methods = {
  10444. values: getIterationMethod(VALUES),
  10445. keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
  10446. entries: getIterationMethod(ENTRIES)
  10447. };
  10448. if (FORCED) for (KEY in methods) {
  10449. if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
  10450. redefine(IterablePrototype, KEY, methods[KEY]);
  10451. }
  10452. } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
  10453. }
  10454. return methods;
  10455. };
  10456. },{"../internals/create-iterator-constructor":75,"../internals/create-non-enumerable-property":76,"../internals/export":85,"../internals/is-pure":106,"../internals/iterators":110,"../internals/iterators-core":109,"../internals/object-get-prototype-of":125,"../internals/object-set-prototype-of":129,"../internals/redefine":138,"../internals/set-to-string-tag":145,"../internals/well-known-symbol":169}],80:[function(require,module,exports){
  10457. var path = require('../internals/path');
  10458. var has = require('../internals/has');
  10459. var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol');
  10460. var defineProperty = require('../internals/object-define-property').f;
  10461. module.exports = function (NAME) {
  10462. var Symbol = path.Symbol || (path.Symbol = {});
  10463. if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
  10464. value: wrappedWellKnownSymbolModule.f(NAME)
  10465. });
  10466. };
  10467. },{"../internals/has":93,"../internals/object-define-property":120,"../internals/path":134,"../internals/wrapped-well-known-symbol":171}],81:[function(require,module,exports){
  10468. var fails = require('../internals/fails');
  10469. // Thank's IE8 for his funny defineProperty
  10470. module.exports = !fails(function () {
  10471. return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
  10472. });
  10473. },{"../internals/fails":86}],82:[function(require,module,exports){
  10474. var global = require('../internals/global');
  10475. var isObject = require('../internals/is-object');
  10476. var document = global.document;
  10477. // typeof document.createElement is 'object' in old IE
  10478. var EXISTS = isObject(document) && isObject(document.createElement);
  10479. module.exports = function (it) {
  10480. return EXISTS ? document.createElement(it) : {};
  10481. };
  10482. },{"../internals/global":92,"../internals/is-object":105}],83:[function(require,module,exports){
  10483. // iterable DOM collections
  10484. // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
  10485. module.exports = {
  10486. CSSRuleList: 0,
  10487. CSSStyleDeclaration: 0,
  10488. CSSValueList: 0,
  10489. ClientRectList: 0,
  10490. DOMRectList: 0,
  10491. DOMStringList: 0,
  10492. DOMTokenList: 1,
  10493. DataTransferItemList: 0,
  10494. FileList: 0,
  10495. HTMLAllCollection: 0,
  10496. HTMLCollection: 0,
  10497. HTMLFormElement: 0,
  10498. HTMLSelectElement: 0,
  10499. MediaList: 0,
  10500. MimeTypeArray: 0,
  10501. NamedNodeMap: 0,
  10502. NodeList: 1,
  10503. PaintRequestList: 0,
  10504. Plugin: 0,
  10505. PluginArray: 0,
  10506. SVGLengthList: 0,
  10507. SVGNumberList: 0,
  10508. SVGPathSegList: 0,
  10509. SVGPointList: 0,
  10510. SVGStringList: 0,
  10511. SVGTransformList: 0,
  10512. SourceBufferList: 0,
  10513. StyleSheetList: 0,
  10514. TextTrackCueList: 0,
  10515. TextTrackList: 0,
  10516. TouchList: 0
  10517. };
  10518. },{}],84:[function(require,module,exports){
  10519. // IE8- don't enum bug keys
  10520. module.exports = [
  10521. 'constructor',
  10522. 'hasOwnProperty',
  10523. 'isPrototypeOf',
  10524. 'propertyIsEnumerable',
  10525. 'toLocaleString',
  10526. 'toString',
  10527. 'valueOf'
  10528. ];
  10529. },{}],85:[function(require,module,exports){
  10530. var global = require('../internals/global');
  10531. var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
  10532. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  10533. var redefine = require('../internals/redefine');
  10534. var setGlobal = require('../internals/set-global');
  10535. var copyConstructorProperties = require('../internals/copy-constructor-properties');
  10536. var isForced = require('../internals/is-forced');
  10537. /*
  10538. options.target - name of the target object
  10539. options.global - target is the global object
  10540. options.stat - export as static methods of target
  10541. options.proto - export as prototype methods of target
  10542. options.real - real prototype method for the `pure` version
  10543. options.forced - export even if the native feature is available
  10544. options.bind - bind methods to the target, required for the `pure` version
  10545. options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
  10546. options.unsafe - use the simple assignment of property instead of delete + defineProperty
  10547. options.sham - add a flag to not completely full polyfills
  10548. options.enumerable - export as enumerable property
  10549. options.noTargetGet - prevent calling a getter on target
  10550. */
  10551. module.exports = function (options, source) {
  10552. var TARGET = options.target;
  10553. var GLOBAL = options.global;
  10554. var STATIC = options.stat;
  10555. var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  10556. if (GLOBAL) {
  10557. target = global;
  10558. } else if (STATIC) {
  10559. target = global[TARGET] || setGlobal(TARGET, {});
  10560. } else {
  10561. target = (global[TARGET] || {}).prototype;
  10562. }
  10563. if (target) for (key in source) {
  10564. sourceProperty = source[key];
  10565. if (options.noTargetGet) {
  10566. descriptor = getOwnPropertyDescriptor(target, key);
  10567. targetProperty = descriptor && descriptor.value;
  10568. } else targetProperty = target[key];
  10569. FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
  10570. // contained in target
  10571. if (!FORCED && targetProperty !== undefined) {
  10572. if (typeof sourceProperty === typeof targetProperty) continue;
  10573. copyConstructorProperties(sourceProperty, targetProperty);
  10574. }
  10575. // add a flag to not completely full polyfills
  10576. if (options.sham || (targetProperty && targetProperty.sham)) {
  10577. createNonEnumerableProperty(sourceProperty, 'sham', true);
  10578. }
  10579. // extend global
  10580. redefine(target, key, sourceProperty, options);
  10581. }
  10582. };
  10583. },{"../internals/copy-constructor-properties":72,"../internals/create-non-enumerable-property":76,"../internals/global":92,"../internals/is-forced":103,"../internals/object-get-own-property-descriptor":121,"../internals/redefine":138,"../internals/set-global":143}],86:[function(require,module,exports){
  10584. module.exports = function (exec) {
  10585. try {
  10586. return !!exec();
  10587. } catch (error) {
  10588. return true;
  10589. }
  10590. };
  10591. },{}],87:[function(require,module,exports){
  10592. 'use strict';
  10593. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  10594. var redefine = require('../internals/redefine');
  10595. var fails = require('../internals/fails');
  10596. var wellKnownSymbol = require('../internals/well-known-symbol');
  10597. var regexpExec = require('../internals/regexp-exec');
  10598. var SPECIES = wellKnownSymbol('species');
  10599. var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
  10600. // #replace needs built-in support for named groups.
  10601. // #match works fine because it just return the exec results, even if it has
  10602. // a "grops" property.
  10603. var re = /./;
  10604. re.exec = function () {
  10605. var result = [];
  10606. result.groups = { a: '7' };
  10607. return result;
  10608. };
  10609. return ''.replace(re, '$<a>') !== '7';
  10610. });
  10611. // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
  10612. // Weex JS has frozen built-in prototypes, so use try / catch wrapper
  10613. var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
  10614. var re = /(?:)/;
  10615. var originalExec = re.exec;
  10616. re.exec = function () { return originalExec.apply(this, arguments); };
  10617. var result = 'ab'.split(re);
  10618. return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
  10619. });
  10620. module.exports = function (KEY, length, exec, sham) {
  10621. var SYMBOL = wellKnownSymbol(KEY);
  10622. var DELEGATES_TO_SYMBOL = !fails(function () {
  10623. // String methods call symbol-named RegEp methods
  10624. var O = {};
  10625. O[SYMBOL] = function () { return 7; };
  10626. return ''[KEY](O) != 7;
  10627. });
  10628. var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
  10629. // Symbol-named RegExp methods call .exec
  10630. var execCalled = false;
  10631. var re = /a/;
  10632. if (KEY === 'split') {
  10633. // We can't use real regex here since it causes deoptimization
  10634. // and serious performance degradation in V8
  10635. // https://github.com/zloirock/core-js/issues/306
  10636. re = {};
  10637. // RegExp[@@split] doesn't call the regex's exec method, but first creates
  10638. // a new one. We need to return the patched regex when creating the new one.
  10639. re.constructor = {};
  10640. re.constructor[SPECIES] = function () { return re; };
  10641. re.flags = '';
  10642. re[SYMBOL] = /./[SYMBOL];
  10643. }
  10644. re.exec = function () { execCalled = true; return null; };
  10645. re[SYMBOL]('');
  10646. return !execCalled;
  10647. });
  10648. if (
  10649. !DELEGATES_TO_SYMBOL ||
  10650. !DELEGATES_TO_EXEC ||
  10651. (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
  10652. (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
  10653. ) {
  10654. var nativeRegExpMethod = /./[SYMBOL];
  10655. var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
  10656. if (regexp.exec === regexpExec) {
  10657. if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
  10658. // The native String method already delegates to @@method (this
  10659. // polyfilled function), leasing to infinite recursion.
  10660. // We avoid it by directly calling the native @@method method.
  10661. return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
  10662. }
  10663. return { done: true, value: nativeMethod.call(str, regexp, arg2) };
  10664. }
  10665. return { done: false };
  10666. });
  10667. var stringMethod = methods[0];
  10668. var regexMethod = methods[1];
  10669. redefine(String.prototype, KEY, stringMethod);
  10670. redefine(RegExp.prototype, SYMBOL, length == 2
  10671. // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
  10672. // 21.2.5.11 RegExp.prototype[@@split](string, limit)
  10673. ? function (string, arg) { return regexMethod.call(string, this, arg); }
  10674. // 21.2.5.6 RegExp.prototype[@@match](string)
  10675. // 21.2.5.9 RegExp.prototype[@@search](string)
  10676. : function (string) { return regexMethod.call(string, this); }
  10677. );
  10678. if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true);
  10679. }
  10680. };
  10681. },{"../internals/create-non-enumerable-property":76,"../internals/fails":86,"../internals/redefine":138,"../internals/regexp-exec":140,"../internals/well-known-symbol":169}],88:[function(require,module,exports){
  10682. 'use strict';
  10683. var aFunction = require('../internals/a-function');
  10684. var isObject = require('../internals/is-object');
  10685. var slice = [].slice;
  10686. var factories = {};
  10687. var construct = function (C, argsLength, args) {
  10688. if (!(argsLength in factories)) {
  10689. for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
  10690. // eslint-disable-next-line no-new-func
  10691. factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
  10692. } return factories[argsLength](C, args);
  10693. };
  10694. // `Function.prototype.bind` method implementation
  10695. // https://tc39.github.io/ecma262/#sec-function.prototype.bind
  10696. module.exports = Function.bind || function bind(that /* , ...args */) {
  10697. var fn = aFunction(this);
  10698. var partArgs = slice.call(arguments, 1);
  10699. var boundFunction = function bound(/* args... */) {
  10700. var args = partArgs.concat(slice.call(arguments));
  10701. return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
  10702. };
  10703. if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype;
  10704. return boundFunction;
  10705. };
  10706. },{"../internals/a-function":50,"../internals/is-object":105}],89:[function(require,module,exports){
  10707. var shared = require('../internals/shared');
  10708. module.exports = shared('native-function-to-string', Function.toString);
  10709. },{"../internals/shared":148}],90:[function(require,module,exports){
  10710. var path = require('../internals/path');
  10711. var global = require('../internals/global');
  10712. var aFunction = function (variable) {
  10713. return typeof variable == 'function' ? variable : undefined;
  10714. };
  10715. module.exports = function (namespace, method) {
  10716. return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
  10717. : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
  10718. };
  10719. },{"../internals/global":92,"../internals/path":134}],91:[function(require,module,exports){
  10720. var classof = require('../internals/classof');
  10721. var Iterators = require('../internals/iterators');
  10722. var wellKnownSymbol = require('../internals/well-known-symbol');
  10723. var ITERATOR = wellKnownSymbol('iterator');
  10724. module.exports = function (it) {
  10725. if (it != undefined) return it[ITERATOR]
  10726. || it['@@iterator']
  10727. || Iterators[classof(it)];
  10728. };
  10729. },{"../internals/classof":71,"../internals/iterators":110,"../internals/well-known-symbol":169}],92:[function(require,module,exports){
  10730. (function (global){
  10731. var check = function (it) {
  10732. return it && it.Math == Math && it;
  10733. };
  10734. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  10735. module.exports =
  10736. // eslint-disable-next-line no-undef
  10737. check(typeof globalThis == 'object' && globalThis) ||
  10738. check(typeof window == 'object' && window) ||
  10739. check(typeof self == 'object' && self) ||
  10740. check(typeof global == 'object' && global) ||
  10741. // eslint-disable-next-line no-new-func
  10742. Function('return this')();
  10743. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10744. },{}],93:[function(require,module,exports){
  10745. var hasOwnProperty = {}.hasOwnProperty;
  10746. module.exports = function (it, key) {
  10747. return hasOwnProperty.call(it, key);
  10748. };
  10749. },{}],94:[function(require,module,exports){
  10750. module.exports = {};
  10751. },{}],95:[function(require,module,exports){
  10752. var global = require('../internals/global');
  10753. module.exports = function (a, b) {
  10754. var console = global.console;
  10755. if (console && console.error) {
  10756. arguments.length === 1 ? console.error(a) : console.error(a, b);
  10757. }
  10758. };
  10759. },{"../internals/global":92}],96:[function(require,module,exports){
  10760. var getBuiltIn = require('../internals/get-built-in');
  10761. module.exports = getBuiltIn('document', 'documentElement');
  10762. },{"../internals/get-built-in":90}],97:[function(require,module,exports){
  10763. var DESCRIPTORS = require('../internals/descriptors');
  10764. var fails = require('../internals/fails');
  10765. var createElement = require('../internals/document-create-element');
  10766. // Thank's IE8 for his funny defineProperty
  10767. module.exports = !DESCRIPTORS && !fails(function () {
  10768. return Object.defineProperty(createElement('div'), 'a', {
  10769. get: function () { return 7; }
  10770. }).a != 7;
  10771. });
  10772. },{"../internals/descriptors":81,"../internals/document-create-element":82,"../internals/fails":86}],98:[function(require,module,exports){
  10773. var fails = require('../internals/fails');
  10774. var classof = require('../internals/classof-raw');
  10775. var split = ''.split;
  10776. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  10777. module.exports = fails(function () {
  10778. // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  10779. // eslint-disable-next-line no-prototype-builtins
  10780. return !Object('z').propertyIsEnumerable(0);
  10781. }) ? function (it) {
  10782. return classof(it) == 'String' ? split.call(it, '') : Object(it);
  10783. } : Object;
  10784. },{"../internals/classof-raw":70,"../internals/fails":86}],99:[function(require,module,exports){
  10785. var isObject = require('../internals/is-object');
  10786. var setPrototypeOf = require('../internals/object-set-prototype-of');
  10787. // makes subclassing work correct for wrapped built-ins
  10788. module.exports = function ($this, dummy, Wrapper) {
  10789. var NewTarget, NewTargetPrototype;
  10790. if (
  10791. // it can work only with native `setPrototypeOf`
  10792. setPrototypeOf &&
  10793. // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
  10794. typeof (NewTarget = dummy.constructor) == 'function' &&
  10795. NewTarget !== Wrapper &&
  10796. isObject(NewTargetPrototype = NewTarget.prototype) &&
  10797. NewTargetPrototype !== Wrapper.prototype
  10798. ) setPrototypeOf($this, NewTargetPrototype);
  10799. return $this;
  10800. };
  10801. },{"../internals/is-object":105,"../internals/object-set-prototype-of":129}],100:[function(require,module,exports){
  10802. var NATIVE_WEAK_MAP = require('../internals/native-weak-map');
  10803. var global = require('../internals/global');
  10804. var isObject = require('../internals/is-object');
  10805. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  10806. var objectHas = require('../internals/has');
  10807. var sharedKey = require('../internals/shared-key');
  10808. var hiddenKeys = require('../internals/hidden-keys');
  10809. var WeakMap = global.WeakMap;
  10810. var set, get, has;
  10811. var enforce = function (it) {
  10812. return has(it) ? get(it) : set(it, {});
  10813. };
  10814. var getterFor = function (TYPE) {
  10815. return function (it) {
  10816. var state;
  10817. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  10818. throw TypeError('Incompatible receiver, ' + TYPE + ' required');
  10819. } return state;
  10820. };
  10821. };
  10822. if (NATIVE_WEAK_MAP) {
  10823. var store = new WeakMap();
  10824. var wmget = store.get;
  10825. var wmhas = store.has;
  10826. var wmset = store.set;
  10827. set = function (it, metadata) {
  10828. wmset.call(store, it, metadata);
  10829. return metadata;
  10830. };
  10831. get = function (it) {
  10832. return wmget.call(store, it) || {};
  10833. };
  10834. has = function (it) {
  10835. return wmhas.call(store, it);
  10836. };
  10837. } else {
  10838. var STATE = sharedKey('state');
  10839. hiddenKeys[STATE] = true;
  10840. set = function (it, metadata) {
  10841. createNonEnumerableProperty(it, STATE, metadata);
  10842. return metadata;
  10843. };
  10844. get = function (it) {
  10845. return objectHas(it, STATE) ? it[STATE] : {};
  10846. };
  10847. has = function (it) {
  10848. return objectHas(it, STATE);
  10849. };
  10850. }
  10851. module.exports = {
  10852. set: set,
  10853. get: get,
  10854. has: has,
  10855. enforce: enforce,
  10856. getterFor: getterFor
  10857. };
  10858. },{"../internals/create-non-enumerable-property":76,"../internals/global":92,"../internals/has":93,"../internals/hidden-keys":94,"../internals/is-object":105,"../internals/native-weak-map":114,"../internals/shared-key":146}],101:[function(require,module,exports){
  10859. var wellKnownSymbol = require('../internals/well-known-symbol');
  10860. var Iterators = require('../internals/iterators');
  10861. var ITERATOR = wellKnownSymbol('iterator');
  10862. var ArrayPrototype = Array.prototype;
  10863. // check on default Array iterator
  10864. module.exports = function (it) {
  10865. return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
  10866. };
  10867. },{"../internals/iterators":110,"../internals/well-known-symbol":169}],102:[function(require,module,exports){
  10868. var classof = require('../internals/classof-raw');
  10869. // `IsArray` abstract operation
  10870. // https://tc39.github.io/ecma262/#sec-isarray
  10871. module.exports = Array.isArray || function isArray(arg) {
  10872. return classof(arg) == 'Array';
  10873. };
  10874. },{"../internals/classof-raw":70}],103:[function(require,module,exports){
  10875. var fails = require('../internals/fails');
  10876. var replacement = /#|\.prototype\./;
  10877. var isForced = function (feature, detection) {
  10878. var value = data[normalize(feature)];
  10879. return value == POLYFILL ? true
  10880. : value == NATIVE ? false
  10881. : typeof detection == 'function' ? fails(detection)
  10882. : !!detection;
  10883. };
  10884. var normalize = isForced.normalize = function (string) {
  10885. return String(string).replace(replacement, '.').toLowerCase();
  10886. };
  10887. var data = isForced.data = {};
  10888. var NATIVE = isForced.NATIVE = 'N';
  10889. var POLYFILL = isForced.POLYFILL = 'P';
  10890. module.exports = isForced;
  10891. },{"../internals/fails":86}],104:[function(require,module,exports){
  10892. var userAgent = require('../internals/user-agent');
  10893. module.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);
  10894. },{"../internals/user-agent":167}],105:[function(require,module,exports){
  10895. module.exports = function (it) {
  10896. return typeof it === 'object' ? it !== null : typeof it === 'function';
  10897. };
  10898. },{}],106:[function(require,module,exports){
  10899. module.exports = false;
  10900. },{}],107:[function(require,module,exports){
  10901. var isObject = require('../internals/is-object');
  10902. var classof = require('../internals/classof-raw');
  10903. var wellKnownSymbol = require('../internals/well-known-symbol');
  10904. var MATCH = wellKnownSymbol('match');
  10905. // `IsRegExp` abstract operation
  10906. // https://tc39.github.io/ecma262/#sec-isregexp
  10907. module.exports = function (it) {
  10908. var isRegExp;
  10909. return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');
  10910. };
  10911. },{"../internals/classof-raw":70,"../internals/is-object":105,"../internals/well-known-symbol":169}],108:[function(require,module,exports){
  10912. var anObject = require('../internals/an-object');
  10913. var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
  10914. var toLength = require('../internals/to-length');
  10915. var bind = require('../internals/bind-context');
  10916. var getIteratorMethod = require('../internals/get-iterator-method');
  10917. var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
  10918. var Result = function (stopped, result) {
  10919. this.stopped = stopped;
  10920. this.result = result;
  10921. };
  10922. var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {
  10923. var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);
  10924. var iterator, iterFn, index, length, result, next, step;
  10925. if (IS_ITERATOR) {
  10926. iterator = iterable;
  10927. } else {
  10928. iterFn = getIteratorMethod(iterable);
  10929. if (typeof iterFn != 'function') throw TypeError('Target is not iterable');
  10930. // optimisation for array iterators
  10931. if (isArrayIteratorMethod(iterFn)) {
  10932. for (index = 0, length = toLength(iterable.length); length > index; index++) {
  10933. result = AS_ENTRIES
  10934. ? boundFunction(anObject(step = iterable[index])[0], step[1])
  10935. : boundFunction(iterable[index]);
  10936. if (result && result instanceof Result) return result;
  10937. } return new Result(false);
  10938. }
  10939. iterator = iterFn.call(iterable);
  10940. }
  10941. next = iterator.next;
  10942. while (!(step = next.call(iterator)).done) {
  10943. result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);
  10944. if (typeof result == 'object' && result && result instanceof Result) return result;
  10945. } return new Result(false);
  10946. };
  10947. iterate.stop = function (result) {
  10948. return new Result(true, result);
  10949. };
  10950. },{"../internals/an-object":55,"../internals/bind-context":67,"../internals/call-with-safe-iteration-closing":68,"../internals/get-iterator-method":91,"../internals/is-array-iterator-method":101,"../internals/to-length":158}],109:[function(require,module,exports){
  10951. 'use strict';
  10952. var getPrototypeOf = require('../internals/object-get-prototype-of');
  10953. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  10954. var has = require('../internals/has');
  10955. var wellKnownSymbol = require('../internals/well-known-symbol');
  10956. var IS_PURE = require('../internals/is-pure');
  10957. var ITERATOR = wellKnownSymbol('iterator');
  10958. var BUGGY_SAFARI_ITERATORS = false;
  10959. var returnThis = function () { return this; };
  10960. // `%IteratorPrototype%` object
  10961. // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
  10962. var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
  10963. if ([].keys) {
  10964. arrayIterator = [].keys();
  10965. // Safari 8 has buggy iterators w/o `next`
  10966. if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
  10967. else {
  10968. PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
  10969. if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
  10970. }
  10971. }
  10972. if (IteratorPrototype == undefined) IteratorPrototype = {};
  10973. // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
  10974. if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {
  10975. createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
  10976. }
  10977. module.exports = {
  10978. IteratorPrototype: IteratorPrototype,
  10979. BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
  10980. };
  10981. },{"../internals/create-non-enumerable-property":76,"../internals/has":93,"../internals/is-pure":106,"../internals/object-get-prototype-of":125,"../internals/well-known-symbol":169}],110:[function(require,module,exports){
  10982. arguments[4][94][0].apply(exports,arguments)
  10983. },{"dup":94}],111:[function(require,module,exports){
  10984. var global = require('../internals/global');
  10985. var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
  10986. var classof = require('../internals/classof-raw');
  10987. var macrotask = require('../internals/task').set;
  10988. var IS_IOS = require('../internals/is-ios');
  10989. var MutationObserver = global.MutationObserver || global.WebKitMutationObserver;
  10990. var process = global.process;
  10991. var Promise = global.Promise;
  10992. var IS_NODE = classof(process) == 'process';
  10993. // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
  10994. var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');
  10995. var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
  10996. var flush, head, last, notify, toggle, node, promise, then;
  10997. // modern engines have queueMicrotask method
  10998. if (!queueMicrotask) {
  10999. flush = function () {
  11000. var parent, fn;
  11001. if (IS_NODE && (parent = process.domain)) parent.exit();
  11002. while (head) {
  11003. fn = head.fn;
  11004. head = head.next;
  11005. try {
  11006. fn();
  11007. } catch (error) {
  11008. if (head) notify();
  11009. else last = undefined;
  11010. throw error;
  11011. }
  11012. } last = undefined;
  11013. if (parent) parent.enter();
  11014. };
  11015. // Node.js
  11016. if (IS_NODE) {
  11017. notify = function () {
  11018. process.nextTick(flush);
  11019. };
  11020. // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
  11021. } else if (MutationObserver && !IS_IOS) {
  11022. toggle = true;
  11023. node = document.createTextNode('');
  11024. new MutationObserver(flush).observe(node, { characterData: true });
  11025. notify = function () {
  11026. node.data = toggle = !toggle;
  11027. };
  11028. // environments with maybe non-completely correct, but existent Promise
  11029. } else if (Promise && Promise.resolve) {
  11030. // Promise.resolve without an argument throws an error in LG WebOS 2
  11031. promise = Promise.resolve(undefined);
  11032. then = promise.then;
  11033. notify = function () {
  11034. then.call(promise, flush);
  11035. };
  11036. // for other environments - macrotask based on:
  11037. // - setImmediate
  11038. // - MessageChannel
  11039. // - window.postMessag
  11040. // - onreadystatechange
  11041. // - setTimeout
  11042. } else {
  11043. notify = function () {
  11044. // strange IE + webpack dev server bug - use .call(global)
  11045. macrotask.call(global, flush);
  11046. };
  11047. }
  11048. }
  11049. module.exports = queueMicrotask || function (fn) {
  11050. var task = { fn: fn, next: undefined };
  11051. if (last) last.next = task;
  11052. if (!head) {
  11053. head = task;
  11054. notify();
  11055. } last = task;
  11056. };
  11057. },{"../internals/classof-raw":70,"../internals/global":92,"../internals/is-ios":104,"../internals/object-get-own-property-descriptor":121,"../internals/task":153}],112:[function(require,module,exports){
  11058. var global = require('../internals/global');
  11059. module.exports = global.Promise;
  11060. },{"../internals/global":92}],113:[function(require,module,exports){
  11061. var fails = require('../internals/fails');
  11062. module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
  11063. // Chrome 38 Symbol has incorrect toString conversion
  11064. // eslint-disable-next-line no-undef
  11065. return !String(Symbol());
  11066. });
  11067. },{"../internals/fails":86}],114:[function(require,module,exports){
  11068. var global = require('../internals/global');
  11069. var nativeFunctionToString = require('../internals/function-to-string');
  11070. var WeakMap = global.WeakMap;
  11071. module.exports = typeof WeakMap === 'function' && /native code/.test(nativeFunctionToString.call(WeakMap));
  11072. },{"../internals/function-to-string":89,"../internals/global":92}],115:[function(require,module,exports){
  11073. 'use strict';
  11074. var aFunction = require('../internals/a-function');
  11075. var PromiseCapability = function (C) {
  11076. var resolve, reject;
  11077. this.promise = new C(function ($$resolve, $$reject) {
  11078. if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
  11079. resolve = $$resolve;
  11080. reject = $$reject;
  11081. });
  11082. this.resolve = aFunction(resolve);
  11083. this.reject = aFunction(reject);
  11084. };
  11085. // 25.4.1.5 NewPromiseCapability(C)
  11086. module.exports.f = function (C) {
  11087. return new PromiseCapability(C);
  11088. };
  11089. },{"../internals/a-function":50}],116:[function(require,module,exports){
  11090. var isRegExp = require('../internals/is-regexp');
  11091. module.exports = function (it) {
  11092. if (isRegExp(it)) {
  11093. throw TypeError("The method doesn't accept regular expressions");
  11094. } return it;
  11095. };
  11096. },{"../internals/is-regexp":107}],117:[function(require,module,exports){
  11097. 'use strict';
  11098. var DESCRIPTORS = require('../internals/descriptors');
  11099. var fails = require('../internals/fails');
  11100. var objectKeys = require('../internals/object-keys');
  11101. var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
  11102. var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
  11103. var toObject = require('../internals/to-object');
  11104. var IndexedObject = require('../internals/indexed-object');
  11105. var nativeAssign = Object.assign;
  11106. // `Object.assign` method
  11107. // https://tc39.github.io/ecma262/#sec-object.assign
  11108. // should work with symbols and should have deterministic property order (V8 bug)
  11109. module.exports = !nativeAssign || fails(function () {
  11110. var A = {};
  11111. var B = {};
  11112. // eslint-disable-next-line no-undef
  11113. var symbol = Symbol();
  11114. var alphabet = 'abcdefghijklmnopqrst';
  11115. A[symbol] = 7;
  11116. alphabet.split('').forEach(function (chr) { B[chr] = chr; });
  11117. return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
  11118. }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  11119. var T = toObject(target);
  11120. var argumentsLength = arguments.length;
  11121. var index = 1;
  11122. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  11123. var propertyIsEnumerable = propertyIsEnumerableModule.f;
  11124. while (argumentsLength > index) {
  11125. var S = IndexedObject(arguments[index++]);
  11126. var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
  11127. var length = keys.length;
  11128. var j = 0;
  11129. var key;
  11130. while (length > j) {
  11131. key = keys[j++];
  11132. if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
  11133. }
  11134. } return T;
  11135. } : nativeAssign;
  11136. },{"../internals/descriptors":81,"../internals/fails":86,"../internals/indexed-object":98,"../internals/object-get-own-property-symbols":124,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/to-object":159}],118:[function(require,module,exports){
  11137. var anObject = require('../internals/an-object');
  11138. var defineProperties = require('../internals/object-define-properties');
  11139. var enumBugKeys = require('../internals/enum-bug-keys');
  11140. var hiddenKeys = require('../internals/hidden-keys');
  11141. var html = require('../internals/html');
  11142. var documentCreateElement = require('../internals/document-create-element');
  11143. var sharedKey = require('../internals/shared-key');
  11144. var IE_PROTO = sharedKey('IE_PROTO');
  11145. var PROTOTYPE = 'prototype';
  11146. var Empty = function () { /* empty */ };
  11147. // Create object with fake `null` prototype: use iframe Object with cleared prototype
  11148. var createDict = function () {
  11149. // Thrash, waste and sodomy: IE GC bug
  11150. var iframe = documentCreateElement('iframe');
  11151. var length = enumBugKeys.length;
  11152. var lt = '<';
  11153. var script = 'script';
  11154. var gt = '>';
  11155. var js = 'java' + script + ':';
  11156. var iframeDocument;
  11157. iframe.style.display = 'none';
  11158. html.appendChild(iframe);
  11159. iframe.src = String(js);
  11160. iframeDocument = iframe.contentWindow.document;
  11161. iframeDocument.open();
  11162. iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt);
  11163. iframeDocument.close();
  11164. createDict = iframeDocument.F;
  11165. while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]];
  11166. return createDict();
  11167. };
  11168. // `Object.create` method
  11169. // https://tc39.github.io/ecma262/#sec-object.create
  11170. module.exports = Object.create || function create(O, Properties) {
  11171. var result;
  11172. if (O !== null) {
  11173. Empty[PROTOTYPE] = anObject(O);
  11174. result = new Empty();
  11175. Empty[PROTOTYPE] = null;
  11176. // add "__proto__" for Object.getPrototypeOf polyfill
  11177. result[IE_PROTO] = O;
  11178. } else result = createDict();
  11179. return Properties === undefined ? result : defineProperties(result, Properties);
  11180. };
  11181. hiddenKeys[IE_PROTO] = true;
  11182. },{"../internals/an-object":55,"../internals/document-create-element":82,"../internals/enum-bug-keys":84,"../internals/hidden-keys":94,"../internals/html":96,"../internals/object-define-properties":119,"../internals/shared-key":146}],119:[function(require,module,exports){
  11183. var DESCRIPTORS = require('../internals/descriptors');
  11184. var definePropertyModule = require('../internals/object-define-property');
  11185. var anObject = require('../internals/an-object');
  11186. var objectKeys = require('../internals/object-keys');
  11187. // `Object.defineProperties` method
  11188. // https://tc39.github.io/ecma262/#sec-object.defineproperties
  11189. module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
  11190. anObject(O);
  11191. var keys = objectKeys(Properties);
  11192. var length = keys.length;
  11193. var index = 0;
  11194. var key;
  11195. while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);
  11196. return O;
  11197. };
  11198. },{"../internals/an-object":55,"../internals/descriptors":81,"../internals/object-define-property":120,"../internals/object-keys":127}],120:[function(require,module,exports){
  11199. var DESCRIPTORS = require('../internals/descriptors');
  11200. var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
  11201. var anObject = require('../internals/an-object');
  11202. var toPrimitive = require('../internals/to-primitive');
  11203. var nativeDefineProperty = Object.defineProperty;
  11204. // `Object.defineProperty` method
  11205. // https://tc39.github.io/ecma262/#sec-object.defineproperty
  11206. exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
  11207. anObject(O);
  11208. P = toPrimitive(P, true);
  11209. anObject(Attributes);
  11210. if (IE8_DOM_DEFINE) try {
  11211. return nativeDefineProperty(O, P, Attributes);
  11212. } catch (error) { /* empty */ }
  11213. if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
  11214. if ('value' in Attributes) O[P] = Attributes.value;
  11215. return O;
  11216. };
  11217. },{"../internals/an-object":55,"../internals/descriptors":81,"../internals/ie8-dom-define":97,"../internals/to-primitive":162}],121:[function(require,module,exports){
  11218. var DESCRIPTORS = require('../internals/descriptors');
  11219. var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
  11220. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  11221. var toIndexedObject = require('../internals/to-indexed-object');
  11222. var toPrimitive = require('../internals/to-primitive');
  11223. var has = require('../internals/has');
  11224. var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
  11225. var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  11226. // `Object.getOwnPropertyDescriptor` method
  11227. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
  11228. exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  11229. O = toIndexedObject(O);
  11230. P = toPrimitive(P, true);
  11231. if (IE8_DOM_DEFINE) try {
  11232. return nativeGetOwnPropertyDescriptor(O, P);
  11233. } catch (error) { /* empty */ }
  11234. if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
  11235. };
  11236. },{"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/has":93,"../internals/ie8-dom-define":97,"../internals/object-property-is-enumerable":128,"../internals/to-indexed-object":156,"../internals/to-primitive":162}],122:[function(require,module,exports){
  11237. var toIndexedObject = require('../internals/to-indexed-object');
  11238. var nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f;
  11239. var toString = {}.toString;
  11240. var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  11241. ? Object.getOwnPropertyNames(window) : [];
  11242. var getWindowNames = function (it) {
  11243. try {
  11244. return nativeGetOwnPropertyNames(it);
  11245. } catch (error) {
  11246. return windowNames.slice();
  11247. }
  11248. };
  11249. // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
  11250. module.exports.f = function getOwnPropertyNames(it) {
  11251. return windowNames && toString.call(it) == '[object Window]'
  11252. ? getWindowNames(it)
  11253. : nativeGetOwnPropertyNames(toIndexedObject(it));
  11254. };
  11255. },{"../internals/object-get-own-property-names":123,"../internals/to-indexed-object":156}],123:[function(require,module,exports){
  11256. var internalObjectKeys = require('../internals/object-keys-internal');
  11257. var enumBugKeys = require('../internals/enum-bug-keys');
  11258. var hiddenKeys = enumBugKeys.concat('length', 'prototype');
  11259. // `Object.getOwnPropertyNames` method
  11260. // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
  11261. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  11262. return internalObjectKeys(O, hiddenKeys);
  11263. };
  11264. },{"../internals/enum-bug-keys":84,"../internals/object-keys-internal":126}],124:[function(require,module,exports){
  11265. exports.f = Object.getOwnPropertySymbols;
  11266. },{}],125:[function(require,module,exports){
  11267. var has = require('../internals/has');
  11268. var toObject = require('../internals/to-object');
  11269. var sharedKey = require('../internals/shared-key');
  11270. var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');
  11271. var IE_PROTO = sharedKey('IE_PROTO');
  11272. var ObjectPrototype = Object.prototype;
  11273. // `Object.getPrototypeOf` method
  11274. // https://tc39.github.io/ecma262/#sec-object.getprototypeof
  11275. module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
  11276. O = toObject(O);
  11277. if (has(O, IE_PROTO)) return O[IE_PROTO];
  11278. if (typeof O.constructor == 'function' && O instanceof O.constructor) {
  11279. return O.constructor.prototype;
  11280. } return O instanceof Object ? ObjectPrototype : null;
  11281. };
  11282. },{"../internals/correct-prototype-getter":74,"../internals/has":93,"../internals/shared-key":146,"../internals/to-object":159}],126:[function(require,module,exports){
  11283. var has = require('../internals/has');
  11284. var toIndexedObject = require('../internals/to-indexed-object');
  11285. var indexOf = require('../internals/array-includes').indexOf;
  11286. var hiddenKeys = require('../internals/hidden-keys');
  11287. module.exports = function (object, names) {
  11288. var O = toIndexedObject(object);
  11289. var i = 0;
  11290. var result = [];
  11291. var key;
  11292. for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
  11293. // Don't enum bug & hidden keys
  11294. while (names.length > i) if (has(O, key = names[i++])) {
  11295. ~indexOf(result, key) || result.push(key);
  11296. }
  11297. return result;
  11298. };
  11299. },{"../internals/array-includes":61,"../internals/has":93,"../internals/hidden-keys":94,"../internals/to-indexed-object":156}],127:[function(require,module,exports){
  11300. var internalObjectKeys = require('../internals/object-keys-internal');
  11301. var enumBugKeys = require('../internals/enum-bug-keys');
  11302. // `Object.keys` method
  11303. // https://tc39.github.io/ecma262/#sec-object.keys
  11304. module.exports = Object.keys || function keys(O) {
  11305. return internalObjectKeys(O, enumBugKeys);
  11306. };
  11307. },{"../internals/enum-bug-keys":84,"../internals/object-keys-internal":126}],128:[function(require,module,exports){
  11308. 'use strict';
  11309. var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
  11310. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  11311. // Nashorn ~ JDK8 bug
  11312. var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
  11313. // `Object.prototype.propertyIsEnumerable` method implementation
  11314. // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
  11315. exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  11316. var descriptor = getOwnPropertyDescriptor(this, V);
  11317. return !!descriptor && descriptor.enumerable;
  11318. } : nativePropertyIsEnumerable;
  11319. },{}],129:[function(require,module,exports){
  11320. var anObject = require('../internals/an-object');
  11321. var aPossiblePrototype = require('../internals/a-possible-prototype');
  11322. // `Object.setPrototypeOf` method
  11323. // https://tc39.github.io/ecma262/#sec-object.setprototypeof
  11324. // Works with __proto__ only. Old v8 can't work with null proto objects.
  11325. /* eslint-disable no-proto */
  11326. module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
  11327. var CORRECT_SETTER = false;
  11328. var test = {};
  11329. var setter;
  11330. try {
  11331. setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
  11332. setter.call(test, []);
  11333. CORRECT_SETTER = test instanceof Array;
  11334. } catch (error) { /* empty */ }
  11335. return function setPrototypeOf(O, proto) {
  11336. anObject(O);
  11337. aPossiblePrototype(proto);
  11338. if (CORRECT_SETTER) setter.call(O, proto);
  11339. else O.__proto__ = proto;
  11340. return O;
  11341. };
  11342. }() : undefined);
  11343. },{"../internals/a-possible-prototype":51,"../internals/an-object":55}],130:[function(require,module,exports){
  11344. var DESCRIPTORS = require('../internals/descriptors');
  11345. var objectKeys = require('../internals/object-keys');
  11346. var toIndexedObject = require('../internals/to-indexed-object');
  11347. var propertyIsEnumerable = require('../internals/object-property-is-enumerable').f;
  11348. // `Object.{ entries, values }` methods implementation
  11349. var createMethod = function (TO_ENTRIES) {
  11350. return function (it) {
  11351. var O = toIndexedObject(it);
  11352. var keys = objectKeys(O);
  11353. var length = keys.length;
  11354. var i = 0;
  11355. var result = [];
  11356. var key;
  11357. while (length > i) {
  11358. key = keys[i++];
  11359. if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) {
  11360. result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
  11361. }
  11362. }
  11363. return result;
  11364. };
  11365. };
  11366. module.exports = {
  11367. // `Object.entries` method
  11368. // https://tc39.github.io/ecma262/#sec-object.entries
  11369. entries: createMethod(true),
  11370. // `Object.values` method
  11371. // https://tc39.github.io/ecma262/#sec-object.values
  11372. values: createMethod(false)
  11373. };
  11374. },{"../internals/descriptors":81,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/to-indexed-object":156}],131:[function(require,module,exports){
  11375. 'use strict';
  11376. var classof = require('../internals/classof');
  11377. var wellKnownSymbol = require('../internals/well-known-symbol');
  11378. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  11379. var test = {};
  11380. test[TO_STRING_TAG] = 'z';
  11381. // `Object.prototype.toString` method implementation
  11382. // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
  11383. module.exports = String(test) !== '[object z]' ? function toString() {
  11384. return '[object ' + classof(this) + ']';
  11385. } : test.toString;
  11386. },{"../internals/classof":71,"../internals/well-known-symbol":169}],132:[function(require,module,exports){
  11387. var getBuiltIn = require('../internals/get-built-in');
  11388. var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');
  11389. var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
  11390. var anObject = require('../internals/an-object');
  11391. // all object keys, includes non-enumerable and symbols
  11392. module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  11393. var keys = getOwnPropertyNamesModule.f(anObject(it));
  11394. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  11395. return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
  11396. };
  11397. },{"../internals/an-object":55,"../internals/get-built-in":90,"../internals/object-get-own-property-names":123,"../internals/object-get-own-property-symbols":124}],133:[function(require,module,exports){
  11398. var global = require('../internals/global');
  11399. var trim = require('../internals/string-trim').trim;
  11400. var whitespaces = require('../internals/whitespaces');
  11401. var nativeParseInt = global.parseInt;
  11402. var hex = /^[+-]?0[Xx]/;
  11403. var FORCED = nativeParseInt(whitespaces + '08') !== 8 || nativeParseInt(whitespaces + '0x16') !== 22;
  11404. // `parseInt` method
  11405. // https://tc39.github.io/ecma262/#sec-parseint-string-radix
  11406. module.exports = FORCED ? function parseInt(string, radix) {
  11407. var S = trim(String(string));
  11408. return nativeParseInt(S, (radix >>> 0) || (hex.test(S) ? 16 : 10));
  11409. } : nativeParseInt;
  11410. },{"../internals/global":92,"../internals/string-trim":152,"../internals/whitespaces":170}],134:[function(require,module,exports){
  11411. module.exports = require('../internals/global');
  11412. },{"../internals/global":92}],135:[function(require,module,exports){
  11413. module.exports = function (exec) {
  11414. try {
  11415. return { error: false, value: exec() };
  11416. } catch (error) {
  11417. return { error: true, value: error };
  11418. }
  11419. };
  11420. },{}],136:[function(require,module,exports){
  11421. var anObject = require('../internals/an-object');
  11422. var isObject = require('../internals/is-object');
  11423. var newPromiseCapability = require('../internals/new-promise-capability');
  11424. module.exports = function (C, x) {
  11425. anObject(C);
  11426. if (isObject(x) && x.constructor === C) return x;
  11427. var promiseCapability = newPromiseCapability.f(C);
  11428. var resolve = promiseCapability.resolve;
  11429. resolve(x);
  11430. return promiseCapability.promise;
  11431. };
  11432. },{"../internals/an-object":55,"../internals/is-object":105,"../internals/new-promise-capability":115}],137:[function(require,module,exports){
  11433. var redefine = require('../internals/redefine');
  11434. module.exports = function (target, src, options) {
  11435. for (var key in src) redefine(target, key, src[key], options);
  11436. return target;
  11437. };
  11438. },{"../internals/redefine":138}],138:[function(require,module,exports){
  11439. var global = require('../internals/global');
  11440. var shared = require('../internals/shared');
  11441. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  11442. var has = require('../internals/has');
  11443. var setGlobal = require('../internals/set-global');
  11444. var nativeFunctionToString = require('../internals/function-to-string');
  11445. var InternalStateModule = require('../internals/internal-state');
  11446. var getInternalState = InternalStateModule.get;
  11447. var enforceInternalState = InternalStateModule.enforce;
  11448. var TEMPLATE = String(nativeFunctionToString).split('toString');
  11449. shared('inspectSource', function (it) {
  11450. return nativeFunctionToString.call(it);
  11451. });
  11452. (module.exports = function (O, key, value, options) {
  11453. var unsafe = options ? !!options.unsafe : false;
  11454. var simple = options ? !!options.enumerable : false;
  11455. var noTargetGet = options ? !!options.noTargetGet : false;
  11456. if (typeof value == 'function') {
  11457. if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
  11458. enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
  11459. }
  11460. if (O === global) {
  11461. if (simple) O[key] = value;
  11462. else setGlobal(key, value);
  11463. return;
  11464. } else if (!unsafe) {
  11465. delete O[key];
  11466. } else if (!noTargetGet && O[key]) {
  11467. simple = true;
  11468. }
  11469. if (simple) O[key] = value;
  11470. else createNonEnumerableProperty(O, key, value);
  11471. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  11472. })(Function.prototype, 'toString', function toString() {
  11473. return typeof this == 'function' && getInternalState(this).source || nativeFunctionToString.call(this);
  11474. });
  11475. },{"../internals/create-non-enumerable-property":76,"../internals/function-to-string":89,"../internals/global":92,"../internals/has":93,"../internals/internal-state":100,"../internals/set-global":143,"../internals/shared":148}],139:[function(require,module,exports){
  11476. var classof = require('./classof-raw');
  11477. var regexpExec = require('./regexp-exec');
  11478. // `RegExpExec` abstract operation
  11479. // https://tc39.github.io/ecma262/#sec-regexpexec
  11480. module.exports = function (R, S) {
  11481. var exec = R.exec;
  11482. if (typeof exec === 'function') {
  11483. var result = exec.call(R, S);
  11484. if (typeof result !== 'object') {
  11485. throw TypeError('RegExp exec method returned something other than an Object or null');
  11486. }
  11487. return result;
  11488. }
  11489. if (classof(R) !== 'RegExp') {
  11490. throw TypeError('RegExp#exec called on incompatible receiver');
  11491. }
  11492. return regexpExec.call(R, S);
  11493. };
  11494. },{"./classof-raw":70,"./regexp-exec":140}],140:[function(require,module,exports){
  11495. 'use strict';
  11496. var regexpFlags = require('./regexp-flags');
  11497. var nativeExec = RegExp.prototype.exec;
  11498. // This always refers to the native implementation, because the
  11499. // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
  11500. // which loads this file before patching the method.
  11501. var nativeReplace = String.prototype.replace;
  11502. var patchedExec = nativeExec;
  11503. var UPDATES_LAST_INDEX_WRONG = (function () {
  11504. var re1 = /a/;
  11505. var re2 = /b*/g;
  11506. nativeExec.call(re1, 'a');
  11507. nativeExec.call(re2, 'a');
  11508. return re1.lastIndex !== 0 || re2.lastIndex !== 0;
  11509. })();
  11510. // nonparticipating capturing group, copied from es5-shim's String#split patch.
  11511. var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
  11512. var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
  11513. if (PATCH) {
  11514. patchedExec = function exec(str) {
  11515. var re = this;
  11516. var lastIndex, reCopy, match, i;
  11517. if (NPCG_INCLUDED) {
  11518. reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
  11519. }
  11520. if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
  11521. match = nativeExec.call(re, str);
  11522. if (UPDATES_LAST_INDEX_WRONG && match) {
  11523. re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
  11524. }
  11525. if (NPCG_INCLUDED && match && match.length > 1) {
  11526. // Fix browsers whose `exec` methods don't consistently return `undefined`
  11527. // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
  11528. nativeReplace.call(match[0], reCopy, function () {
  11529. for (i = 1; i < arguments.length - 2; i++) {
  11530. if (arguments[i] === undefined) match[i] = undefined;
  11531. }
  11532. });
  11533. }
  11534. return match;
  11535. };
  11536. }
  11537. module.exports = patchedExec;
  11538. },{"./regexp-flags":141}],141:[function(require,module,exports){
  11539. 'use strict';
  11540. var anObject = require('../internals/an-object');
  11541. // `RegExp.prototype.flags` getter implementation
  11542. // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
  11543. module.exports = function () {
  11544. var that = anObject(this);
  11545. var result = '';
  11546. if (that.global) result += 'g';
  11547. if (that.ignoreCase) result += 'i';
  11548. if (that.multiline) result += 'm';
  11549. if (that.dotAll) result += 's';
  11550. if (that.unicode) result += 'u';
  11551. if (that.sticky) result += 'y';
  11552. return result;
  11553. };
  11554. },{"../internals/an-object":55}],142:[function(require,module,exports){
  11555. // `RequireObjectCoercible` abstract operation
  11556. // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
  11557. module.exports = function (it) {
  11558. if (it == undefined) throw TypeError("Can't call method on " + it);
  11559. return it;
  11560. };
  11561. },{}],143:[function(require,module,exports){
  11562. var global = require('../internals/global');
  11563. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  11564. module.exports = function (key, value) {
  11565. try {
  11566. createNonEnumerableProperty(global, key, value);
  11567. } catch (error) {
  11568. global[key] = value;
  11569. } return value;
  11570. };
  11571. },{"../internals/create-non-enumerable-property":76,"../internals/global":92}],144:[function(require,module,exports){
  11572. 'use strict';
  11573. var getBuiltIn = require('../internals/get-built-in');
  11574. var definePropertyModule = require('../internals/object-define-property');
  11575. var wellKnownSymbol = require('../internals/well-known-symbol');
  11576. var DESCRIPTORS = require('../internals/descriptors');
  11577. var SPECIES = wellKnownSymbol('species');
  11578. module.exports = function (CONSTRUCTOR_NAME) {
  11579. var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
  11580. var defineProperty = definePropertyModule.f;
  11581. if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {
  11582. defineProperty(Constructor, SPECIES, {
  11583. configurable: true,
  11584. get: function () { return this; }
  11585. });
  11586. }
  11587. };
  11588. },{"../internals/descriptors":81,"../internals/get-built-in":90,"../internals/object-define-property":120,"../internals/well-known-symbol":169}],145:[function(require,module,exports){
  11589. var defineProperty = require('../internals/object-define-property').f;
  11590. var has = require('../internals/has');
  11591. var wellKnownSymbol = require('../internals/well-known-symbol');
  11592. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  11593. module.exports = function (it, TAG, STATIC) {
  11594. if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
  11595. defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });
  11596. }
  11597. };
  11598. },{"../internals/has":93,"../internals/object-define-property":120,"../internals/well-known-symbol":169}],146:[function(require,module,exports){
  11599. var shared = require('../internals/shared');
  11600. var uid = require('../internals/uid');
  11601. var keys = shared('keys');
  11602. module.exports = function (key) {
  11603. return keys[key] || (keys[key] = uid(key));
  11604. };
  11605. },{"../internals/shared":148,"../internals/uid":166}],147:[function(require,module,exports){
  11606. var global = require('../internals/global');
  11607. var setGlobal = require('../internals/set-global');
  11608. var SHARED = '__core-js_shared__';
  11609. var store = global[SHARED] || setGlobal(SHARED, {});
  11610. module.exports = store;
  11611. },{"../internals/global":92,"../internals/set-global":143}],148:[function(require,module,exports){
  11612. var IS_PURE = require('../internals/is-pure');
  11613. var store = require('../internals/shared-store');
  11614. (module.exports = function (key, value) {
  11615. return store[key] || (store[key] = value !== undefined ? value : {});
  11616. })('versions', []).push({
  11617. version: '3.4.1',
  11618. mode: IS_PURE ? 'pure' : 'global',
  11619. copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
  11620. });
  11621. },{"../internals/is-pure":106,"../internals/shared-store":147}],149:[function(require,module,exports){
  11622. 'use strict';
  11623. var fails = require('../internals/fails');
  11624. module.exports = function (METHOD_NAME, argument) {
  11625. var method = [][METHOD_NAME];
  11626. return !method || !fails(function () {
  11627. // eslint-disable-next-line no-useless-call,no-throw-literal
  11628. method.call(null, argument || function () { throw 1; }, 1);
  11629. });
  11630. };
  11631. },{"../internals/fails":86}],150:[function(require,module,exports){
  11632. var anObject = require('../internals/an-object');
  11633. var aFunction = require('../internals/a-function');
  11634. var wellKnownSymbol = require('../internals/well-known-symbol');
  11635. var SPECIES = wellKnownSymbol('species');
  11636. // `SpeciesConstructor` abstract operation
  11637. // https://tc39.github.io/ecma262/#sec-speciesconstructor
  11638. module.exports = function (O, defaultConstructor) {
  11639. var C = anObject(O).constructor;
  11640. var S;
  11641. return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);
  11642. };
  11643. },{"../internals/a-function":50,"../internals/an-object":55,"../internals/well-known-symbol":169}],151:[function(require,module,exports){
  11644. var toInteger = require('../internals/to-integer');
  11645. var requireObjectCoercible = require('../internals/require-object-coercible');
  11646. // `String.prototype.{ codePointAt, at }` methods implementation
  11647. var createMethod = function (CONVERT_TO_STRING) {
  11648. return function ($this, pos) {
  11649. var S = String(requireObjectCoercible($this));
  11650. var position = toInteger(pos);
  11651. var size = S.length;
  11652. var first, second;
  11653. if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
  11654. first = S.charCodeAt(position);
  11655. return first < 0xD800 || first > 0xDBFF || position + 1 === size
  11656. || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
  11657. ? CONVERT_TO_STRING ? S.charAt(position) : first
  11658. : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
  11659. };
  11660. };
  11661. module.exports = {
  11662. // `String.prototype.codePointAt` method
  11663. // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
  11664. codeAt: createMethod(false),
  11665. // `String.prototype.at` method
  11666. // https://github.com/mathiasbynens/String.prototype.at
  11667. charAt: createMethod(true)
  11668. };
  11669. },{"../internals/require-object-coercible":142,"../internals/to-integer":157}],152:[function(require,module,exports){
  11670. var requireObjectCoercible = require('../internals/require-object-coercible');
  11671. var whitespaces = require('../internals/whitespaces');
  11672. var whitespace = '[' + whitespaces + ']';
  11673. var ltrim = RegExp('^' + whitespace + whitespace + '*');
  11674. var rtrim = RegExp(whitespace + whitespace + '*$');
  11675. // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
  11676. var createMethod = function (TYPE) {
  11677. return function ($this) {
  11678. var string = String(requireObjectCoercible($this));
  11679. if (TYPE & 1) string = string.replace(ltrim, '');
  11680. if (TYPE & 2) string = string.replace(rtrim, '');
  11681. return string;
  11682. };
  11683. };
  11684. module.exports = {
  11685. // `String.prototype.{ trimLeft, trimStart }` methods
  11686. // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
  11687. start: createMethod(1),
  11688. // `String.prototype.{ trimRight, trimEnd }` methods
  11689. // https://tc39.github.io/ecma262/#sec-string.prototype.trimend
  11690. end: createMethod(2),
  11691. // `String.prototype.trim` method
  11692. // https://tc39.github.io/ecma262/#sec-string.prototype.trim
  11693. trim: createMethod(3)
  11694. };
  11695. },{"../internals/require-object-coercible":142,"../internals/whitespaces":170}],153:[function(require,module,exports){
  11696. var global = require('../internals/global');
  11697. var fails = require('../internals/fails');
  11698. var classof = require('../internals/classof-raw');
  11699. var bind = require('../internals/bind-context');
  11700. var html = require('../internals/html');
  11701. var createElement = require('../internals/document-create-element');
  11702. var IS_IOS = require('../internals/is-ios');
  11703. var location = global.location;
  11704. var set = global.setImmediate;
  11705. var clear = global.clearImmediate;
  11706. var process = global.process;
  11707. var MessageChannel = global.MessageChannel;
  11708. var Dispatch = global.Dispatch;
  11709. var counter = 0;
  11710. var queue = {};
  11711. var ONREADYSTATECHANGE = 'onreadystatechange';
  11712. var defer, channel, port;
  11713. var run = function (id) {
  11714. // eslint-disable-next-line no-prototype-builtins
  11715. if (queue.hasOwnProperty(id)) {
  11716. var fn = queue[id];
  11717. delete queue[id];
  11718. fn();
  11719. }
  11720. };
  11721. var runner = function (id) {
  11722. return function () {
  11723. run(id);
  11724. };
  11725. };
  11726. var listener = function (event) {
  11727. run(event.data);
  11728. };
  11729. var post = function (id) {
  11730. // old engines have not location.origin
  11731. global.postMessage(id + '', location.protocol + '//' + location.host);
  11732. };
  11733. // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
  11734. if (!set || !clear) {
  11735. set = function setImmediate(fn) {
  11736. var args = [];
  11737. var i = 1;
  11738. while (arguments.length > i) args.push(arguments[i++]);
  11739. queue[++counter] = function () {
  11740. // eslint-disable-next-line no-new-func
  11741. (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
  11742. };
  11743. defer(counter);
  11744. return counter;
  11745. };
  11746. clear = function clearImmediate(id) {
  11747. delete queue[id];
  11748. };
  11749. // Node.js 0.8-
  11750. if (classof(process) == 'process') {
  11751. defer = function (id) {
  11752. process.nextTick(runner(id));
  11753. };
  11754. // Sphere (JS game engine) Dispatch API
  11755. } else if (Dispatch && Dispatch.now) {
  11756. defer = function (id) {
  11757. Dispatch.now(runner(id));
  11758. };
  11759. // Browsers with MessageChannel, includes WebWorkers
  11760. // except iOS - https://github.com/zloirock/core-js/issues/624
  11761. } else if (MessageChannel && !IS_IOS) {
  11762. channel = new MessageChannel();
  11763. port = channel.port2;
  11764. channel.port1.onmessage = listener;
  11765. defer = bind(port.postMessage, port, 1);
  11766. // Browsers with postMessage, skip WebWorkers
  11767. // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  11768. } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post)) {
  11769. defer = post;
  11770. global.addEventListener('message', listener, false);
  11771. // IE8-
  11772. } else if (ONREADYSTATECHANGE in createElement('script')) {
  11773. defer = function (id) {
  11774. html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
  11775. html.removeChild(this);
  11776. run(id);
  11777. };
  11778. };
  11779. // Rest old browsers
  11780. } else {
  11781. defer = function (id) {
  11782. setTimeout(runner(id), 0);
  11783. };
  11784. }
  11785. }
  11786. module.exports = {
  11787. set: set,
  11788. clear: clear
  11789. };
  11790. },{"../internals/bind-context":67,"../internals/classof-raw":70,"../internals/document-create-element":82,"../internals/fails":86,"../internals/global":92,"../internals/html":96,"../internals/is-ios":104}],154:[function(require,module,exports){
  11791. var toInteger = require('../internals/to-integer');
  11792. var max = Math.max;
  11793. var min = Math.min;
  11794. // Helper for a popular repeating case of the spec:
  11795. // Let integer be ? ToInteger(index).
  11796. // If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
  11797. module.exports = function (index, length) {
  11798. var integer = toInteger(index);
  11799. return integer < 0 ? max(integer + length, 0) : min(integer, length);
  11800. };
  11801. },{"../internals/to-integer":157}],155:[function(require,module,exports){
  11802. var toInteger = require('../internals/to-integer');
  11803. var toLength = require('../internals/to-length');
  11804. // `ToIndex` abstract operation
  11805. // https://tc39.github.io/ecma262/#sec-toindex
  11806. module.exports = function (it) {
  11807. if (it === undefined) return 0;
  11808. var number = toInteger(it);
  11809. var length = toLength(number);
  11810. if (number !== length) throw RangeError('Wrong length or index');
  11811. return length;
  11812. };
  11813. },{"../internals/to-integer":157,"../internals/to-length":158}],156:[function(require,module,exports){
  11814. // toObject with fallback for non-array-like ES3 strings
  11815. var IndexedObject = require('../internals/indexed-object');
  11816. var requireObjectCoercible = require('../internals/require-object-coercible');
  11817. module.exports = function (it) {
  11818. return IndexedObject(requireObjectCoercible(it));
  11819. };
  11820. },{"../internals/indexed-object":98,"../internals/require-object-coercible":142}],157:[function(require,module,exports){
  11821. var ceil = Math.ceil;
  11822. var floor = Math.floor;
  11823. // `ToInteger` abstract operation
  11824. // https://tc39.github.io/ecma262/#sec-tointeger
  11825. module.exports = function (argument) {
  11826. return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
  11827. };
  11828. },{}],158:[function(require,module,exports){
  11829. var toInteger = require('../internals/to-integer');
  11830. var min = Math.min;
  11831. // `ToLength` abstract operation
  11832. // https://tc39.github.io/ecma262/#sec-tolength
  11833. module.exports = function (argument) {
  11834. return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
  11835. };
  11836. },{"../internals/to-integer":157}],159:[function(require,module,exports){
  11837. var requireObjectCoercible = require('../internals/require-object-coercible');
  11838. // `ToObject` abstract operation
  11839. // https://tc39.github.io/ecma262/#sec-toobject
  11840. module.exports = function (argument) {
  11841. return Object(requireObjectCoercible(argument));
  11842. };
  11843. },{"../internals/require-object-coercible":142}],160:[function(require,module,exports){
  11844. var toPositiveInteger = require('../internals/to-positive-integer');
  11845. module.exports = function (it, BYTES) {
  11846. var offset = toPositiveInteger(it);
  11847. if (offset % BYTES) throw RangeError('Wrong offset');
  11848. return offset;
  11849. };
  11850. },{"../internals/to-positive-integer":161}],161:[function(require,module,exports){
  11851. var toInteger = require('../internals/to-integer');
  11852. module.exports = function (it) {
  11853. var result = toInteger(it);
  11854. if (result < 0) throw RangeError("The argument can't be less than 0");
  11855. return result;
  11856. };
  11857. },{"../internals/to-integer":157}],162:[function(require,module,exports){
  11858. var isObject = require('../internals/is-object');
  11859. // `ToPrimitive` abstract operation
  11860. // https://tc39.github.io/ecma262/#sec-toprimitive
  11861. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  11862. // and the second argument - flag - preferred type is a string
  11863. module.exports = function (input, PREFERRED_STRING) {
  11864. if (!isObject(input)) return input;
  11865. var fn, val;
  11866. if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  11867. if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
  11868. if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  11869. throw TypeError("Can't convert object to primitive value");
  11870. };
  11871. },{"../internals/is-object":105}],163:[function(require,module,exports){
  11872. 'use strict';
  11873. var $ = require('../internals/export');
  11874. var global = require('../internals/global');
  11875. var DESCRIPTORS = require('../internals/descriptors');
  11876. var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-arrays-constructors-requires-wrappers');
  11877. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  11878. var ArrayBufferModule = require('../internals/array-buffer');
  11879. var anInstance = require('../internals/an-instance');
  11880. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  11881. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  11882. var toLength = require('../internals/to-length');
  11883. var toIndex = require('../internals/to-index');
  11884. var toOffset = require('../internals/to-offset');
  11885. var toPrimitive = require('../internals/to-primitive');
  11886. var has = require('../internals/has');
  11887. var classof = require('../internals/classof');
  11888. var isObject = require('../internals/is-object');
  11889. var create = require('../internals/object-create');
  11890. var setPrototypeOf = require('../internals/object-set-prototype-of');
  11891. var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
  11892. var typedArrayFrom = require('../internals/typed-array-from');
  11893. var forEach = require('../internals/array-iteration').forEach;
  11894. var setSpecies = require('../internals/set-species');
  11895. var definePropertyModule = require('../internals/object-define-property');
  11896. var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
  11897. var InternalStateModule = require('../internals/internal-state');
  11898. var inheritIfRequired = require('../internals/inherit-if-required');
  11899. var getInternalState = InternalStateModule.get;
  11900. var setInternalState = InternalStateModule.set;
  11901. var nativeDefineProperty = definePropertyModule.f;
  11902. var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  11903. var round = Math.round;
  11904. var RangeError = global.RangeError;
  11905. var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
  11906. var DataView = ArrayBufferModule.DataView;
  11907. var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;
  11908. var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG;
  11909. var TypedArray = ArrayBufferViewCore.TypedArray;
  11910. var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype;
  11911. var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
  11912. var isTypedArray = ArrayBufferViewCore.isTypedArray;
  11913. var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
  11914. var WRONG_LENGTH = 'Wrong length';
  11915. var fromList = function (C, list) {
  11916. var index = 0;
  11917. var length = list.length;
  11918. var result = new (aTypedArrayConstructor(C))(length);
  11919. while (length > index) result[index] = list[index++];
  11920. return result;
  11921. };
  11922. var addGetter = function (it, key) {
  11923. nativeDefineProperty(it, key, { get: function () {
  11924. return getInternalState(this)[key];
  11925. } });
  11926. };
  11927. var isArrayBuffer = function (it) {
  11928. var klass;
  11929. return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';
  11930. };
  11931. var isTypedArrayIndex = function (target, key) {
  11932. return isTypedArray(target)
  11933. && typeof key != 'symbol'
  11934. && key in target
  11935. && String(+key) == String(key);
  11936. };
  11937. var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {
  11938. return isTypedArrayIndex(target, key = toPrimitive(key, true))
  11939. ? createPropertyDescriptor(2, target[key])
  11940. : nativeGetOwnPropertyDescriptor(target, key);
  11941. };
  11942. var wrappedDefineProperty = function defineProperty(target, key, descriptor) {
  11943. if (isTypedArrayIndex(target, key = toPrimitive(key, true))
  11944. && isObject(descriptor)
  11945. && has(descriptor, 'value')
  11946. && !has(descriptor, 'get')
  11947. && !has(descriptor, 'set')
  11948. // TODO: add validation descriptor w/o calling accessors
  11949. && !descriptor.configurable
  11950. && (!has(descriptor, 'writable') || descriptor.writable)
  11951. && (!has(descriptor, 'enumerable') || descriptor.enumerable)
  11952. ) {
  11953. target[key] = descriptor.value;
  11954. return target;
  11955. } return nativeDefineProperty(target, key, descriptor);
  11956. };
  11957. if (DESCRIPTORS) {
  11958. if (!NATIVE_ARRAY_BUFFER_VIEWS) {
  11959. getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;
  11960. definePropertyModule.f = wrappedDefineProperty;
  11961. addGetter(TypedArrayPrototype, 'buffer');
  11962. addGetter(TypedArrayPrototype, 'byteOffset');
  11963. addGetter(TypedArrayPrototype, 'byteLength');
  11964. addGetter(TypedArrayPrototype, 'length');
  11965. }
  11966. $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {
  11967. getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,
  11968. defineProperty: wrappedDefineProperty
  11969. });
  11970. module.exports = function (TYPE, BYTES, wrapper, CLAMPED) {
  11971. var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';
  11972. var GETTER = 'get' + TYPE;
  11973. var SETTER = 'set' + TYPE;
  11974. var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME];
  11975. var TypedArrayConstructor = NativeTypedArrayConstructor;
  11976. var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;
  11977. var exported = {};
  11978. var getter = function (that, index) {
  11979. var data = getInternalState(that);
  11980. return data.view[GETTER](index * BYTES + data.byteOffset, true);
  11981. };
  11982. var setter = function (that, index, value) {
  11983. var data = getInternalState(that);
  11984. if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;
  11985. data.view[SETTER](index * BYTES + data.byteOffset, value, true);
  11986. };
  11987. var addElement = function (that, index) {
  11988. nativeDefineProperty(that, index, {
  11989. get: function () {
  11990. return getter(this, index);
  11991. },
  11992. set: function (value) {
  11993. return setter(this, index, value);
  11994. },
  11995. enumerable: true
  11996. });
  11997. };
  11998. if (!NATIVE_ARRAY_BUFFER_VIEWS) {
  11999. TypedArrayConstructor = wrapper(function (that, data, offset, $length) {
  12000. anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME);
  12001. var index = 0;
  12002. var byteOffset = 0;
  12003. var buffer, byteLength, length;
  12004. if (!isObject(data)) {
  12005. length = toIndex(data);
  12006. byteLength = length * BYTES;
  12007. buffer = new ArrayBuffer(byteLength);
  12008. } else if (isArrayBuffer(data)) {
  12009. buffer = data;
  12010. byteOffset = toOffset(offset, BYTES);
  12011. var $len = data.byteLength;
  12012. if ($length === undefined) {
  12013. if ($len % BYTES) throw RangeError(WRONG_LENGTH);
  12014. byteLength = $len - byteOffset;
  12015. if (byteLength < 0) throw RangeError(WRONG_LENGTH);
  12016. } else {
  12017. byteLength = toLength($length) * BYTES;
  12018. if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);
  12019. }
  12020. length = byteLength / BYTES;
  12021. } else if (isTypedArray(data)) {
  12022. return fromList(TypedArrayConstructor, data);
  12023. } else {
  12024. return typedArrayFrom.call(TypedArrayConstructor, data);
  12025. }
  12026. setInternalState(that, {
  12027. buffer: buffer,
  12028. byteOffset: byteOffset,
  12029. byteLength: byteLength,
  12030. length: length,
  12031. view: new DataView(buffer)
  12032. });
  12033. while (index < length) addElement(that, index++);
  12034. });
  12035. if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
  12036. TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype);
  12037. } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {
  12038. TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {
  12039. anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME);
  12040. return inheritIfRequired(function () {
  12041. if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data));
  12042. if (isArrayBuffer(data)) return $length !== undefined
  12043. ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length)
  12044. : typedArrayOffset !== undefined
  12045. ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES))
  12046. : new NativeTypedArrayConstructor(data);
  12047. if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);
  12048. return typedArrayFrom.call(TypedArrayConstructor, data);
  12049. }(), dummy, TypedArrayConstructor);
  12050. });
  12051. if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
  12052. forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {
  12053. if (!(key in TypedArrayConstructor)) {
  12054. createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);
  12055. }
  12056. });
  12057. TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;
  12058. }
  12059. if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {
  12060. createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);
  12061. }
  12062. if (TYPED_ARRAY_TAG) {
  12063. createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);
  12064. }
  12065. exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;
  12066. $({
  12067. global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS
  12068. }, exported);
  12069. if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {
  12070. createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);
  12071. }
  12072. if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {
  12073. createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);
  12074. }
  12075. setSpecies(CONSTRUCTOR_NAME);
  12076. };
  12077. } else module.exports = function () { /* empty */ };
  12078. },{"../internals/an-instance":54,"../internals/array-buffer":57,"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/classof":71,"../internals/create-non-enumerable-property":76,"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/export":85,"../internals/global":92,"../internals/has":93,"../internals/inherit-if-required":99,"../internals/internal-state":100,"../internals/is-object":105,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/object-set-prototype-of":129,"../internals/set-species":144,"../internals/to-index":155,"../internals/to-length":158,"../internals/to-offset":160,"../internals/to-primitive":162,"../internals/typed-array-from":164,"../internals/typed-arrays-constructors-requires-wrappers":165}],164:[function(require,module,exports){
  12079. var toObject = require('../internals/to-object');
  12080. var toLength = require('../internals/to-length');
  12081. var getIteratorMethod = require('../internals/get-iterator-method');
  12082. var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
  12083. var bind = require('../internals/bind-context');
  12084. var aTypedArrayConstructor = require('../internals/array-buffer-view-core').aTypedArrayConstructor;
  12085. module.exports = function from(source /* , mapfn, thisArg */) {
  12086. var O = toObject(source);
  12087. var argumentsLength = arguments.length;
  12088. var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
  12089. var mapping = mapfn !== undefined;
  12090. var iteratorMethod = getIteratorMethod(O);
  12091. var i, length, result, step, iterator, next;
  12092. if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) {
  12093. iterator = iteratorMethod.call(O);
  12094. next = iterator.next;
  12095. O = [];
  12096. while (!(step = next.call(iterator)).done) {
  12097. O.push(step.value);
  12098. }
  12099. }
  12100. if (mapping && argumentsLength > 2) {
  12101. mapfn = bind(mapfn, arguments[2], 2);
  12102. }
  12103. length = toLength(O.length);
  12104. result = new (aTypedArrayConstructor(this))(length);
  12105. for (i = 0; length > i; i++) {
  12106. result[i] = mapping ? mapfn(O[i], i) : O[i];
  12107. }
  12108. return result;
  12109. };
  12110. },{"../internals/array-buffer-view-core":56,"../internals/bind-context":67,"../internals/get-iterator-method":91,"../internals/is-array-iterator-method":101,"../internals/to-length":158,"../internals/to-object":159}],165:[function(require,module,exports){
  12111. /* eslint-disable no-new */
  12112. var global = require('../internals/global');
  12113. var fails = require('../internals/fails');
  12114. var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');
  12115. var NATIVE_ARRAY_BUFFER_VIEWS = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS;
  12116. var ArrayBuffer = global.ArrayBuffer;
  12117. var Int8Array = global.Int8Array;
  12118. module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {
  12119. Int8Array(1);
  12120. }) || !fails(function () {
  12121. new Int8Array(-1);
  12122. }) || !checkCorrectnessOfIteration(function (iterable) {
  12123. new Int8Array();
  12124. new Int8Array(null);
  12125. new Int8Array(1.5);
  12126. new Int8Array(iterable);
  12127. }, true) || fails(function () {
  12128. // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill
  12129. return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1;
  12130. });
  12131. },{"../internals/array-buffer-view-core":56,"../internals/check-correctness-of-iteration":69,"../internals/fails":86,"../internals/global":92}],166:[function(require,module,exports){
  12132. var id = 0;
  12133. var postfix = Math.random();
  12134. module.exports = function (key) {
  12135. return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
  12136. };
  12137. },{}],167:[function(require,module,exports){
  12138. var getBuiltIn = require('../internals/get-built-in');
  12139. module.exports = getBuiltIn('navigator', 'userAgent') || '';
  12140. },{"../internals/get-built-in":90}],168:[function(require,module,exports){
  12141. var global = require('../internals/global');
  12142. var userAgent = require('../internals/user-agent');
  12143. var process = global.process;
  12144. var versions = process && process.versions;
  12145. var v8 = versions && versions.v8;
  12146. var match, version;
  12147. if (v8) {
  12148. match = v8.split('.');
  12149. version = match[0] + match[1];
  12150. } else if (userAgent) {
  12151. match = userAgent.match(/Edge\/(\d+)/);
  12152. if (!match || match[1] >= 74) {
  12153. match = userAgent.match(/Chrome\/(\d+)/);
  12154. if (match) version = match[1];
  12155. }
  12156. }
  12157. module.exports = version && +version;
  12158. },{"../internals/global":92,"../internals/user-agent":167}],169:[function(require,module,exports){
  12159. var global = require('../internals/global');
  12160. var shared = require('../internals/shared');
  12161. var uid = require('../internals/uid');
  12162. var NATIVE_SYMBOL = require('../internals/native-symbol');
  12163. var Symbol = global.Symbol;
  12164. var store = shared('wks');
  12165. module.exports = function (name) {
  12166. return store[name] || (store[name] = NATIVE_SYMBOL && Symbol[name]
  12167. || (NATIVE_SYMBOL ? Symbol : uid)('Symbol.' + name));
  12168. };
  12169. },{"../internals/global":92,"../internals/native-symbol":113,"../internals/shared":148,"../internals/uid":166}],170:[function(require,module,exports){
  12170. // a string of all valid unicode whitespaces
  12171. // eslint-disable-next-line max-len
  12172. module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
  12173. },{}],171:[function(require,module,exports){
  12174. exports.f = require('../internals/well-known-symbol');
  12175. },{"../internals/well-known-symbol":169}],172:[function(require,module,exports){
  12176. 'use strict';
  12177. var $ = require('../internals/export');
  12178. var fails = require('../internals/fails');
  12179. var ArrayBufferModule = require('../internals/array-buffer');
  12180. var anObject = require('../internals/an-object');
  12181. var toAbsoluteIndex = require('../internals/to-absolute-index');
  12182. var toLength = require('../internals/to-length');
  12183. var speciesConstructor = require('../internals/species-constructor');
  12184. var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
  12185. var DataView = ArrayBufferModule.DataView;
  12186. var nativeArrayBufferSlice = ArrayBuffer.prototype.slice;
  12187. var INCORRECT_SLICE = fails(function () {
  12188. return !new ArrayBuffer(2).slice(1, undefined).byteLength;
  12189. });
  12190. // `ArrayBuffer.prototype.slice` method
  12191. // https://tc39.github.io/ecma262/#sec-arraybuffer.prototype.slice
  12192. $({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, {
  12193. slice: function slice(start, end) {
  12194. if (nativeArrayBufferSlice !== undefined && end === undefined) {
  12195. return nativeArrayBufferSlice.call(anObject(this), start); // FF fix
  12196. }
  12197. var length = anObject(this).byteLength;
  12198. var first = toAbsoluteIndex(start, length);
  12199. var fin = toAbsoluteIndex(end === undefined ? length : end, length);
  12200. var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first));
  12201. var viewSource = new DataView(this);
  12202. var viewTarget = new DataView(result);
  12203. var index = 0;
  12204. while (first < fin) {
  12205. viewTarget.setUint8(index++, viewSource.getUint8(first++));
  12206. } return result;
  12207. }
  12208. });
  12209. },{"../internals/an-object":55,"../internals/array-buffer":57,"../internals/export":85,"../internals/fails":86,"../internals/species-constructor":150,"../internals/to-absolute-index":154,"../internals/to-length":158}],173:[function(require,module,exports){
  12210. 'use strict';
  12211. var $ = require('../internals/export');
  12212. var fails = require('../internals/fails');
  12213. var isArray = require('../internals/is-array');
  12214. var isObject = require('../internals/is-object');
  12215. var toObject = require('../internals/to-object');
  12216. var toLength = require('../internals/to-length');
  12217. var createProperty = require('../internals/create-property');
  12218. var arraySpeciesCreate = require('../internals/array-species-create');
  12219. var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
  12220. var wellKnownSymbol = require('../internals/well-known-symbol');
  12221. var V8_VERSION = require('../internals/v8-version');
  12222. var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
  12223. var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
  12224. var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
  12225. // We can't use this feature detection in V8 since it causes
  12226. // deoptimization and serious performance degradation
  12227. // https://github.com/zloirock/core-js/issues/679
  12228. var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
  12229. var array = [];
  12230. array[IS_CONCAT_SPREADABLE] = false;
  12231. return array.concat()[0] !== array;
  12232. });
  12233. var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
  12234. var isConcatSpreadable = function (O) {
  12235. if (!isObject(O)) return false;
  12236. var spreadable = O[IS_CONCAT_SPREADABLE];
  12237. return spreadable !== undefined ? !!spreadable : isArray(O);
  12238. };
  12239. var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
  12240. // `Array.prototype.concat` method
  12241. // https://tc39.github.io/ecma262/#sec-array.prototype.concat
  12242. // with adding support of @@isConcatSpreadable and @@species
  12243. $({ target: 'Array', proto: true, forced: FORCED }, {
  12244. concat: function concat(arg) { // eslint-disable-line no-unused-vars
  12245. var O = toObject(this);
  12246. var A = arraySpeciesCreate(O, 0);
  12247. var n = 0;
  12248. var i, k, length, len, E;
  12249. for (i = -1, length = arguments.length; i < length; i++) {
  12250. E = i === -1 ? O : arguments[i];
  12251. if (isConcatSpreadable(E)) {
  12252. len = toLength(E.length);
  12253. if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
  12254. for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
  12255. } else {
  12256. if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
  12257. createProperty(A, n++, E);
  12258. }
  12259. }
  12260. A.length = n;
  12261. return A;
  12262. }
  12263. });
  12264. },{"../internals/array-method-has-species-support":64,"../internals/array-species-create":66,"../internals/create-property":78,"../internals/export":85,"../internals/fails":86,"../internals/is-array":102,"../internals/is-object":105,"../internals/to-length":158,"../internals/to-object":159,"../internals/v8-version":168,"../internals/well-known-symbol":169}],174:[function(require,module,exports){
  12265. var $ = require('../internals/export');
  12266. var fill = require('../internals/array-fill');
  12267. var addToUnscopables = require('../internals/add-to-unscopables');
  12268. // `Array.prototype.fill` method
  12269. // https://tc39.github.io/ecma262/#sec-array.prototype.fill
  12270. $({ target: 'Array', proto: true }, {
  12271. fill: fill
  12272. });
  12273. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  12274. addToUnscopables('fill');
  12275. },{"../internals/add-to-unscopables":52,"../internals/array-fill":59,"../internals/export":85}],175:[function(require,module,exports){
  12276. 'use strict';
  12277. var $ = require('../internals/export');
  12278. var $filter = require('../internals/array-iteration').filter;
  12279. var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
  12280. // `Array.prototype.filter` method
  12281. // https://tc39.github.io/ecma262/#sec-array.prototype.filter
  12282. // with adding support of @@species
  12283. $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, {
  12284. filter: function filter(callbackfn /* , thisArg */) {
  12285. return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  12286. }
  12287. });
  12288. },{"../internals/array-iteration":62,"../internals/array-method-has-species-support":64,"../internals/export":85}],176:[function(require,module,exports){
  12289. 'use strict';
  12290. var $ = require('../internals/export');
  12291. var $findIndex = require('../internals/array-iteration').findIndex;
  12292. var addToUnscopables = require('../internals/add-to-unscopables');
  12293. var FIND_INDEX = 'findIndex';
  12294. var SKIPS_HOLES = true;
  12295. // Shouldn't skip holes
  12296. if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; });
  12297. // `Array.prototype.findIndex` method
  12298. // https://tc39.github.io/ecma262/#sec-array.prototype.findindex
  12299. $({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
  12300. findIndex: function findIndex(callbackfn /* , that = undefined */) {
  12301. return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  12302. }
  12303. });
  12304. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  12305. addToUnscopables(FIND_INDEX);
  12306. },{"../internals/add-to-unscopables":52,"../internals/array-iteration":62,"../internals/export":85}],177:[function(require,module,exports){
  12307. 'use strict';
  12308. var $ = require('../internals/export');
  12309. var $find = require('../internals/array-iteration').find;
  12310. var addToUnscopables = require('../internals/add-to-unscopables');
  12311. var FIND = 'find';
  12312. var SKIPS_HOLES = true;
  12313. // Shouldn't skip holes
  12314. if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
  12315. // `Array.prototype.find` method
  12316. // https://tc39.github.io/ecma262/#sec-array.prototype.find
  12317. $({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
  12318. find: function find(callbackfn /* , that = undefined */) {
  12319. return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  12320. }
  12321. });
  12322. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  12323. addToUnscopables(FIND);
  12324. },{"../internals/add-to-unscopables":52,"../internals/array-iteration":62,"../internals/export":85}],178:[function(require,module,exports){
  12325. 'use strict';
  12326. var $ = require('../internals/export');
  12327. var forEach = require('../internals/array-for-each');
  12328. // `Array.prototype.forEach` method
  12329. // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
  12330. $({ target: 'Array', proto: true, forced: [].forEach != forEach }, {
  12331. forEach: forEach
  12332. });
  12333. },{"../internals/array-for-each":60,"../internals/export":85}],179:[function(require,module,exports){
  12334. 'use strict';
  12335. var $ = require('../internals/export');
  12336. var $includes = require('../internals/array-includes').includes;
  12337. var addToUnscopables = require('../internals/add-to-unscopables');
  12338. // `Array.prototype.includes` method
  12339. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  12340. $({ target: 'Array', proto: true }, {
  12341. includes: function includes(el /* , fromIndex = 0 */) {
  12342. return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
  12343. }
  12344. });
  12345. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  12346. addToUnscopables('includes');
  12347. },{"../internals/add-to-unscopables":52,"../internals/array-includes":61,"../internals/export":85}],180:[function(require,module,exports){
  12348. 'use strict';
  12349. var $ = require('../internals/export');
  12350. var $indexOf = require('../internals/array-includes').indexOf;
  12351. var sloppyArrayMethod = require('../internals/sloppy-array-method');
  12352. var nativeIndexOf = [].indexOf;
  12353. var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
  12354. var SLOPPY_METHOD = sloppyArrayMethod('indexOf');
  12355. // `Array.prototype.indexOf` method
  12356. // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
  12357. $({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || SLOPPY_METHOD }, {
  12358. indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
  12359. return NEGATIVE_ZERO
  12360. // convert -0 to +0
  12361. ? nativeIndexOf.apply(this, arguments) || 0
  12362. : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
  12363. }
  12364. });
  12365. },{"../internals/array-includes":61,"../internals/export":85,"../internals/sloppy-array-method":149}],181:[function(require,module,exports){
  12366. var $ = require('../internals/export');
  12367. var isArray = require('../internals/is-array');
  12368. // `Array.isArray` method
  12369. // https://tc39.github.io/ecma262/#sec-array.isarray
  12370. $({ target: 'Array', stat: true }, {
  12371. isArray: isArray
  12372. });
  12373. },{"../internals/export":85,"../internals/is-array":102}],182:[function(require,module,exports){
  12374. 'use strict';
  12375. var toIndexedObject = require('../internals/to-indexed-object');
  12376. var addToUnscopables = require('../internals/add-to-unscopables');
  12377. var Iterators = require('../internals/iterators');
  12378. var InternalStateModule = require('../internals/internal-state');
  12379. var defineIterator = require('../internals/define-iterator');
  12380. var ARRAY_ITERATOR = 'Array Iterator';
  12381. var setInternalState = InternalStateModule.set;
  12382. var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
  12383. // `Array.prototype.entries` method
  12384. // https://tc39.github.io/ecma262/#sec-array.prototype.entries
  12385. // `Array.prototype.keys` method
  12386. // https://tc39.github.io/ecma262/#sec-array.prototype.keys
  12387. // `Array.prototype.values` method
  12388. // https://tc39.github.io/ecma262/#sec-array.prototype.values
  12389. // `Array.prototype[@@iterator]` method
  12390. // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
  12391. // `CreateArrayIterator` internal method
  12392. // https://tc39.github.io/ecma262/#sec-createarrayiterator
  12393. module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
  12394. setInternalState(this, {
  12395. type: ARRAY_ITERATOR,
  12396. target: toIndexedObject(iterated), // target
  12397. index: 0, // next index
  12398. kind: kind // kind
  12399. });
  12400. // `%ArrayIteratorPrototype%.next` method
  12401. // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
  12402. }, function () {
  12403. var state = getInternalState(this);
  12404. var target = state.target;
  12405. var kind = state.kind;
  12406. var index = state.index++;
  12407. if (!target || index >= target.length) {
  12408. state.target = undefined;
  12409. return { value: undefined, done: true };
  12410. }
  12411. if (kind == 'keys') return { value: index, done: false };
  12412. if (kind == 'values') return { value: target[index], done: false };
  12413. return { value: [index, target[index]], done: false };
  12414. }, 'values');
  12415. // argumentsList[@@iterator] is %ArrayProto_values%
  12416. // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
  12417. // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
  12418. Iterators.Arguments = Iterators.Array;
  12419. // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
  12420. addToUnscopables('keys');
  12421. addToUnscopables('values');
  12422. addToUnscopables('entries');
  12423. },{"../internals/add-to-unscopables":52,"../internals/define-iterator":79,"../internals/internal-state":100,"../internals/iterators":110,"../internals/to-indexed-object":156}],183:[function(require,module,exports){
  12424. 'use strict';
  12425. var $ = require('../internals/export');
  12426. var IndexedObject = require('../internals/indexed-object');
  12427. var toIndexedObject = require('../internals/to-indexed-object');
  12428. var sloppyArrayMethod = require('../internals/sloppy-array-method');
  12429. var nativeJoin = [].join;
  12430. var ES3_STRINGS = IndexedObject != Object;
  12431. var SLOPPY_METHOD = sloppyArrayMethod('join', ',');
  12432. // `Array.prototype.join` method
  12433. // https://tc39.github.io/ecma262/#sec-array.prototype.join
  12434. $({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD }, {
  12435. join: function join(separator) {
  12436. return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
  12437. }
  12438. });
  12439. },{"../internals/export":85,"../internals/indexed-object":98,"../internals/sloppy-array-method":149,"../internals/to-indexed-object":156}],184:[function(require,module,exports){
  12440. 'use strict';
  12441. var $ = require('../internals/export');
  12442. var $map = require('../internals/array-iteration').map;
  12443. var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
  12444. // `Array.prototype.map` method
  12445. // https://tc39.github.io/ecma262/#sec-array.prototype.map
  12446. // with adding support of @@species
  12447. $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('map') }, {
  12448. map: function map(callbackfn /* , thisArg */) {
  12449. return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  12450. }
  12451. });
  12452. },{"../internals/array-iteration":62,"../internals/array-method-has-species-support":64,"../internals/export":85}],185:[function(require,module,exports){
  12453. 'use strict';
  12454. var $ = require('../internals/export');
  12455. var isArray = require('../internals/is-array');
  12456. var nativeReverse = [].reverse;
  12457. var test = [1, 2];
  12458. // `Array.prototype.reverse` method
  12459. // https://tc39.github.io/ecma262/#sec-array.prototype.reverse
  12460. // fix for Safari 12.0 bug
  12461. // https://bugs.webkit.org/show_bug.cgi?id=188794
  12462. $({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, {
  12463. reverse: function reverse() {
  12464. // eslint-disable-next-line no-self-assign
  12465. if (isArray(this)) this.length = this.length;
  12466. return nativeReverse.call(this);
  12467. }
  12468. });
  12469. },{"../internals/export":85,"../internals/is-array":102}],186:[function(require,module,exports){
  12470. 'use strict';
  12471. var $ = require('../internals/export');
  12472. var isObject = require('../internals/is-object');
  12473. var isArray = require('../internals/is-array');
  12474. var toAbsoluteIndex = require('../internals/to-absolute-index');
  12475. var toLength = require('../internals/to-length');
  12476. var toIndexedObject = require('../internals/to-indexed-object');
  12477. var createProperty = require('../internals/create-property');
  12478. var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
  12479. var wellKnownSymbol = require('../internals/well-known-symbol');
  12480. var SPECIES = wellKnownSymbol('species');
  12481. var nativeSlice = [].slice;
  12482. var max = Math.max;
  12483. // `Array.prototype.slice` method
  12484. // https://tc39.github.io/ecma262/#sec-array.prototype.slice
  12485. // fallback for not array-like ES3 strings and DOM objects
  12486. $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, {
  12487. slice: function slice(start, end) {
  12488. var O = toIndexedObject(this);
  12489. var length = toLength(O.length);
  12490. var k = toAbsoluteIndex(start, length);
  12491. var fin = toAbsoluteIndex(end === undefined ? length : end, length);
  12492. // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
  12493. var Constructor, result, n;
  12494. if (isArray(O)) {
  12495. Constructor = O.constructor;
  12496. // cross-realm fallback
  12497. if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
  12498. Constructor = undefined;
  12499. } else if (isObject(Constructor)) {
  12500. Constructor = Constructor[SPECIES];
  12501. if (Constructor === null) Constructor = undefined;
  12502. }
  12503. if (Constructor === Array || Constructor === undefined) {
  12504. return nativeSlice.call(O, k, fin);
  12505. }
  12506. }
  12507. result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
  12508. for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
  12509. result.length = n;
  12510. return result;
  12511. }
  12512. });
  12513. },{"../internals/array-method-has-species-support":64,"../internals/create-property":78,"../internals/export":85,"../internals/is-array":102,"../internals/is-object":105,"../internals/to-absolute-index":154,"../internals/to-indexed-object":156,"../internals/to-length":158,"../internals/well-known-symbol":169}],187:[function(require,module,exports){
  12514. var redefine = require('../internals/redefine');
  12515. var DatePrototype = Date.prototype;
  12516. var INVALID_DATE = 'Invalid Date';
  12517. var TO_STRING = 'toString';
  12518. var nativeDateToString = DatePrototype[TO_STRING];
  12519. var getTime = DatePrototype.getTime;
  12520. // `Date.prototype.toString` method
  12521. // https://tc39.github.io/ecma262/#sec-date.prototype.tostring
  12522. if (new Date(NaN) + '' != INVALID_DATE) {
  12523. redefine(DatePrototype, TO_STRING, function toString() {
  12524. var value = getTime.call(this);
  12525. // eslint-disable-next-line no-self-compare
  12526. return value === value ? nativeDateToString.call(this) : INVALID_DATE;
  12527. });
  12528. }
  12529. },{"../internals/redefine":138}],188:[function(require,module,exports){
  12530. var $ = require('../internals/export');
  12531. var bind = require('../internals/function-bind');
  12532. // `Function.prototype.bind` method
  12533. // https://tc39.github.io/ecma262/#sec-function.prototype.bind
  12534. $({ target: 'Function', proto: true }, {
  12535. bind: bind
  12536. });
  12537. },{"../internals/export":85,"../internals/function-bind":88}],189:[function(require,module,exports){
  12538. 'use strict';
  12539. var DESCRIPTORS = require('../internals/descriptors');
  12540. var global = require('../internals/global');
  12541. var isForced = require('../internals/is-forced');
  12542. var redefine = require('../internals/redefine');
  12543. var has = require('../internals/has');
  12544. var classof = require('../internals/classof-raw');
  12545. var inheritIfRequired = require('../internals/inherit-if-required');
  12546. var toPrimitive = require('../internals/to-primitive');
  12547. var fails = require('../internals/fails');
  12548. var create = require('../internals/object-create');
  12549. var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
  12550. var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
  12551. var defineProperty = require('../internals/object-define-property').f;
  12552. var trim = require('../internals/string-trim').trim;
  12553. var NUMBER = 'Number';
  12554. var NativeNumber = global[NUMBER];
  12555. var NumberPrototype = NativeNumber.prototype;
  12556. // Opera ~12 has broken Object#toString
  12557. var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER;
  12558. // `ToNumber` abstract operation
  12559. // https://tc39.github.io/ecma262/#sec-tonumber
  12560. var toNumber = function (argument) {
  12561. var it = toPrimitive(argument, false);
  12562. var first, third, radix, maxCode, digits, length, index, code;
  12563. if (typeof it == 'string' && it.length > 2) {
  12564. it = trim(it);
  12565. first = it.charCodeAt(0);
  12566. if (first === 43 || first === 45) {
  12567. third = it.charCodeAt(2);
  12568. if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
  12569. } else if (first === 48) {
  12570. switch (it.charCodeAt(1)) {
  12571. case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
  12572. case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
  12573. default: return +it;
  12574. }
  12575. digits = it.slice(2);
  12576. length = digits.length;
  12577. for (index = 0; index < length; index++) {
  12578. code = digits.charCodeAt(index);
  12579. // parseInt parses a string to a first unavailable symbol
  12580. // but ToNumber should return NaN if a string contains unavailable symbols
  12581. if (code < 48 || code > maxCode) return NaN;
  12582. } return parseInt(digits, radix);
  12583. }
  12584. } return +it;
  12585. };
  12586. // `Number` constructor
  12587. // https://tc39.github.io/ecma262/#sec-number-constructor
  12588. if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
  12589. var NumberWrapper = function Number(value) {
  12590. var it = arguments.length < 1 ? 0 : value;
  12591. var dummy = this;
  12592. return dummy instanceof NumberWrapper
  12593. // check on 1..constructor(foo) case
  12594. && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER)
  12595. ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
  12596. };
  12597. for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : (
  12598. // ES3:
  12599. 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
  12600. // ES2015 (in case, if modules with ES2015 Number statics required before):
  12601. 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
  12602. 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
  12603. ).split(','), j = 0, key; keys.length > j; j++) {
  12604. if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) {
  12605. defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));
  12606. }
  12607. }
  12608. NumberWrapper.prototype = NumberPrototype;
  12609. NumberPrototype.constructor = NumberWrapper;
  12610. redefine(global, NUMBER, NumberWrapper);
  12611. }
  12612. },{"../internals/classof-raw":70,"../internals/descriptors":81,"../internals/fails":86,"../internals/global":92,"../internals/has":93,"../internals/inherit-if-required":99,"../internals/is-forced":103,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/redefine":138,"../internals/string-trim":152,"../internals/to-primitive":162}],190:[function(require,module,exports){
  12613. var $ = require('../internals/export');
  12614. var assign = require('../internals/object-assign');
  12615. // `Object.assign` method
  12616. // https://tc39.github.io/ecma262/#sec-object.assign
  12617. $({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
  12618. assign: assign
  12619. });
  12620. },{"../internals/export":85,"../internals/object-assign":117}],191:[function(require,module,exports){
  12621. var $ = require('../internals/export');
  12622. var DESCRIPTORS = require('../internals/descriptors');
  12623. var defineProperties = require('../internals/object-define-properties');
  12624. // `Object.defineProperties` method
  12625. // https://tc39.github.io/ecma262/#sec-object.defineproperties
  12626. $({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, {
  12627. defineProperties: defineProperties
  12628. });
  12629. },{"../internals/descriptors":81,"../internals/export":85,"../internals/object-define-properties":119}],192:[function(require,module,exports){
  12630. var $ = require('../internals/export');
  12631. var DESCRIPTORS = require('../internals/descriptors');
  12632. var objectDefinePropertyModile = require('../internals/object-define-property');
  12633. // `Object.defineProperty` method
  12634. // https://tc39.github.io/ecma262/#sec-object.defineproperty
  12635. $({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, {
  12636. defineProperty: objectDefinePropertyModile.f
  12637. });
  12638. },{"../internals/descriptors":81,"../internals/export":85,"../internals/object-define-property":120}],193:[function(require,module,exports){
  12639. var $ = require('../internals/export');
  12640. var $entries = require('../internals/object-to-array').entries;
  12641. // `Object.entries` method
  12642. // https://tc39.github.io/ecma262/#sec-object.entries
  12643. $({ target: 'Object', stat: true }, {
  12644. entries: function entries(O) {
  12645. return $entries(O);
  12646. }
  12647. });
  12648. },{"../internals/export":85,"../internals/object-to-array":130}],194:[function(require,module,exports){
  12649. var $ = require('../internals/export');
  12650. var fails = require('../internals/fails');
  12651. var toIndexedObject = require('../internals/to-indexed-object');
  12652. var nativeGetOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
  12653. var DESCRIPTORS = require('../internals/descriptors');
  12654. var FAILS_ON_PRIMITIVES = fails(function () { nativeGetOwnPropertyDescriptor(1); });
  12655. var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES;
  12656. // `Object.getOwnPropertyDescriptor` method
  12657. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
  12658. $({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, {
  12659. getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
  12660. return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key);
  12661. }
  12662. });
  12663. },{"../internals/descriptors":81,"../internals/export":85,"../internals/fails":86,"../internals/object-get-own-property-descriptor":121,"../internals/to-indexed-object":156}],195:[function(require,module,exports){
  12664. var $ = require('../internals/export');
  12665. var DESCRIPTORS = require('../internals/descriptors');
  12666. var ownKeys = require('../internals/own-keys');
  12667. var toIndexedObject = require('../internals/to-indexed-object');
  12668. var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
  12669. var createProperty = require('../internals/create-property');
  12670. // `Object.getOwnPropertyDescriptors` method
  12671. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
  12672. $({ target: 'Object', stat: true, sham: !DESCRIPTORS }, {
  12673. getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
  12674. var O = toIndexedObject(object);
  12675. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  12676. var keys = ownKeys(O);
  12677. var result = {};
  12678. var index = 0;
  12679. var key, descriptor;
  12680. while (keys.length > index) {
  12681. descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
  12682. if (descriptor !== undefined) createProperty(result, key, descriptor);
  12683. }
  12684. return result;
  12685. }
  12686. });
  12687. },{"../internals/create-property":78,"../internals/descriptors":81,"../internals/export":85,"../internals/object-get-own-property-descriptor":121,"../internals/own-keys":132,"../internals/to-indexed-object":156}],196:[function(require,module,exports){
  12688. var $ = require('../internals/export');
  12689. var toObject = require('../internals/to-object');
  12690. var nativeKeys = require('../internals/object-keys');
  12691. var fails = require('../internals/fails');
  12692. var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); });
  12693. // `Object.keys` method
  12694. // https://tc39.github.io/ecma262/#sec-object.keys
  12695. $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
  12696. keys: function keys(it) {
  12697. return nativeKeys(toObject(it));
  12698. }
  12699. });
  12700. },{"../internals/export":85,"../internals/fails":86,"../internals/object-keys":127,"../internals/to-object":159}],197:[function(require,module,exports){
  12701. var redefine = require('../internals/redefine');
  12702. var toString = require('../internals/object-to-string');
  12703. var ObjectPrototype = Object.prototype;
  12704. // `Object.prototype.toString` method
  12705. // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
  12706. if (toString !== ObjectPrototype.toString) {
  12707. redefine(ObjectPrototype, 'toString', toString, { unsafe: true });
  12708. }
  12709. },{"../internals/object-to-string":131,"../internals/redefine":138}],198:[function(require,module,exports){
  12710. var $ = require('../internals/export');
  12711. var parseIntImplementation = require('../internals/parse-int');
  12712. // `parseInt` method
  12713. // https://tc39.github.io/ecma262/#sec-parseint-string-radix
  12714. $({ global: true, forced: parseInt != parseIntImplementation }, {
  12715. parseInt: parseIntImplementation
  12716. });
  12717. },{"../internals/export":85,"../internals/parse-int":133}],199:[function(require,module,exports){
  12718. 'use strict';
  12719. var $ = require('../internals/export');
  12720. var IS_PURE = require('../internals/is-pure');
  12721. var global = require('../internals/global');
  12722. var getBuiltIn = require('../internals/get-built-in');
  12723. var NativePromise = require('../internals/native-promise-constructor');
  12724. var redefine = require('../internals/redefine');
  12725. var redefineAll = require('../internals/redefine-all');
  12726. var shared = require('../internals/shared');
  12727. var setToStringTag = require('../internals/set-to-string-tag');
  12728. var setSpecies = require('../internals/set-species');
  12729. var isObject = require('../internals/is-object');
  12730. var aFunction = require('../internals/a-function');
  12731. var anInstance = require('../internals/an-instance');
  12732. var classof = require('../internals/classof-raw');
  12733. var iterate = require('../internals/iterate');
  12734. var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');
  12735. var speciesConstructor = require('../internals/species-constructor');
  12736. var task = require('../internals/task').set;
  12737. var microtask = require('../internals/microtask');
  12738. var promiseResolve = require('../internals/promise-resolve');
  12739. var hostReportErrors = require('../internals/host-report-errors');
  12740. var newPromiseCapabilityModule = require('../internals/new-promise-capability');
  12741. var perform = require('../internals/perform');
  12742. var InternalStateModule = require('../internals/internal-state');
  12743. var isForced = require('../internals/is-forced');
  12744. var wellKnownSymbol = require('../internals/well-known-symbol');
  12745. var V8_VERSION = require('../internals/v8-version');
  12746. var SPECIES = wellKnownSymbol('species');
  12747. var PROMISE = 'Promise';
  12748. var getInternalState = InternalStateModule.get;
  12749. var setInternalState = InternalStateModule.set;
  12750. var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
  12751. var PromiseConstructor = NativePromise;
  12752. var TypeError = global.TypeError;
  12753. var document = global.document;
  12754. var process = global.process;
  12755. var inspectSource = shared('inspectSource');
  12756. var $fetch = getBuiltIn('fetch');
  12757. var newPromiseCapability = newPromiseCapabilityModule.f;
  12758. var newGenericPromiseCapability = newPromiseCapability;
  12759. var IS_NODE = classof(process) == 'process';
  12760. var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);
  12761. var UNHANDLED_REJECTION = 'unhandledrejection';
  12762. var REJECTION_HANDLED = 'rejectionhandled';
  12763. var PENDING = 0;
  12764. var FULFILLED = 1;
  12765. var REJECTED = 2;
  12766. var HANDLED = 1;
  12767. var UNHANDLED = 2;
  12768. var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
  12769. var FORCED = isForced(PROMISE, function () {
  12770. var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);
  12771. // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
  12772. // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
  12773. // We can't detect it synchronously, so just check versions
  12774. if (V8_VERSION === 66) return true;
  12775. // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
  12776. if (!GLOBAL_CORE_JS_PROMISE && !IS_NODE && typeof PromiseRejectionEvent != 'function') return true;
  12777. // We need Promise#finally in the pure version for preventing prototype pollution
  12778. if (IS_PURE && !PromiseConstructor.prototype['finally']) return true;
  12779. // We can't use @@species feature detection in V8 since it causes
  12780. // deoptimization and performance degradation
  12781. // https://github.com/zloirock/core-js/issues/679
  12782. if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;
  12783. // Detect correctness of subclassing with @@species support
  12784. var promise = PromiseConstructor.resolve(1);
  12785. var FakePromise = function (exec) {
  12786. exec(function () { /* empty */ }, function () { /* empty */ });
  12787. };
  12788. var constructor = promise.constructor = {};
  12789. constructor[SPECIES] = FakePromise;
  12790. return !(promise.then(function () { /* empty */ }) instanceof FakePromise);
  12791. });
  12792. var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {
  12793. PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
  12794. });
  12795. // helpers
  12796. var isThenable = function (it) {
  12797. var then;
  12798. return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
  12799. };
  12800. var notify = function (promise, state, isReject) {
  12801. if (state.notified) return;
  12802. state.notified = true;
  12803. var chain = state.reactions;
  12804. microtask(function () {
  12805. var value = state.value;
  12806. var ok = state.state == FULFILLED;
  12807. var index = 0;
  12808. // variable length - can't use forEach
  12809. while (chain.length > index) {
  12810. var reaction = chain[index++];
  12811. var handler = ok ? reaction.ok : reaction.fail;
  12812. var resolve = reaction.resolve;
  12813. var reject = reaction.reject;
  12814. var domain = reaction.domain;
  12815. var result, then, exited;
  12816. try {
  12817. if (handler) {
  12818. if (!ok) {
  12819. if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state);
  12820. state.rejection = HANDLED;
  12821. }
  12822. if (handler === true) result = value;
  12823. else {
  12824. if (domain) domain.enter();
  12825. result = handler(value); // can throw
  12826. if (domain) {
  12827. domain.exit();
  12828. exited = true;
  12829. }
  12830. }
  12831. if (result === reaction.promise) {
  12832. reject(TypeError('Promise-chain cycle'));
  12833. } else if (then = isThenable(result)) {
  12834. then.call(result, resolve, reject);
  12835. } else resolve(result);
  12836. } else reject(value);
  12837. } catch (error) {
  12838. if (domain && !exited) domain.exit();
  12839. reject(error);
  12840. }
  12841. }
  12842. state.reactions = [];
  12843. state.notified = false;
  12844. if (isReject && !state.rejection) onUnhandled(promise, state);
  12845. });
  12846. };
  12847. var dispatchEvent = function (name, promise, reason) {
  12848. var event, handler;
  12849. if (DISPATCH_EVENT) {
  12850. event = document.createEvent('Event');
  12851. event.promise = promise;
  12852. event.reason = reason;
  12853. event.initEvent(name, false, true);
  12854. global.dispatchEvent(event);
  12855. } else event = { promise: promise, reason: reason };
  12856. if (handler = global['on' + name]) handler(event);
  12857. else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
  12858. };
  12859. var onUnhandled = function (promise, state) {
  12860. task.call(global, function () {
  12861. var value = state.value;
  12862. var IS_UNHANDLED = isUnhandled(state);
  12863. var result;
  12864. if (IS_UNHANDLED) {
  12865. result = perform(function () {
  12866. if (IS_NODE) {
  12867. process.emit('unhandledRejection', value, promise);
  12868. } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
  12869. });
  12870. // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
  12871. state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
  12872. if (result.error) throw result.value;
  12873. }
  12874. });
  12875. };
  12876. var isUnhandled = function (state) {
  12877. return state.rejection !== HANDLED && !state.parent;
  12878. };
  12879. var onHandleUnhandled = function (promise, state) {
  12880. task.call(global, function () {
  12881. if (IS_NODE) {
  12882. process.emit('rejectionHandled', promise);
  12883. } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
  12884. });
  12885. };
  12886. var bind = function (fn, promise, state, unwrap) {
  12887. return function (value) {
  12888. fn(promise, state, value, unwrap);
  12889. };
  12890. };
  12891. var internalReject = function (promise, state, value, unwrap) {
  12892. if (state.done) return;
  12893. state.done = true;
  12894. if (unwrap) state = unwrap;
  12895. state.value = value;
  12896. state.state = REJECTED;
  12897. notify(promise, state, true);
  12898. };
  12899. var internalResolve = function (promise, state, value, unwrap) {
  12900. if (state.done) return;
  12901. state.done = true;
  12902. if (unwrap) state = unwrap;
  12903. try {
  12904. if (promise === value) throw TypeError("Promise can't be resolved itself");
  12905. var then = isThenable(value);
  12906. if (then) {
  12907. microtask(function () {
  12908. var wrapper = { done: false };
  12909. try {
  12910. then.call(value,
  12911. bind(internalResolve, promise, wrapper, state),
  12912. bind(internalReject, promise, wrapper, state)
  12913. );
  12914. } catch (error) {
  12915. internalReject(promise, wrapper, error, state);
  12916. }
  12917. });
  12918. } else {
  12919. state.value = value;
  12920. state.state = FULFILLED;
  12921. notify(promise, state, false);
  12922. }
  12923. } catch (error) {
  12924. internalReject(promise, { done: false }, error, state);
  12925. }
  12926. };
  12927. // constructor polyfill
  12928. if (FORCED) {
  12929. // 25.4.3.1 Promise(executor)
  12930. PromiseConstructor = function Promise(executor) {
  12931. anInstance(this, PromiseConstructor, PROMISE);
  12932. aFunction(executor);
  12933. Internal.call(this);
  12934. var state = getInternalState(this);
  12935. try {
  12936. executor(bind(internalResolve, this, state), bind(internalReject, this, state));
  12937. } catch (error) {
  12938. internalReject(this, state, error);
  12939. }
  12940. };
  12941. // eslint-disable-next-line no-unused-vars
  12942. Internal = function Promise(executor) {
  12943. setInternalState(this, {
  12944. type: PROMISE,
  12945. done: false,
  12946. notified: false,
  12947. parent: false,
  12948. reactions: [],
  12949. rejection: false,
  12950. state: PENDING,
  12951. value: undefined
  12952. });
  12953. };
  12954. Internal.prototype = redefineAll(PromiseConstructor.prototype, {
  12955. // `Promise.prototype.then` method
  12956. // https://tc39.github.io/ecma262/#sec-promise.prototype.then
  12957. then: function then(onFulfilled, onRejected) {
  12958. var state = getInternalPromiseState(this);
  12959. var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
  12960. reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
  12961. reaction.fail = typeof onRejected == 'function' && onRejected;
  12962. reaction.domain = IS_NODE ? process.domain : undefined;
  12963. state.parent = true;
  12964. state.reactions.push(reaction);
  12965. if (state.state != PENDING) notify(this, state, false);
  12966. return reaction.promise;
  12967. },
  12968. // `Promise.prototype.catch` method
  12969. // https://tc39.github.io/ecma262/#sec-promise.prototype.catch
  12970. 'catch': function (onRejected) {
  12971. return this.then(undefined, onRejected);
  12972. }
  12973. });
  12974. OwnPromiseCapability = function () {
  12975. var promise = new Internal();
  12976. var state = getInternalState(promise);
  12977. this.promise = promise;
  12978. this.resolve = bind(internalResolve, promise, state);
  12979. this.reject = bind(internalReject, promise, state);
  12980. };
  12981. newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
  12982. return C === PromiseConstructor || C === PromiseWrapper
  12983. ? new OwnPromiseCapability(C)
  12984. : newGenericPromiseCapability(C);
  12985. };
  12986. if (!IS_PURE && typeof NativePromise == 'function') {
  12987. nativeThen = NativePromise.prototype.then;
  12988. // wrap native Promise#then for native async functions
  12989. redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {
  12990. var that = this;
  12991. return new PromiseConstructor(function (resolve, reject) {
  12992. nativeThen.call(that, resolve, reject);
  12993. }).then(onFulfilled, onRejected);
  12994. // https://github.com/zloirock/core-js/issues/640
  12995. }, { unsafe: true });
  12996. // wrap fetch result
  12997. if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, {
  12998. // eslint-disable-next-line no-unused-vars
  12999. fetch: function fetch(input /* , init */) {
  13000. return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));
  13001. }
  13002. });
  13003. }
  13004. }
  13005. $({ global: true, wrap: true, forced: FORCED }, {
  13006. Promise: PromiseConstructor
  13007. });
  13008. setToStringTag(PromiseConstructor, PROMISE, false, true);
  13009. setSpecies(PROMISE);
  13010. PromiseWrapper = getBuiltIn(PROMISE);
  13011. // statics
  13012. $({ target: PROMISE, stat: true, forced: FORCED }, {
  13013. // `Promise.reject` method
  13014. // https://tc39.github.io/ecma262/#sec-promise.reject
  13015. reject: function reject(r) {
  13016. var capability = newPromiseCapability(this);
  13017. capability.reject.call(undefined, r);
  13018. return capability.promise;
  13019. }
  13020. });
  13021. $({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {
  13022. // `Promise.resolve` method
  13023. // https://tc39.github.io/ecma262/#sec-promise.resolve
  13024. resolve: function resolve(x) {
  13025. return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);
  13026. }
  13027. });
  13028. $({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {
  13029. // `Promise.all` method
  13030. // https://tc39.github.io/ecma262/#sec-promise.all
  13031. all: function all(iterable) {
  13032. var C = this;
  13033. var capability = newPromiseCapability(C);
  13034. var resolve = capability.resolve;
  13035. var reject = capability.reject;
  13036. var result = perform(function () {
  13037. var $promiseResolve = aFunction(C.resolve);
  13038. var values = [];
  13039. var counter = 0;
  13040. var remaining = 1;
  13041. iterate(iterable, function (promise) {
  13042. var index = counter++;
  13043. var alreadyCalled = false;
  13044. values.push(undefined);
  13045. remaining++;
  13046. $promiseResolve.call(C, promise).then(function (value) {
  13047. if (alreadyCalled) return;
  13048. alreadyCalled = true;
  13049. values[index] = value;
  13050. --remaining || resolve(values);
  13051. }, reject);
  13052. });
  13053. --remaining || resolve(values);
  13054. });
  13055. if (result.error) reject(result.value);
  13056. return capability.promise;
  13057. },
  13058. // `Promise.race` method
  13059. // https://tc39.github.io/ecma262/#sec-promise.race
  13060. race: function race(iterable) {
  13061. var C = this;
  13062. var capability = newPromiseCapability(C);
  13063. var reject = capability.reject;
  13064. var result = perform(function () {
  13065. var $promiseResolve = aFunction(C.resolve);
  13066. iterate(iterable, function (promise) {
  13067. $promiseResolve.call(C, promise).then(capability.resolve, reject);
  13068. });
  13069. });
  13070. if (result.error) reject(result.value);
  13071. return capability.promise;
  13072. }
  13073. });
  13074. },{"../internals/a-function":50,"../internals/an-instance":54,"../internals/check-correctness-of-iteration":69,"../internals/classof-raw":70,"../internals/export":85,"../internals/get-built-in":90,"../internals/global":92,"../internals/host-report-errors":95,"../internals/internal-state":100,"../internals/is-forced":103,"../internals/is-object":105,"../internals/is-pure":106,"../internals/iterate":108,"../internals/microtask":111,"../internals/native-promise-constructor":112,"../internals/new-promise-capability":115,"../internals/perform":135,"../internals/promise-resolve":136,"../internals/redefine":138,"../internals/redefine-all":137,"../internals/set-species":144,"../internals/set-to-string-tag":145,"../internals/shared":148,"../internals/species-constructor":150,"../internals/task":153,"../internals/v8-version":168,"../internals/well-known-symbol":169}],200:[function(require,module,exports){
  13075. 'use strict';
  13076. var $ = require('../internals/export');
  13077. var exec = require('../internals/regexp-exec');
  13078. $({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, {
  13079. exec: exec
  13080. });
  13081. },{"../internals/export":85,"../internals/regexp-exec":140}],201:[function(require,module,exports){
  13082. 'use strict';
  13083. var redefine = require('../internals/redefine');
  13084. var anObject = require('../internals/an-object');
  13085. var fails = require('../internals/fails');
  13086. var flags = require('../internals/regexp-flags');
  13087. var TO_STRING = 'toString';
  13088. var RegExpPrototype = RegExp.prototype;
  13089. var nativeToString = RegExpPrototype[TO_STRING];
  13090. var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
  13091. // FF44- RegExp#toString has a wrong name
  13092. var INCORRECT_NAME = nativeToString.name != TO_STRING;
  13093. // `RegExp.prototype.toString` method
  13094. // https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring
  13095. if (NOT_GENERIC || INCORRECT_NAME) {
  13096. redefine(RegExp.prototype, TO_STRING, function toString() {
  13097. var R = anObject(this);
  13098. var p = String(R.source);
  13099. var rf = R.flags;
  13100. var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf);
  13101. return '/' + p + '/' + f;
  13102. }, { unsafe: true });
  13103. }
  13104. },{"../internals/an-object":55,"../internals/fails":86,"../internals/redefine":138,"../internals/regexp-flags":141}],202:[function(require,module,exports){
  13105. 'use strict';
  13106. var $ = require('../internals/export');
  13107. var notARegExp = require('../internals/not-a-regexp');
  13108. var requireObjectCoercible = require('../internals/require-object-coercible');
  13109. var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');
  13110. // `String.prototype.includes` method
  13111. // https://tc39.github.io/ecma262/#sec-string.prototype.includes
  13112. $({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, {
  13113. includes: function includes(searchString /* , position = 0 */) {
  13114. return !!~String(requireObjectCoercible(this))
  13115. .indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined);
  13116. }
  13117. });
  13118. },{"../internals/correct-is-regexp-logic":73,"../internals/export":85,"../internals/not-a-regexp":116,"../internals/require-object-coercible":142}],203:[function(require,module,exports){
  13119. 'use strict';
  13120. var charAt = require('../internals/string-multibyte').charAt;
  13121. var InternalStateModule = require('../internals/internal-state');
  13122. var defineIterator = require('../internals/define-iterator');
  13123. var STRING_ITERATOR = 'String Iterator';
  13124. var setInternalState = InternalStateModule.set;
  13125. var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
  13126. // `String.prototype[@@iterator]` method
  13127. // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
  13128. defineIterator(String, 'String', function (iterated) {
  13129. setInternalState(this, {
  13130. type: STRING_ITERATOR,
  13131. string: String(iterated),
  13132. index: 0
  13133. });
  13134. // `%StringIteratorPrototype%.next` method
  13135. // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
  13136. }, function next() {
  13137. var state = getInternalState(this);
  13138. var string = state.string;
  13139. var index = state.index;
  13140. var point;
  13141. if (index >= string.length) return { value: undefined, done: true };
  13142. point = charAt(string, index);
  13143. state.index += point.length;
  13144. return { value: point, done: false };
  13145. });
  13146. },{"../internals/define-iterator":79,"../internals/internal-state":100,"../internals/string-multibyte":151}],204:[function(require,module,exports){
  13147. 'use strict';
  13148. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  13149. var anObject = require('../internals/an-object');
  13150. var toLength = require('../internals/to-length');
  13151. var requireObjectCoercible = require('../internals/require-object-coercible');
  13152. var advanceStringIndex = require('../internals/advance-string-index');
  13153. var regExpExec = require('../internals/regexp-exec-abstract');
  13154. // @@match logic
  13155. fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) {
  13156. return [
  13157. // `String.prototype.match` method
  13158. // https://tc39.github.io/ecma262/#sec-string.prototype.match
  13159. function match(regexp) {
  13160. var O = requireObjectCoercible(this);
  13161. var matcher = regexp == undefined ? undefined : regexp[MATCH];
  13162. return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
  13163. },
  13164. // `RegExp.prototype[@@match]` method
  13165. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
  13166. function (regexp) {
  13167. var res = maybeCallNative(nativeMatch, regexp, this);
  13168. if (res.done) return res.value;
  13169. var rx = anObject(regexp);
  13170. var S = String(this);
  13171. if (!rx.global) return regExpExec(rx, S);
  13172. var fullUnicode = rx.unicode;
  13173. rx.lastIndex = 0;
  13174. var A = [];
  13175. var n = 0;
  13176. var result;
  13177. while ((result = regExpExec(rx, S)) !== null) {
  13178. var matchStr = String(result[0]);
  13179. A[n] = matchStr;
  13180. if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
  13181. n++;
  13182. }
  13183. return n === 0 ? null : A;
  13184. }
  13185. ];
  13186. });
  13187. },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/to-length":158}],205:[function(require,module,exports){
  13188. 'use strict';
  13189. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  13190. var anObject = require('../internals/an-object');
  13191. var toObject = require('../internals/to-object');
  13192. var toLength = require('../internals/to-length');
  13193. var toInteger = require('../internals/to-integer');
  13194. var requireObjectCoercible = require('../internals/require-object-coercible');
  13195. var advanceStringIndex = require('../internals/advance-string-index');
  13196. var regExpExec = require('../internals/regexp-exec-abstract');
  13197. var max = Math.max;
  13198. var min = Math.min;
  13199. var floor = Math.floor;
  13200. var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
  13201. var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;
  13202. var maybeToString = function (it) {
  13203. return it === undefined ? it : String(it);
  13204. };
  13205. // @@replace logic
  13206. fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) {
  13207. return [
  13208. // `String.prototype.replace` method
  13209. // https://tc39.github.io/ecma262/#sec-string.prototype.replace
  13210. function replace(searchValue, replaceValue) {
  13211. var O = requireObjectCoercible(this);
  13212. var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
  13213. return replacer !== undefined
  13214. ? replacer.call(searchValue, O, replaceValue)
  13215. : nativeReplace.call(String(O), searchValue, replaceValue);
  13216. },
  13217. // `RegExp.prototype[@@replace]` method
  13218. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
  13219. function (regexp, replaceValue) {
  13220. var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
  13221. if (res.done) return res.value;
  13222. var rx = anObject(regexp);
  13223. var S = String(this);
  13224. var functionalReplace = typeof replaceValue === 'function';
  13225. if (!functionalReplace) replaceValue = String(replaceValue);
  13226. var global = rx.global;
  13227. if (global) {
  13228. var fullUnicode = rx.unicode;
  13229. rx.lastIndex = 0;
  13230. }
  13231. var results = [];
  13232. while (true) {
  13233. var result = regExpExec(rx, S);
  13234. if (result === null) break;
  13235. results.push(result);
  13236. if (!global) break;
  13237. var matchStr = String(result[0]);
  13238. if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
  13239. }
  13240. var accumulatedResult = '';
  13241. var nextSourcePosition = 0;
  13242. for (var i = 0; i < results.length; i++) {
  13243. result = results[i];
  13244. var matched = String(result[0]);
  13245. var position = max(min(toInteger(result.index), S.length), 0);
  13246. var captures = [];
  13247. // NOTE: This is equivalent to
  13248. // captures = result.slice(1).map(maybeToString)
  13249. // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
  13250. // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
  13251. // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
  13252. for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
  13253. var namedCaptures = result.groups;
  13254. if (functionalReplace) {
  13255. var replacerArgs = [matched].concat(captures, position, S);
  13256. if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
  13257. var replacement = String(replaceValue.apply(undefined, replacerArgs));
  13258. } else {
  13259. replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
  13260. }
  13261. if (position >= nextSourcePosition) {
  13262. accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
  13263. nextSourcePosition = position + matched.length;
  13264. }
  13265. }
  13266. return accumulatedResult + S.slice(nextSourcePosition);
  13267. }
  13268. ];
  13269. // https://tc39.github.io/ecma262/#sec-getsubstitution
  13270. function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
  13271. var tailPos = position + matched.length;
  13272. var m = captures.length;
  13273. var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
  13274. if (namedCaptures !== undefined) {
  13275. namedCaptures = toObject(namedCaptures);
  13276. symbols = SUBSTITUTION_SYMBOLS;
  13277. }
  13278. return nativeReplace.call(replacement, symbols, function (match, ch) {
  13279. var capture;
  13280. switch (ch.charAt(0)) {
  13281. case '$': return '$';
  13282. case '&': return matched;
  13283. case '`': return str.slice(0, position);
  13284. case "'": return str.slice(tailPos);
  13285. case '<':
  13286. capture = namedCaptures[ch.slice(1, -1)];
  13287. break;
  13288. default: // \d\d?
  13289. var n = +ch;
  13290. if (n === 0) return match;
  13291. if (n > m) {
  13292. var f = floor(n / 10);
  13293. if (f === 0) return match;
  13294. if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
  13295. return match;
  13296. }
  13297. capture = captures[n - 1];
  13298. }
  13299. return capture === undefined ? '' : capture;
  13300. });
  13301. }
  13302. });
  13303. },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/to-integer":157,"../internals/to-length":158,"../internals/to-object":159}],206:[function(require,module,exports){
  13304. 'use strict';
  13305. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  13306. var isRegExp = require('../internals/is-regexp');
  13307. var anObject = require('../internals/an-object');
  13308. var requireObjectCoercible = require('../internals/require-object-coercible');
  13309. var speciesConstructor = require('../internals/species-constructor');
  13310. var advanceStringIndex = require('../internals/advance-string-index');
  13311. var toLength = require('../internals/to-length');
  13312. var callRegExpExec = require('../internals/regexp-exec-abstract');
  13313. var regexpExec = require('../internals/regexp-exec');
  13314. var fails = require('../internals/fails');
  13315. var arrayPush = [].push;
  13316. var min = Math.min;
  13317. var MAX_UINT32 = 0xFFFFFFFF;
  13318. // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
  13319. var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });
  13320. // @@split logic
  13321. fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
  13322. var internalSplit;
  13323. if (
  13324. 'abbc'.split(/(b)*/)[1] == 'c' ||
  13325. 'test'.split(/(?:)/, -1).length != 4 ||
  13326. 'ab'.split(/(?:ab)*/).length != 2 ||
  13327. '.'.split(/(.?)(.?)/).length != 4 ||
  13328. '.'.split(/()()/).length > 1 ||
  13329. ''.split(/.?/).length
  13330. ) {
  13331. // based on es5-shim implementation, need to rework it
  13332. internalSplit = function (separator, limit) {
  13333. var string = String(requireObjectCoercible(this));
  13334. var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
  13335. if (lim === 0) return [];
  13336. if (separator === undefined) return [string];
  13337. // If `separator` is not a regex, use native split
  13338. if (!isRegExp(separator)) {
  13339. return nativeSplit.call(string, separator, lim);
  13340. }
  13341. var output = [];
  13342. var flags = (separator.ignoreCase ? 'i' : '') +
  13343. (separator.multiline ? 'm' : '') +
  13344. (separator.unicode ? 'u' : '') +
  13345. (separator.sticky ? 'y' : '');
  13346. var lastLastIndex = 0;
  13347. // Make `global` and avoid `lastIndex` issues by working with a copy
  13348. var separatorCopy = new RegExp(separator.source, flags + 'g');
  13349. var match, lastIndex, lastLength;
  13350. while (match = regexpExec.call(separatorCopy, string)) {
  13351. lastIndex = separatorCopy.lastIndex;
  13352. if (lastIndex > lastLastIndex) {
  13353. output.push(string.slice(lastLastIndex, match.index));
  13354. if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
  13355. lastLength = match[0].length;
  13356. lastLastIndex = lastIndex;
  13357. if (output.length >= lim) break;
  13358. }
  13359. if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
  13360. }
  13361. if (lastLastIndex === string.length) {
  13362. if (lastLength || !separatorCopy.test('')) output.push('');
  13363. } else output.push(string.slice(lastLastIndex));
  13364. return output.length > lim ? output.slice(0, lim) : output;
  13365. };
  13366. // Chakra, V8
  13367. } else if ('0'.split(undefined, 0).length) {
  13368. internalSplit = function (separator, limit) {
  13369. return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
  13370. };
  13371. } else internalSplit = nativeSplit;
  13372. return [
  13373. // `String.prototype.split` method
  13374. // https://tc39.github.io/ecma262/#sec-string.prototype.split
  13375. function split(separator, limit) {
  13376. var O = requireObjectCoercible(this);
  13377. var splitter = separator == undefined ? undefined : separator[SPLIT];
  13378. return splitter !== undefined
  13379. ? splitter.call(separator, O, limit)
  13380. : internalSplit.call(String(O), separator, limit);
  13381. },
  13382. // `RegExp.prototype[@@split]` method
  13383. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
  13384. //
  13385. // NOTE: This cannot be properly polyfilled in engines that don't support
  13386. // the 'y' flag.
  13387. function (regexp, limit) {
  13388. var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
  13389. if (res.done) return res.value;
  13390. var rx = anObject(regexp);
  13391. var S = String(this);
  13392. var C = speciesConstructor(rx, RegExp);
  13393. var unicodeMatching = rx.unicode;
  13394. var flags = (rx.ignoreCase ? 'i' : '') +
  13395. (rx.multiline ? 'm' : '') +
  13396. (rx.unicode ? 'u' : '') +
  13397. (SUPPORTS_Y ? 'y' : 'g');
  13398. // ^(? + rx + ) is needed, in combination with some S slicing, to
  13399. // simulate the 'y' flag.
  13400. var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
  13401. var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
  13402. if (lim === 0) return [];
  13403. if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : [];
  13404. var p = 0;
  13405. var q = 0;
  13406. var A = [];
  13407. while (q < S.length) {
  13408. splitter.lastIndex = SUPPORTS_Y ? q : 0;
  13409. var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q));
  13410. var e;
  13411. if (
  13412. z === null ||
  13413. (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
  13414. ) {
  13415. q = advanceStringIndex(S, q, unicodeMatching);
  13416. } else {
  13417. A.push(S.slice(p, q));
  13418. if (A.length === lim) return A;
  13419. for (var i = 1; i <= z.length - 1; i++) {
  13420. A.push(z[i]);
  13421. if (A.length === lim) return A;
  13422. }
  13423. q = p = e;
  13424. }
  13425. }
  13426. A.push(S.slice(p));
  13427. return A;
  13428. }
  13429. ];
  13430. }, !SUPPORTS_Y);
  13431. },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fails":86,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/is-regexp":107,"../internals/regexp-exec":140,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/species-constructor":150,"../internals/to-length":158}],207:[function(require,module,exports){
  13432. 'use strict';
  13433. var $ = require('../internals/export');
  13434. var global = require('../internals/global');
  13435. var getBuiltIn = require('../internals/get-built-in');
  13436. var IS_PURE = require('../internals/is-pure');
  13437. var DESCRIPTORS = require('../internals/descriptors');
  13438. var NATIVE_SYMBOL = require('../internals/native-symbol');
  13439. var fails = require('../internals/fails');
  13440. var has = require('../internals/has');
  13441. var isArray = require('../internals/is-array');
  13442. var isObject = require('../internals/is-object');
  13443. var anObject = require('../internals/an-object');
  13444. var toObject = require('../internals/to-object');
  13445. var toIndexedObject = require('../internals/to-indexed-object');
  13446. var toPrimitive = require('../internals/to-primitive');
  13447. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  13448. var nativeObjectCreate = require('../internals/object-create');
  13449. var objectKeys = require('../internals/object-keys');
  13450. var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');
  13451. var getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external');
  13452. var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
  13453. var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
  13454. var definePropertyModule = require('../internals/object-define-property');
  13455. var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
  13456. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  13457. var redefine = require('../internals/redefine');
  13458. var shared = require('../internals/shared');
  13459. var sharedKey = require('../internals/shared-key');
  13460. var hiddenKeys = require('../internals/hidden-keys');
  13461. var uid = require('../internals/uid');
  13462. var wellKnownSymbol = require('../internals/well-known-symbol');
  13463. var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol');
  13464. var defineWellKnownSymbol = require('../internals/define-well-known-symbol');
  13465. var setToStringTag = require('../internals/set-to-string-tag');
  13466. var InternalStateModule = require('../internals/internal-state');
  13467. var $forEach = require('../internals/array-iteration').forEach;
  13468. var HIDDEN = sharedKey('hidden');
  13469. var SYMBOL = 'Symbol';
  13470. var PROTOTYPE = 'prototype';
  13471. var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
  13472. var setInternalState = InternalStateModule.set;
  13473. var getInternalState = InternalStateModule.getterFor(SYMBOL);
  13474. var ObjectPrototype = Object[PROTOTYPE];
  13475. var $Symbol = global.Symbol;
  13476. var $stringify = getBuiltIn('JSON', 'stringify');
  13477. var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  13478. var nativeDefineProperty = definePropertyModule.f;
  13479. var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;
  13480. var nativePropertyIsEnumerable = propertyIsEnumerableModule.f;
  13481. var AllSymbols = shared('symbols');
  13482. var ObjectPrototypeSymbols = shared('op-symbols');
  13483. var StringToSymbolRegistry = shared('string-to-symbol-registry');
  13484. var SymbolToStringRegistry = shared('symbol-to-string-registry');
  13485. var WellKnownSymbolsStore = shared('wks');
  13486. var QObject = global.QObject;
  13487. // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
  13488. var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
  13489. // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
  13490. var setSymbolDescriptor = DESCRIPTORS && fails(function () {
  13491. return nativeObjectCreate(nativeDefineProperty({}, 'a', {
  13492. get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }
  13493. })).a != 7;
  13494. }) ? function (O, P, Attributes) {
  13495. var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);
  13496. if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
  13497. nativeDefineProperty(O, P, Attributes);
  13498. if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
  13499. nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);
  13500. }
  13501. } : nativeDefineProperty;
  13502. var wrap = function (tag, description) {
  13503. var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);
  13504. setInternalState(symbol, {
  13505. type: SYMBOL,
  13506. tag: tag,
  13507. description: description
  13508. });
  13509. if (!DESCRIPTORS) symbol.description = description;
  13510. return symbol;
  13511. };
  13512. var isSymbol = NATIVE_SYMBOL && typeof $Symbol.iterator == 'symbol' ? function (it) {
  13513. return typeof it == 'symbol';
  13514. } : function (it) {
  13515. return Object(it) instanceof $Symbol;
  13516. };
  13517. var $defineProperty = function defineProperty(O, P, Attributes) {
  13518. if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
  13519. anObject(O);
  13520. var key = toPrimitive(P, true);
  13521. anObject(Attributes);
  13522. if (has(AllSymbols, key)) {
  13523. if (!Attributes.enumerable) {
  13524. if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
  13525. O[HIDDEN][key] = true;
  13526. } else {
  13527. if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
  13528. Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
  13529. } return setSymbolDescriptor(O, key, Attributes);
  13530. } return nativeDefineProperty(O, key, Attributes);
  13531. };
  13532. var $defineProperties = function defineProperties(O, Properties) {
  13533. anObject(O);
  13534. var properties = toIndexedObject(Properties);
  13535. var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
  13536. $forEach(keys, function (key) {
  13537. if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
  13538. });
  13539. return O;
  13540. };
  13541. var $create = function create(O, Properties) {
  13542. return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);
  13543. };
  13544. var $propertyIsEnumerable = function propertyIsEnumerable(V) {
  13545. var P = toPrimitive(V, true);
  13546. var enumerable = nativePropertyIsEnumerable.call(this, P);
  13547. if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
  13548. return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
  13549. };
  13550. var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
  13551. var it = toIndexedObject(O);
  13552. var key = toPrimitive(P, true);
  13553. if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
  13554. var descriptor = nativeGetOwnPropertyDescriptor(it, key);
  13555. if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
  13556. descriptor.enumerable = true;
  13557. }
  13558. return descriptor;
  13559. };
  13560. var $getOwnPropertyNames = function getOwnPropertyNames(O) {
  13561. var names = nativeGetOwnPropertyNames(toIndexedObject(O));
  13562. var result = [];
  13563. $forEach(names, function (key) {
  13564. if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
  13565. });
  13566. return result;
  13567. };
  13568. var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
  13569. var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
  13570. var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
  13571. var result = [];
  13572. $forEach(names, function (key) {
  13573. if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
  13574. result.push(AllSymbols[key]);
  13575. }
  13576. });
  13577. return result;
  13578. };
  13579. // `Symbol` constructor
  13580. // https://tc39.github.io/ecma262/#sec-symbol-constructor
  13581. if (!NATIVE_SYMBOL) {
  13582. $Symbol = function Symbol() {
  13583. if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
  13584. var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
  13585. var tag = uid(description);
  13586. var setter = function (value) {
  13587. if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
  13588. if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
  13589. setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
  13590. };
  13591. if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
  13592. return wrap(tag, description);
  13593. };
  13594. redefine($Symbol[PROTOTYPE], 'toString', function toString() {
  13595. return getInternalState(this).tag;
  13596. });
  13597. propertyIsEnumerableModule.f = $propertyIsEnumerable;
  13598. definePropertyModule.f = $defineProperty;
  13599. getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;
  13600. getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;
  13601. getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;
  13602. if (DESCRIPTORS) {
  13603. // https://github.com/tc39/proposal-Symbol-description
  13604. nativeDefineProperty($Symbol[PROTOTYPE], 'description', {
  13605. configurable: true,
  13606. get: function description() {
  13607. return getInternalState(this).description;
  13608. }
  13609. });
  13610. if (!IS_PURE) {
  13611. redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
  13612. }
  13613. }
  13614. wrappedWellKnownSymbolModule.f = function (name) {
  13615. return wrap(wellKnownSymbol(name), name);
  13616. };
  13617. }
  13618. $({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {
  13619. Symbol: $Symbol
  13620. });
  13621. $forEach(objectKeys(WellKnownSymbolsStore), function (name) {
  13622. defineWellKnownSymbol(name);
  13623. });
  13624. $({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {
  13625. // `Symbol.for` method
  13626. // https://tc39.github.io/ecma262/#sec-symbol.for
  13627. 'for': function (key) {
  13628. var string = String(key);
  13629. if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
  13630. var symbol = $Symbol(string);
  13631. StringToSymbolRegistry[string] = symbol;
  13632. SymbolToStringRegistry[symbol] = string;
  13633. return symbol;
  13634. },
  13635. // `Symbol.keyFor` method
  13636. // https://tc39.github.io/ecma262/#sec-symbol.keyfor
  13637. keyFor: function keyFor(sym) {
  13638. if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
  13639. if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
  13640. },
  13641. useSetter: function () { USE_SETTER = true; },
  13642. useSimple: function () { USE_SETTER = false; }
  13643. });
  13644. $({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {
  13645. // `Object.create` method
  13646. // https://tc39.github.io/ecma262/#sec-object.create
  13647. create: $create,
  13648. // `Object.defineProperty` method
  13649. // https://tc39.github.io/ecma262/#sec-object.defineproperty
  13650. defineProperty: $defineProperty,
  13651. // `Object.defineProperties` method
  13652. // https://tc39.github.io/ecma262/#sec-object.defineproperties
  13653. defineProperties: $defineProperties,
  13654. // `Object.getOwnPropertyDescriptor` method
  13655. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
  13656. getOwnPropertyDescriptor: $getOwnPropertyDescriptor
  13657. });
  13658. $({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {
  13659. // `Object.getOwnPropertyNames` method
  13660. // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
  13661. getOwnPropertyNames: $getOwnPropertyNames,
  13662. // `Object.getOwnPropertySymbols` method
  13663. // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
  13664. getOwnPropertySymbols: $getOwnPropertySymbols
  13665. });
  13666. // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
  13667. // https://bugs.chromium.org/p/v8/issues/detail?id=3443
  13668. $({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, {
  13669. getOwnPropertySymbols: function getOwnPropertySymbols(it) {
  13670. return getOwnPropertySymbolsModule.f(toObject(it));
  13671. }
  13672. });
  13673. // `JSON.stringify` method behavior with symbols
  13674. // https://tc39.github.io/ecma262/#sec-json.stringify
  13675. if ($stringify) {
  13676. var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {
  13677. var symbol = $Symbol();
  13678. // MS Edge converts symbol values to JSON as {}
  13679. return $stringify([symbol]) != '[null]'
  13680. // WebKit converts symbol values to JSON as null
  13681. || $stringify({ a: symbol }) != '{}'
  13682. // V8 throws on boxed symbols
  13683. || $stringify(Object(symbol)) != '{}';
  13684. });
  13685. $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {
  13686. // eslint-disable-next-line no-unused-vars
  13687. stringify: function stringify(it, replacer, space) {
  13688. var args = [it];
  13689. var index = 1;
  13690. var $replacer;
  13691. while (arguments.length > index) args.push(arguments[index++]);
  13692. $replacer = replacer;
  13693. if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
  13694. if (!isArray(replacer)) replacer = function (key, value) {
  13695. if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
  13696. if (!isSymbol(value)) return value;
  13697. };
  13698. args[1] = replacer;
  13699. return $stringify.apply(null, args);
  13700. }
  13701. });
  13702. }
  13703. // `Symbol.prototype[@@toPrimitive]` method
  13704. // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
  13705. if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {
  13706. createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
  13707. }
  13708. // `Symbol.prototype[@@toStringTag]` property
  13709. // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
  13710. setToStringTag($Symbol, SYMBOL);
  13711. hiddenKeys[HIDDEN] = true;
  13712. },{"../internals/an-object":55,"../internals/array-iteration":62,"../internals/create-non-enumerable-property":76,"../internals/create-property-descriptor":77,"../internals/define-well-known-symbol":80,"../internals/descriptors":81,"../internals/export":85,"../internals/fails":86,"../internals/get-built-in":90,"../internals/global":92,"../internals/has":93,"../internals/hidden-keys":94,"../internals/internal-state":100,"../internals/is-array":102,"../internals/is-object":105,"../internals/is-pure":106,"../internals/native-symbol":113,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/object-get-own-property-names-external":122,"../internals/object-get-own-property-symbols":124,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/redefine":138,"../internals/set-to-string-tag":145,"../internals/shared":148,"../internals/shared-key":146,"../internals/to-indexed-object":156,"../internals/to-object":159,"../internals/to-primitive":162,"../internals/uid":166,"../internals/well-known-symbol":169,"../internals/wrapped-well-known-symbol":171}],208:[function(require,module,exports){
  13713. 'use strict';
  13714. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13715. var $copyWithin = require('../internals/array-copy-within');
  13716. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13717. // `%TypedArray%.prototype.copyWithin` method
  13718. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin
  13719. ArrayBufferViewCore.exportProto('copyWithin', function copyWithin(target, start /* , end */) {
  13720. return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
  13721. });
  13722. },{"../internals/array-buffer-view-core":56,"../internals/array-copy-within":58}],209:[function(require,module,exports){
  13723. 'use strict';
  13724. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13725. var $every = require('../internals/array-iteration').every;
  13726. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13727. // `%TypedArray%.prototype.every` method
  13728. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every
  13729. ArrayBufferViewCore.exportProto('every', function every(callbackfn /* , thisArg */) {
  13730. return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  13731. });
  13732. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],210:[function(require,module,exports){
  13733. 'use strict';
  13734. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13735. var $fill = require('../internals/array-fill');
  13736. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13737. // `%TypedArray%.prototype.fill` method
  13738. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill
  13739. // eslint-disable-next-line no-unused-vars
  13740. ArrayBufferViewCore.exportProto('fill', function fill(value /* , start, end */) {
  13741. return $fill.apply(aTypedArray(this), arguments);
  13742. });
  13743. },{"../internals/array-buffer-view-core":56,"../internals/array-fill":59}],211:[function(require,module,exports){
  13744. 'use strict';
  13745. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13746. var $filter = require('../internals/array-iteration').filter;
  13747. var speciesConstructor = require('../internals/species-constructor');
  13748. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13749. var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
  13750. // `%TypedArray%.prototype.filter` method
  13751. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter
  13752. ArrayBufferViewCore.exportProto('filter', function filter(callbackfn /* , thisArg */) {
  13753. var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  13754. var C = speciesConstructor(this, this.constructor);
  13755. var index = 0;
  13756. var length = list.length;
  13757. var result = new (aTypedArrayConstructor(C))(length);
  13758. while (length > index) result[index] = list[index++];
  13759. return result;
  13760. });
  13761. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/species-constructor":150}],212:[function(require,module,exports){
  13762. 'use strict';
  13763. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13764. var $findIndex = require('../internals/array-iteration').findIndex;
  13765. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13766. // `%TypedArray%.prototype.findIndex` method
  13767. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex
  13768. ArrayBufferViewCore.exportProto('findIndex', function findIndex(predicate /* , thisArg */) {
  13769. return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
  13770. });
  13771. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],213:[function(require,module,exports){
  13772. 'use strict';
  13773. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13774. var $find = require('../internals/array-iteration').find;
  13775. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13776. // `%TypedArray%.prototype.find` method
  13777. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find
  13778. ArrayBufferViewCore.exportProto('find', function find(predicate /* , thisArg */) {
  13779. return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
  13780. });
  13781. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],214:[function(require,module,exports){
  13782. var typedArrayConstructor = require('../internals/typed-array-constructor');
  13783. // `Float32Array` constructor
  13784. // https://tc39.github.io/ecma262/#sec-typedarray-objects
  13785. typedArrayConstructor('Float32', 4, function (init) {
  13786. return function Float32Array(data, byteOffset, length) {
  13787. return init(this, data, byteOffset, length);
  13788. };
  13789. });
  13790. },{"../internals/typed-array-constructor":163}],215:[function(require,module,exports){
  13791. var typedArrayConstructor = require('../internals/typed-array-constructor');
  13792. // `Float64Array` constructor
  13793. // https://tc39.github.io/ecma262/#sec-typedarray-objects
  13794. typedArrayConstructor('Float64', 8, function (init) {
  13795. return function Float64Array(data, byteOffset, length) {
  13796. return init(this, data, byteOffset, length);
  13797. };
  13798. });
  13799. },{"../internals/typed-array-constructor":163}],216:[function(require,module,exports){
  13800. 'use strict';
  13801. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13802. var $forEach = require('../internals/array-iteration').forEach;
  13803. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13804. // `%TypedArray%.prototype.forEach` method
  13805. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach
  13806. ArrayBufferViewCore.exportProto('forEach', function forEach(callbackfn /* , thisArg */) {
  13807. $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  13808. });
  13809. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],217:[function(require,module,exports){
  13810. 'use strict';
  13811. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13812. var $includes = require('../internals/array-includes').includes;
  13813. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13814. // `%TypedArray%.prototype.includes` method
  13815. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes
  13816. ArrayBufferViewCore.exportProto('includes', function includes(searchElement /* , fromIndex */) {
  13817. return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
  13818. });
  13819. },{"../internals/array-buffer-view-core":56,"../internals/array-includes":61}],218:[function(require,module,exports){
  13820. 'use strict';
  13821. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13822. var $indexOf = require('../internals/array-includes').indexOf;
  13823. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13824. // `%TypedArray%.prototype.indexOf` method
  13825. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof
  13826. ArrayBufferViewCore.exportProto('indexOf', function indexOf(searchElement /* , fromIndex */) {
  13827. return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
  13828. });
  13829. },{"../internals/array-buffer-view-core":56,"../internals/array-includes":61}],219:[function(require,module,exports){
  13830. 'use strict';
  13831. var global = require('../internals/global');
  13832. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13833. var ArrayIterators = require('../modules/es.array.iterator');
  13834. var wellKnownSymbol = require('../internals/well-known-symbol');
  13835. var ITERATOR = wellKnownSymbol('iterator');
  13836. var Uint8Array = global.Uint8Array;
  13837. var arrayValues = ArrayIterators.values;
  13838. var arrayKeys = ArrayIterators.keys;
  13839. var arrayEntries = ArrayIterators.entries;
  13840. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13841. var exportProto = ArrayBufferViewCore.exportProto;
  13842. var nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR];
  13843. var CORRECT_ITER_NAME = !!nativeTypedArrayIterator
  13844. && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined);
  13845. var typedArrayValues = function values() {
  13846. return arrayValues.call(aTypedArray(this));
  13847. };
  13848. // `%TypedArray%.prototype.entries` method
  13849. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries
  13850. exportProto('entries', function entries() {
  13851. return arrayEntries.call(aTypedArray(this));
  13852. });
  13853. // `%TypedArray%.prototype.keys` method
  13854. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys
  13855. exportProto('keys', function keys() {
  13856. return arrayKeys.call(aTypedArray(this));
  13857. });
  13858. // `%TypedArray%.prototype.values` method
  13859. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values
  13860. exportProto('values', typedArrayValues, !CORRECT_ITER_NAME);
  13861. // `%TypedArray%.prototype[@@iterator]` method
  13862. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator
  13863. exportProto(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME);
  13864. },{"../internals/array-buffer-view-core":56,"../internals/global":92,"../internals/well-known-symbol":169,"../modules/es.array.iterator":182}],220:[function(require,module,exports){
  13865. 'use strict';
  13866. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13867. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13868. var $join = [].join;
  13869. // `%TypedArray%.prototype.join` method
  13870. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join
  13871. // eslint-disable-next-line no-unused-vars
  13872. ArrayBufferViewCore.exportProto('join', function join(separator) {
  13873. return $join.apply(aTypedArray(this), arguments);
  13874. });
  13875. },{"../internals/array-buffer-view-core":56}],221:[function(require,module,exports){
  13876. 'use strict';
  13877. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13878. var $lastIndexOf = require('../internals/array-last-index-of');
  13879. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13880. // `%TypedArray%.prototype.lastIndexOf` method
  13881. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof
  13882. // eslint-disable-next-line no-unused-vars
  13883. ArrayBufferViewCore.exportProto('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) {
  13884. return $lastIndexOf.apply(aTypedArray(this), arguments);
  13885. });
  13886. },{"../internals/array-buffer-view-core":56,"../internals/array-last-index-of":63}],222:[function(require,module,exports){
  13887. 'use strict';
  13888. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13889. var $map = require('../internals/array-iteration').map;
  13890. var speciesConstructor = require('../internals/species-constructor');
  13891. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13892. var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
  13893. // `%TypedArray%.prototype.map` method
  13894. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map
  13895. ArrayBufferViewCore.exportProto('map', function map(mapfn /* , thisArg */) {
  13896. return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {
  13897. return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor)))(length);
  13898. });
  13899. });
  13900. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/species-constructor":150}],223:[function(require,module,exports){
  13901. 'use strict';
  13902. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13903. var $reduceRight = require('../internals/array-reduce').right;
  13904. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13905. // `%TypedArray%.prototype.reduceRicht` method
  13906. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright
  13907. ArrayBufferViewCore.exportProto('reduceRight', function reduceRight(callbackfn /* , initialValue */) {
  13908. return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
  13909. });
  13910. },{"../internals/array-buffer-view-core":56,"../internals/array-reduce":65}],224:[function(require,module,exports){
  13911. 'use strict';
  13912. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13913. var $reduce = require('../internals/array-reduce').left;
  13914. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13915. // `%TypedArray%.prototype.reduce` method
  13916. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce
  13917. ArrayBufferViewCore.exportProto('reduce', function reduce(callbackfn /* , initialValue */) {
  13918. return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
  13919. });
  13920. },{"../internals/array-buffer-view-core":56,"../internals/array-reduce":65}],225:[function(require,module,exports){
  13921. 'use strict';
  13922. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13923. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13924. var floor = Math.floor;
  13925. // `%TypedArray%.prototype.reverse` method
  13926. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse
  13927. ArrayBufferViewCore.exportProto('reverse', function reverse() {
  13928. var that = this;
  13929. var length = aTypedArray(that).length;
  13930. var middle = floor(length / 2);
  13931. var index = 0;
  13932. var value;
  13933. while (index < middle) {
  13934. value = that[index];
  13935. that[index++] = that[--length];
  13936. that[length] = value;
  13937. } return that;
  13938. });
  13939. },{"../internals/array-buffer-view-core":56}],226:[function(require,module,exports){
  13940. 'use strict';
  13941. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13942. var toLength = require('../internals/to-length');
  13943. var toOffset = require('../internals/to-offset');
  13944. var toObject = require('../internals/to-object');
  13945. var fails = require('../internals/fails');
  13946. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13947. var FORCED = fails(function () {
  13948. // eslint-disable-next-line no-undef
  13949. new Int8Array(1).set({});
  13950. });
  13951. // `%TypedArray%.prototype.set` method
  13952. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set
  13953. ArrayBufferViewCore.exportProto('set', function set(arrayLike /* , offset */) {
  13954. aTypedArray(this);
  13955. var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
  13956. var length = this.length;
  13957. var src = toObject(arrayLike);
  13958. var len = toLength(src.length);
  13959. var index = 0;
  13960. if (len + offset > length) throw RangeError('Wrong length');
  13961. while (index < len) this[offset + index] = src[index++];
  13962. }, FORCED);
  13963. },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/to-length":158,"../internals/to-object":159,"../internals/to-offset":160}],227:[function(require,module,exports){
  13964. 'use strict';
  13965. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13966. var speciesConstructor = require('../internals/species-constructor');
  13967. var fails = require('../internals/fails');
  13968. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13969. var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
  13970. var $slice = [].slice;
  13971. var FORCED = fails(function () {
  13972. // eslint-disable-next-line no-undef
  13973. new Int8Array(1).slice();
  13974. });
  13975. // `%TypedArray%.prototype.slice` method
  13976. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice
  13977. ArrayBufferViewCore.exportProto('slice', function slice(start, end) {
  13978. var list = $slice.call(aTypedArray(this), start, end);
  13979. var C = speciesConstructor(this, this.constructor);
  13980. var index = 0;
  13981. var length = list.length;
  13982. var result = new (aTypedArrayConstructor(C))(length);
  13983. while (length > index) result[index] = list[index++];
  13984. return result;
  13985. }, FORCED);
  13986. },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/species-constructor":150}],228:[function(require,module,exports){
  13987. 'use strict';
  13988. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13989. var $some = require('../internals/array-iteration').some;
  13990. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  13991. // `%TypedArray%.prototype.some` method
  13992. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some
  13993. ArrayBufferViewCore.exportProto('some', function some(callbackfn /* , thisArg */) {
  13994. return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  13995. });
  13996. },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],229:[function(require,module,exports){
  13997. 'use strict';
  13998. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  13999. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  14000. var $sort = [].sort;
  14001. // `%TypedArray%.prototype.sort` method
  14002. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort
  14003. ArrayBufferViewCore.exportProto('sort', function sort(comparefn) {
  14004. return $sort.call(aTypedArray(this), comparefn);
  14005. });
  14006. },{"../internals/array-buffer-view-core":56}],230:[function(require,module,exports){
  14007. 'use strict';
  14008. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  14009. var toLength = require('../internals/to-length');
  14010. var toAbsoluteIndex = require('../internals/to-absolute-index');
  14011. var speciesConstructor = require('../internals/species-constructor');
  14012. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  14013. // `%TypedArray%.prototype.subarray` method
  14014. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray
  14015. ArrayBufferViewCore.exportProto('subarray', function subarray(begin, end) {
  14016. var O = aTypedArray(this);
  14017. var length = O.length;
  14018. var beginIndex = toAbsoluteIndex(begin, length);
  14019. return new (speciesConstructor(O, O.constructor))(
  14020. O.buffer,
  14021. O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT,
  14022. toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)
  14023. );
  14024. });
  14025. },{"../internals/array-buffer-view-core":56,"../internals/species-constructor":150,"../internals/to-absolute-index":154,"../internals/to-length":158}],231:[function(require,module,exports){
  14026. 'use strict';
  14027. var global = require('../internals/global');
  14028. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  14029. var fails = require('../internals/fails');
  14030. var Int8Array = global.Int8Array;
  14031. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  14032. var $toLocaleString = [].toLocaleString;
  14033. var $slice = [].slice;
  14034. // iOS Safari 6.x fails here
  14035. var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {
  14036. $toLocaleString.call(new Int8Array(1));
  14037. });
  14038. var FORCED = fails(function () {
  14039. return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();
  14040. }) || !fails(function () {
  14041. Int8Array.prototype.toLocaleString.call([1, 2]);
  14042. });
  14043. // `%TypedArray%.prototype.toLocaleString` method
  14044. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring
  14045. ArrayBufferViewCore.exportProto('toLocaleString', function toLocaleString() {
  14046. return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
  14047. }, FORCED);
  14048. },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/global":92}],232:[function(require,module,exports){
  14049. 'use strict';
  14050. var global = require('../internals/global');
  14051. var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
  14052. var fails = require('../internals/fails');
  14053. var Uint8Array = global.Uint8Array;
  14054. var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype;
  14055. var arrayToString = [].toString;
  14056. var arrayJoin = [].join;
  14057. if (fails(function () { arrayToString.call({}); })) {
  14058. arrayToString = function toString() {
  14059. return arrayJoin.call(this);
  14060. };
  14061. }
  14062. // `%TypedArray%.prototype.toString` method
  14063. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring
  14064. ArrayBufferViewCore.exportProto('toString', arrayToString, (Uint8ArrayPrototype || {}).toString != arrayToString);
  14065. },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/global":92}],233:[function(require,module,exports){
  14066. var typedArrayConstructor = require('../internals/typed-array-constructor');
  14067. // `Uint8Array` constructor
  14068. // https://tc39.github.io/ecma262/#sec-typedarray-objects
  14069. typedArrayConstructor('Uint8', 1, function (init) {
  14070. return function Uint8Array(data, byteOffset, length) {
  14071. return init(this, data, byteOffset, length);
  14072. };
  14073. });
  14074. },{"../internals/typed-array-constructor":163}],234:[function(require,module,exports){
  14075. var typedArrayConstructor = require('../internals/typed-array-constructor');
  14076. // `Uint8ClampedArray` constructor
  14077. // https://tc39.github.io/ecma262/#sec-typedarray-objects
  14078. typedArrayConstructor('Uint8', 1, function (init) {
  14079. return function Uint8ClampedArray(data, byteOffset, length) {
  14080. return init(this, data, byteOffset, length);
  14081. };
  14082. }, true);
  14083. },{"../internals/typed-array-constructor":163}],235:[function(require,module,exports){
  14084. var global = require('../internals/global');
  14085. var DOMIterables = require('../internals/dom-iterables');
  14086. var forEach = require('../internals/array-for-each');
  14087. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  14088. for (var COLLECTION_NAME in DOMIterables) {
  14089. var Collection = global[COLLECTION_NAME];
  14090. var CollectionPrototype = Collection && Collection.prototype;
  14091. // some Chrome versions have non-configurable methods on DOMTokenList
  14092. if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
  14093. createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach);
  14094. } catch (error) {
  14095. CollectionPrototype.forEach = forEach;
  14096. }
  14097. }
  14098. },{"../internals/array-for-each":60,"../internals/create-non-enumerable-property":76,"../internals/dom-iterables":83,"../internals/global":92}],236:[function(require,module,exports){
  14099. var global = require('../internals/global');
  14100. var DOMIterables = require('../internals/dom-iterables');
  14101. var ArrayIteratorMethods = require('../modules/es.array.iterator');
  14102. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  14103. var wellKnownSymbol = require('../internals/well-known-symbol');
  14104. var ITERATOR = wellKnownSymbol('iterator');
  14105. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  14106. var ArrayValues = ArrayIteratorMethods.values;
  14107. for (var COLLECTION_NAME in DOMIterables) {
  14108. var Collection = global[COLLECTION_NAME];
  14109. var CollectionPrototype = Collection && Collection.prototype;
  14110. if (CollectionPrototype) {
  14111. // some Chrome versions have non-configurable methods on DOMTokenList
  14112. if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
  14113. createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
  14114. } catch (error) {
  14115. CollectionPrototype[ITERATOR] = ArrayValues;
  14116. }
  14117. if (!CollectionPrototype[TO_STRING_TAG]) {
  14118. createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
  14119. }
  14120. if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
  14121. // some Chrome versions have non-configurable methods on DOMTokenList
  14122. if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
  14123. createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
  14124. } catch (error) {
  14125. CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
  14126. }
  14127. }
  14128. }
  14129. }
  14130. },{"../internals/create-non-enumerable-property":76,"../internals/dom-iterables":83,"../internals/global":92,"../internals/well-known-symbol":169,"../modules/es.array.iterator":182}],237:[function(require,module,exports){
  14131. var $ = require('../internals/export');
  14132. var global = require('../internals/global');
  14133. var userAgent = require('../internals/user-agent');
  14134. var slice = [].slice;
  14135. var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check
  14136. var wrap = function (scheduler) {
  14137. return function (handler, timeout /* , ...arguments */) {
  14138. var boundArgs = arguments.length > 2;
  14139. var args = boundArgs ? slice.call(arguments, 2) : undefined;
  14140. return scheduler(boundArgs ? function () {
  14141. // eslint-disable-next-line no-new-func
  14142. (typeof handler == 'function' ? handler : Function(handler)).apply(this, args);
  14143. } : handler, timeout);
  14144. };
  14145. };
  14146. // ie9- setTimeout & setInterval additional parameters fix
  14147. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
  14148. $({ global: true, bind: true, forced: MSIE }, {
  14149. // `setTimeout` method
  14150. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  14151. setTimeout: wrap(global.setTimeout),
  14152. // `setInterval` method
  14153. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  14154. setInterval: wrap(global.setInterval)
  14155. });
  14156. },{"../internals/export":85,"../internals/global":92,"../internals/user-agent":167}],238:[function(require,module,exports){
  14157. (function (Buffer){
  14158. // Copyright Joyent, Inc. and other Node contributors.
  14159. //
  14160. // Permission is hereby granted, free of charge, to any person obtaining a
  14161. // copy of this software and associated documentation files (the
  14162. // "Software"), to deal in the Software without restriction, including
  14163. // without limitation the rights to use, copy, modify, merge, publish,
  14164. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14165. // persons to whom the Software is furnished to do so, subject to the
  14166. // following conditions:
  14167. //
  14168. // The above copyright notice and this permission notice shall be included
  14169. // in all copies or substantial portions of the Software.
  14170. //
  14171. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14172. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14173. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14174. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14175. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14176. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14177. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14178. // NOTE: These type checking functions intentionally don't use `instanceof`
  14179. // because it is fragile and can be easily faked with `Object.create()`.
  14180. function isArray(arg) {
  14181. if (Array.isArray) {
  14182. return Array.isArray(arg);
  14183. }
  14184. return objectToString(arg) === '[object Array]';
  14185. }
  14186. exports.isArray = isArray;
  14187. function isBoolean(arg) {
  14188. return typeof arg === 'boolean';
  14189. }
  14190. exports.isBoolean = isBoolean;
  14191. function isNull(arg) {
  14192. return arg === null;
  14193. }
  14194. exports.isNull = isNull;
  14195. function isNullOrUndefined(arg) {
  14196. return arg == null;
  14197. }
  14198. exports.isNullOrUndefined = isNullOrUndefined;
  14199. function isNumber(arg) {
  14200. return typeof arg === 'number';
  14201. }
  14202. exports.isNumber = isNumber;
  14203. function isString(arg) {
  14204. return typeof arg === 'string';
  14205. }
  14206. exports.isString = isString;
  14207. function isSymbol(arg) {
  14208. return typeof arg === 'symbol';
  14209. }
  14210. exports.isSymbol = isSymbol;
  14211. function isUndefined(arg) {
  14212. return arg === void 0;
  14213. }
  14214. exports.isUndefined = isUndefined;
  14215. function isRegExp(re) {
  14216. return objectToString(re) === '[object RegExp]';
  14217. }
  14218. exports.isRegExp = isRegExp;
  14219. function isObject(arg) {
  14220. return typeof arg === 'object' && arg !== null;
  14221. }
  14222. exports.isObject = isObject;
  14223. function isDate(d) {
  14224. return objectToString(d) === '[object Date]';
  14225. }
  14226. exports.isDate = isDate;
  14227. function isError(e) {
  14228. return (objectToString(e) === '[object Error]' || e instanceof Error);
  14229. }
  14230. exports.isError = isError;
  14231. function isFunction(arg) {
  14232. return typeof arg === 'function';
  14233. }
  14234. exports.isFunction = isFunction;
  14235. function isPrimitive(arg) {
  14236. return arg === null ||
  14237. typeof arg === 'boolean' ||
  14238. typeof arg === 'number' ||
  14239. typeof arg === 'string' ||
  14240. typeof arg === 'symbol' || // ES6 symbol
  14241. typeof arg === 'undefined';
  14242. }
  14243. exports.isPrimitive = isPrimitive;
  14244. exports.isBuffer = Buffer.isBuffer;
  14245. function objectToString(o) {
  14246. return Object.prototype.toString.call(o);
  14247. }
  14248. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  14249. },{"../../is-buffer/index.js":255}],239:[function(require,module,exports){
  14250. // Copyright Joyent, Inc. and other Node contributors.
  14251. //
  14252. // Permission is hereby granted, free of charge, to any person obtaining a
  14253. // copy of this software and associated documentation files (the
  14254. // "Software"), to deal in the Software without restriction, including
  14255. // without limitation the rights to use, copy, modify, merge, publish,
  14256. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14257. // persons to whom the Software is furnished to do so, subject to the
  14258. // following conditions:
  14259. //
  14260. // The above copyright notice and this permission notice shall be included
  14261. // in all copies or substantial portions of the Software.
  14262. //
  14263. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14264. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14265. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14266. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14267. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14268. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14269. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14270. var objectCreate = Object.create || objectCreatePolyfill
  14271. var objectKeys = Object.keys || objectKeysPolyfill
  14272. var bind = Function.prototype.bind || functionBindPolyfill
  14273. function EventEmitter() {
  14274. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  14275. this._events = objectCreate(null);
  14276. this._eventsCount = 0;
  14277. }
  14278. this._maxListeners = this._maxListeners || undefined;
  14279. }
  14280. module.exports = EventEmitter;
  14281. // Backwards-compat with node 0.10.x
  14282. EventEmitter.EventEmitter = EventEmitter;
  14283. EventEmitter.prototype._events = undefined;
  14284. EventEmitter.prototype._maxListeners = undefined;
  14285. // By default EventEmitters will print a warning if more than 10 listeners are
  14286. // added to it. This is a useful default which helps finding memory leaks.
  14287. var defaultMaxListeners = 10;
  14288. var hasDefineProperty;
  14289. try {
  14290. var o = {};
  14291. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  14292. hasDefineProperty = o.x === 0;
  14293. } catch (err) { hasDefineProperty = false }
  14294. if (hasDefineProperty) {
  14295. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  14296. enumerable: true,
  14297. get: function() {
  14298. return defaultMaxListeners;
  14299. },
  14300. set: function(arg) {
  14301. // check whether the input is a positive number (whose value is zero or
  14302. // greater and not a NaN).
  14303. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  14304. throw new TypeError('"defaultMaxListeners" must be a positive number');
  14305. defaultMaxListeners = arg;
  14306. }
  14307. });
  14308. } else {
  14309. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  14310. }
  14311. // Obviously not all Emitters should be limited to 10. This function allows
  14312. // that to be increased. Set to zero for unlimited.
  14313. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  14314. if (typeof n !== 'number' || n < 0 || isNaN(n))
  14315. throw new TypeError('"n" argument must be a positive number');
  14316. this._maxListeners = n;
  14317. return this;
  14318. };
  14319. function $getMaxListeners(that) {
  14320. if (that._maxListeners === undefined)
  14321. return EventEmitter.defaultMaxListeners;
  14322. return that._maxListeners;
  14323. }
  14324. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  14325. return $getMaxListeners(this);
  14326. };
  14327. // These standalone emit* functions are used to optimize calling of event
  14328. // handlers for fast cases because emit() itself often has a variable number of
  14329. // arguments and can be deoptimized because of that. These functions always have
  14330. // the same number of arguments and thus do not get deoptimized, so the code
  14331. // inside them can execute faster.
  14332. function emitNone(handler, isFn, self) {
  14333. if (isFn)
  14334. handler.call(self);
  14335. else {
  14336. var len = handler.length;
  14337. var listeners = arrayClone(handler, len);
  14338. for (var i = 0; i < len; ++i)
  14339. listeners[i].call(self);
  14340. }
  14341. }
  14342. function emitOne(handler, isFn, self, arg1) {
  14343. if (isFn)
  14344. handler.call(self, arg1);
  14345. else {
  14346. var len = handler.length;
  14347. var listeners = arrayClone(handler, len);
  14348. for (var i = 0; i < len; ++i)
  14349. listeners[i].call(self, arg1);
  14350. }
  14351. }
  14352. function emitTwo(handler, isFn, self, arg1, arg2) {
  14353. if (isFn)
  14354. handler.call(self, arg1, arg2);
  14355. else {
  14356. var len = handler.length;
  14357. var listeners = arrayClone(handler, len);
  14358. for (var i = 0; i < len; ++i)
  14359. listeners[i].call(self, arg1, arg2);
  14360. }
  14361. }
  14362. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  14363. if (isFn)
  14364. handler.call(self, arg1, arg2, arg3);
  14365. else {
  14366. var len = handler.length;
  14367. var listeners = arrayClone(handler, len);
  14368. for (var i = 0; i < len; ++i)
  14369. listeners[i].call(self, arg1, arg2, arg3);
  14370. }
  14371. }
  14372. function emitMany(handler, isFn, self, args) {
  14373. if (isFn)
  14374. handler.apply(self, args);
  14375. else {
  14376. var len = handler.length;
  14377. var listeners = arrayClone(handler, len);
  14378. for (var i = 0; i < len; ++i)
  14379. listeners[i].apply(self, args);
  14380. }
  14381. }
  14382. EventEmitter.prototype.emit = function emit(type) {
  14383. var er, handler, len, args, i, events;
  14384. var doError = (type === 'error');
  14385. events = this._events;
  14386. if (events)
  14387. doError = (doError && events.error == null);
  14388. else if (!doError)
  14389. return false;
  14390. // If there is no 'error' event listener then throw.
  14391. if (doError) {
  14392. if (arguments.length > 1)
  14393. er = arguments[1];
  14394. if (er instanceof Error) {
  14395. throw er; // Unhandled 'error' event
  14396. } else {
  14397. // At least give some kind of context to the user
  14398. var err = new Error('Unhandled "error" event. (' + er + ')');
  14399. err.context = er;
  14400. throw err;
  14401. }
  14402. return false;
  14403. }
  14404. handler = events[type];
  14405. if (!handler)
  14406. return false;
  14407. var isFn = typeof handler === 'function';
  14408. len = arguments.length;
  14409. switch (len) {
  14410. // fast cases
  14411. case 1:
  14412. emitNone(handler, isFn, this);
  14413. break;
  14414. case 2:
  14415. emitOne(handler, isFn, this, arguments[1]);
  14416. break;
  14417. case 3:
  14418. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  14419. break;
  14420. case 4:
  14421. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  14422. break;
  14423. // slower
  14424. default:
  14425. args = new Array(len - 1);
  14426. for (i = 1; i < len; i++)
  14427. args[i - 1] = arguments[i];
  14428. emitMany(handler, isFn, this, args);
  14429. }
  14430. return true;
  14431. };
  14432. function _addListener(target, type, listener, prepend) {
  14433. var m;
  14434. var events;
  14435. var existing;
  14436. if (typeof listener !== 'function')
  14437. throw new TypeError('"listener" argument must be a function');
  14438. events = target._events;
  14439. if (!events) {
  14440. events = target._events = objectCreate(null);
  14441. target._eventsCount = 0;
  14442. } else {
  14443. // To avoid recursion in the case that type === "newListener"! Before
  14444. // adding it to the listeners, first emit "newListener".
  14445. if (events.newListener) {
  14446. target.emit('newListener', type,
  14447. listener.listener ? listener.listener : listener);
  14448. // Re-assign `events` because a newListener handler could have caused the
  14449. // this._events to be assigned to a new object
  14450. events = target._events;
  14451. }
  14452. existing = events[type];
  14453. }
  14454. if (!existing) {
  14455. // Optimize the case of one listener. Don't need the extra array object.
  14456. existing = events[type] = listener;
  14457. ++target._eventsCount;
  14458. } else {
  14459. if (typeof existing === 'function') {
  14460. // Adding the second element, need to change to array.
  14461. existing = events[type] =
  14462. prepend ? [listener, existing] : [existing, listener];
  14463. } else {
  14464. // If we've already got an array, just append.
  14465. if (prepend) {
  14466. existing.unshift(listener);
  14467. } else {
  14468. existing.push(listener);
  14469. }
  14470. }
  14471. // Check for listener leak
  14472. if (!existing.warned) {
  14473. m = $getMaxListeners(target);
  14474. if (m && m > 0 && existing.length > m) {
  14475. existing.warned = true;
  14476. var w = new Error('Possible EventEmitter memory leak detected. ' +
  14477. existing.length + ' "' + String(type) + '" listeners ' +
  14478. 'added. Use emitter.setMaxListeners() to ' +
  14479. 'increase limit.');
  14480. w.name = 'MaxListenersExceededWarning';
  14481. w.emitter = target;
  14482. w.type = type;
  14483. w.count = existing.length;
  14484. if (typeof console === 'object' && console.warn) {
  14485. console.warn('%s: %s', w.name, w.message);
  14486. }
  14487. }
  14488. }
  14489. }
  14490. return target;
  14491. }
  14492. EventEmitter.prototype.addListener = function addListener(type, listener) {
  14493. return _addListener(this, type, listener, false);
  14494. };
  14495. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  14496. EventEmitter.prototype.prependListener =
  14497. function prependListener(type, listener) {
  14498. return _addListener(this, type, listener, true);
  14499. };
  14500. function onceWrapper() {
  14501. if (!this.fired) {
  14502. this.target.removeListener(this.type, this.wrapFn);
  14503. this.fired = true;
  14504. switch (arguments.length) {
  14505. case 0:
  14506. return this.listener.call(this.target);
  14507. case 1:
  14508. return this.listener.call(this.target, arguments[0]);
  14509. case 2:
  14510. return this.listener.call(this.target, arguments[0], arguments[1]);
  14511. case 3:
  14512. return this.listener.call(this.target, arguments[0], arguments[1],
  14513. arguments[2]);
  14514. default:
  14515. var args = new Array(arguments.length);
  14516. for (var i = 0; i < args.length; ++i)
  14517. args[i] = arguments[i];
  14518. this.listener.apply(this.target, args);
  14519. }
  14520. }
  14521. }
  14522. function _onceWrap(target, type, listener) {
  14523. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  14524. var wrapped = bind.call(onceWrapper, state);
  14525. wrapped.listener = listener;
  14526. state.wrapFn = wrapped;
  14527. return wrapped;
  14528. }
  14529. EventEmitter.prototype.once = function once(type, listener) {
  14530. if (typeof listener !== 'function')
  14531. throw new TypeError('"listener" argument must be a function');
  14532. this.on(type, _onceWrap(this, type, listener));
  14533. return this;
  14534. };
  14535. EventEmitter.prototype.prependOnceListener =
  14536. function prependOnceListener(type, listener) {
  14537. if (typeof listener !== 'function')
  14538. throw new TypeError('"listener" argument must be a function');
  14539. this.prependListener(type, _onceWrap(this, type, listener));
  14540. return this;
  14541. };
  14542. // Emits a 'removeListener' event if and only if the listener was removed.
  14543. EventEmitter.prototype.removeListener =
  14544. function removeListener(type, listener) {
  14545. var list, events, position, i, originalListener;
  14546. if (typeof listener !== 'function')
  14547. throw new TypeError('"listener" argument must be a function');
  14548. events = this._events;
  14549. if (!events)
  14550. return this;
  14551. list = events[type];
  14552. if (!list)
  14553. return this;
  14554. if (list === listener || list.listener === listener) {
  14555. if (--this._eventsCount === 0)
  14556. this._events = objectCreate(null);
  14557. else {
  14558. delete events[type];
  14559. if (events.removeListener)
  14560. this.emit('removeListener', type, list.listener || listener);
  14561. }
  14562. } else if (typeof list !== 'function') {
  14563. position = -1;
  14564. for (i = list.length - 1; i >= 0; i--) {
  14565. if (list[i] === listener || list[i].listener === listener) {
  14566. originalListener = list[i].listener;
  14567. position = i;
  14568. break;
  14569. }
  14570. }
  14571. if (position < 0)
  14572. return this;
  14573. if (position === 0)
  14574. list.shift();
  14575. else
  14576. spliceOne(list, position);
  14577. if (list.length === 1)
  14578. events[type] = list[0];
  14579. if (events.removeListener)
  14580. this.emit('removeListener', type, originalListener || listener);
  14581. }
  14582. return this;
  14583. };
  14584. EventEmitter.prototype.removeAllListeners =
  14585. function removeAllListeners(type) {
  14586. var listeners, events, i;
  14587. events = this._events;
  14588. if (!events)
  14589. return this;
  14590. // not listening for removeListener, no need to emit
  14591. if (!events.removeListener) {
  14592. if (arguments.length === 0) {
  14593. this._events = objectCreate(null);
  14594. this._eventsCount = 0;
  14595. } else if (events[type]) {
  14596. if (--this._eventsCount === 0)
  14597. this._events = objectCreate(null);
  14598. else
  14599. delete events[type];
  14600. }
  14601. return this;
  14602. }
  14603. // emit removeListener for all listeners on all events
  14604. if (arguments.length === 0) {
  14605. var keys = objectKeys(events);
  14606. var key;
  14607. for (i = 0; i < keys.length; ++i) {
  14608. key = keys[i];
  14609. if (key === 'removeListener') continue;
  14610. this.removeAllListeners(key);
  14611. }
  14612. this.removeAllListeners('removeListener');
  14613. this._events = objectCreate(null);
  14614. this._eventsCount = 0;
  14615. return this;
  14616. }
  14617. listeners = events[type];
  14618. if (typeof listeners === 'function') {
  14619. this.removeListener(type, listeners);
  14620. } else if (listeners) {
  14621. // LIFO order
  14622. for (i = listeners.length - 1; i >= 0; i--) {
  14623. this.removeListener(type, listeners[i]);
  14624. }
  14625. }
  14626. return this;
  14627. };
  14628. function _listeners(target, type, unwrap) {
  14629. var events = target._events;
  14630. if (!events)
  14631. return [];
  14632. var evlistener = events[type];
  14633. if (!evlistener)
  14634. return [];
  14635. if (typeof evlistener === 'function')
  14636. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  14637. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  14638. }
  14639. EventEmitter.prototype.listeners = function listeners(type) {
  14640. return _listeners(this, type, true);
  14641. };
  14642. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  14643. return _listeners(this, type, false);
  14644. };
  14645. EventEmitter.listenerCount = function(emitter, type) {
  14646. if (typeof emitter.listenerCount === 'function') {
  14647. return emitter.listenerCount(type);
  14648. } else {
  14649. return listenerCount.call(emitter, type);
  14650. }
  14651. };
  14652. EventEmitter.prototype.listenerCount = listenerCount;
  14653. function listenerCount(type) {
  14654. var events = this._events;
  14655. if (events) {
  14656. var evlistener = events[type];
  14657. if (typeof evlistener === 'function') {
  14658. return 1;
  14659. } else if (evlistener) {
  14660. return evlistener.length;
  14661. }
  14662. }
  14663. return 0;
  14664. }
  14665. EventEmitter.prototype.eventNames = function eventNames() {
  14666. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  14667. };
  14668. // About 1.5x faster than the two-arg version of Array#splice().
  14669. function spliceOne(list, index) {
  14670. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  14671. list[i] = list[k];
  14672. list.pop();
  14673. }
  14674. function arrayClone(arr, n) {
  14675. var copy = new Array(n);
  14676. for (var i = 0; i < n; ++i)
  14677. copy[i] = arr[i];
  14678. return copy;
  14679. }
  14680. function unwrapListeners(arr) {
  14681. var ret = new Array(arr.length);
  14682. for (var i = 0; i < ret.length; ++i) {
  14683. ret[i] = arr[i].listener || arr[i];
  14684. }
  14685. return ret;
  14686. }
  14687. function objectCreatePolyfill(proto) {
  14688. var F = function() {};
  14689. F.prototype = proto;
  14690. return new F;
  14691. }
  14692. function objectKeysPolyfill(obj) {
  14693. var keys = [];
  14694. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  14695. keys.push(k);
  14696. }
  14697. return k;
  14698. }
  14699. function functionBindPolyfill(context) {
  14700. var fn = this;
  14701. return function () {
  14702. return fn.apply(context, arguments);
  14703. };
  14704. }
  14705. },{}],240:[function(require,module,exports){
  14706. var Parser = require('./lib/parser');
  14707. function getGlobal() {
  14708. return (1,eval)('this');
  14709. }
  14710. module.exports = {
  14711. create: function(buffer, global) {
  14712. global = global || getGlobal();
  14713. if(buffer instanceof global.ArrayBuffer) {
  14714. var DOMBufferStream = require('./lib/dom-bufferstream');
  14715. return new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global));
  14716. } else {
  14717. var NodeBufferStream = require('./lib/bufferstream');
  14718. return new Parser(new NodeBufferStream(buffer, 0, buffer.length, true));
  14719. }
  14720. }
  14721. };
  14722. },{"./lib/bufferstream":241,"./lib/dom-bufferstream":243,"./lib/parser":247}],241:[function(require,module,exports){
  14723. function BufferStream(buffer, offset, length, bigEndian) {
  14724. this.buffer = buffer;
  14725. this.offset = offset || 0;
  14726. length = typeof length === 'number' ? length : buffer.length;
  14727. this.endPosition = this.offset + length;
  14728. this.setBigEndian(bigEndian);
  14729. }
  14730. BufferStream.prototype = {
  14731. setBigEndian: function(bigEndian) {
  14732. this.bigEndian = !!bigEndian;
  14733. },
  14734. nextUInt8: function() {
  14735. var value = this.buffer.readUInt8(this.offset);
  14736. this.offset += 1;
  14737. return value;
  14738. },
  14739. nextInt8: function() {
  14740. var value = this.buffer.readInt8(this.offset);
  14741. this.offset += 1;
  14742. return value;
  14743. },
  14744. nextUInt16: function() {
  14745. var value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);
  14746. this.offset += 2;
  14747. return value;
  14748. },
  14749. nextUInt32: function() {
  14750. var value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);
  14751. this.offset += 4;
  14752. return value;
  14753. },
  14754. nextInt16: function() {
  14755. var value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);
  14756. this.offset += 2;
  14757. return value;
  14758. },
  14759. nextInt32: function() {
  14760. var value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);
  14761. this.offset += 4;
  14762. return value;
  14763. },
  14764. nextFloat: function() {
  14765. var value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);
  14766. this.offset += 4;
  14767. return value;
  14768. },
  14769. nextDouble: function() {
  14770. var value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);
  14771. this.offset += 8;
  14772. return value;
  14773. },
  14774. nextBuffer: function(length) {
  14775. var value = this.buffer.slice(this.offset, this.offset + length);
  14776. this.offset += length;
  14777. return value;
  14778. },
  14779. remainingLength: function() {
  14780. return this.endPosition - this.offset;
  14781. },
  14782. nextString: function(length) {
  14783. var value = this.buffer.toString('utf8', this.offset, this.offset + length);
  14784. this.offset += length;
  14785. return value;
  14786. },
  14787. mark: function() {
  14788. var self = this;
  14789. return {
  14790. openWithOffset: function(offset) {
  14791. offset = (offset || 0) + this.offset;
  14792. return new BufferStream(self.buffer, offset, self.endPosition - offset, self.bigEndian);
  14793. },
  14794. offset: this.offset
  14795. };
  14796. },
  14797. offsetFrom: function(marker) {
  14798. return this.offset - marker.offset;
  14799. },
  14800. skip: function(amount) {
  14801. this.offset += amount;
  14802. },
  14803. branch: function(offset, length) {
  14804. length = typeof length === 'number' ? length : this.endPosition - (this.offset + offset);
  14805. return new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian);
  14806. }
  14807. };
  14808. module.exports = BufferStream;
  14809. },{}],242:[function(require,module,exports){
  14810. function parseNumber(s) {
  14811. return parseInt(s, 10);
  14812. }
  14813. //in seconds
  14814. var hours = 3600;
  14815. var minutes = 60;
  14816. //take date (year, month, day) and time (hour, minutes, seconds) digits in UTC
  14817. //and return a timestamp in seconds
  14818. function parseDateTimeParts(dateParts, timeParts) {
  14819. dateParts = dateParts.map(parseNumber);
  14820. timeParts = timeParts.map(parseNumber);
  14821. var year = dateParts[0];
  14822. var month = dateParts[1] - 1;
  14823. var day = dateParts[2];
  14824. var hours = timeParts[0];
  14825. var minutes = timeParts[1];
  14826. var seconds = timeParts[2];
  14827. var date = Date.UTC(year, month, day, hours, minutes, seconds, 0);
  14828. var timestamp = date / 1000;
  14829. return timestamp;
  14830. }
  14831. //parse date with "2004-09-04T23:39:06-08:00" format,
  14832. //one of the formats supported by ISO 8601, and
  14833. //convert to utc timestamp in seconds
  14834. function parseDateWithTimezoneFormat(dateTimeStr) {
  14835. var dateParts = dateTimeStr.substr(0, 10).split('-');
  14836. var timeParts = dateTimeStr.substr(11, 8).split(':');
  14837. var timezoneStr = dateTimeStr.substr(19, 6);
  14838. var timezoneParts = timezoneStr.split(':').map(parseNumber);
  14839. var timezoneOffset = (timezoneParts[0] * hours) +
  14840. (timezoneParts[1] * minutes);
  14841. var timestamp = parseDateTimeParts(dateParts, timeParts);
  14842. //minus because the timezoneOffset describes
  14843. //how much the described time is ahead of UTC
  14844. timestamp -= timezoneOffset;
  14845. if(typeof timestamp === 'number' && !isNaN(timestamp)) {
  14846. return timestamp;
  14847. }
  14848. }
  14849. //parse date with "YYYY:MM:DD hh:mm:ss" format, convert to utc timestamp in seconds
  14850. function parseDateWithSpecFormat(dateTimeStr) {
  14851. var parts = dateTimeStr.split(' '),
  14852. dateParts = parts[0].split(':'),
  14853. timeParts = parts[1].split(':');
  14854. var timestamp = parseDateTimeParts(dateParts, timeParts);
  14855. if(typeof timestamp === 'number' && !isNaN(timestamp)) {
  14856. return timestamp;
  14857. }
  14858. }
  14859. function parseExifDate(dateTimeStr) {
  14860. //some easy checks to determine two common date formats
  14861. //is the date in the standard "YYYY:MM:DD hh:mm:ss" format?
  14862. var isSpecFormat = dateTimeStr.length === 19 &&
  14863. dateTimeStr.charAt(4) === ':';
  14864. //is the date in the non-standard format,
  14865. //"2004-09-04T23:39:06-08:00" to include a timezone?
  14866. var isTimezoneFormat = dateTimeStr.length === 25 &&
  14867. dateTimeStr.charAt(10) === 'T';
  14868. var timestamp;
  14869. if(isTimezoneFormat) {
  14870. return parseDateWithTimezoneFormat(dateTimeStr);
  14871. }
  14872. else if(isSpecFormat) {
  14873. return parseDateWithSpecFormat(dateTimeStr);
  14874. }
  14875. }
  14876. module.exports = {
  14877. parseDateWithSpecFormat: parseDateWithSpecFormat,
  14878. parseDateWithTimezoneFormat: parseDateWithTimezoneFormat,
  14879. parseExifDate: parseExifDate
  14880. };
  14881. },{}],243:[function(require,module,exports){
  14882. /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
  14883. function DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) {
  14884. this.global = global;
  14885. offset = offset || 0;
  14886. length = length || (arrayBuffer.byteLength - offset);
  14887. this.arrayBuffer = arrayBuffer.slice(offset, offset + length);
  14888. this.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength);
  14889. this.setBigEndian(bigEndian);
  14890. this.offset = 0;
  14891. this.parentOffset = (parentOffset || 0) + offset;
  14892. }
  14893. DOMBufferStream.prototype = {
  14894. setBigEndian: function(bigEndian) {
  14895. this.littleEndian = !bigEndian;
  14896. },
  14897. nextUInt8: function() {
  14898. var value = this.view.getUint8(this.offset);
  14899. this.offset += 1;
  14900. return value;
  14901. },
  14902. nextInt8: function() {
  14903. var value = this.view.getInt8(this.offset);
  14904. this.offset += 1;
  14905. return value;
  14906. },
  14907. nextUInt16: function() {
  14908. var value = this.view.getUint16(this.offset, this.littleEndian);
  14909. this.offset += 2;
  14910. return value;
  14911. },
  14912. nextUInt32: function() {
  14913. var value = this.view.getUint32(this.offset, this.littleEndian);
  14914. this.offset += 4;
  14915. return value;
  14916. },
  14917. nextInt16: function() {
  14918. var value = this.view.getInt16(this.offset, this.littleEndian);
  14919. this.offset += 2;
  14920. return value;
  14921. },
  14922. nextInt32: function() {
  14923. var value = this.view.getInt32(this.offset, this.littleEndian);
  14924. this.offset += 4;
  14925. return value;
  14926. },
  14927. nextFloat: function() {
  14928. var value = this.view.getFloat32(this.offset, this.littleEndian);
  14929. this.offset += 4;
  14930. return value;
  14931. },
  14932. nextDouble: function() {
  14933. var value = this.view.getFloat64(this.offset, this.littleEndian);
  14934. this.offset += 8;
  14935. return value;
  14936. },
  14937. nextBuffer: function(length) {
  14938. //this won't work in IE10
  14939. var value = this.arrayBuffer.slice(this.offset, this.offset + length);
  14940. this.offset += length;
  14941. return value;
  14942. },
  14943. remainingLength: function() {
  14944. return this.arrayBuffer.byteLength - this.offset;
  14945. },
  14946. nextString: function(length) {
  14947. var value = this.arrayBuffer.slice(this.offset, this.offset + length);
  14948. value = String.fromCharCode.apply(null, new this.global.Uint8Array(value));
  14949. this.offset += length;
  14950. return value;
  14951. },
  14952. mark: function() {
  14953. var self = this;
  14954. return {
  14955. openWithOffset: function(offset) {
  14956. offset = (offset || 0) + this.offset;
  14957. return new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset);
  14958. },
  14959. offset: this.offset,
  14960. getParentOffset: function() {
  14961. return self.parentOffset;
  14962. }
  14963. };
  14964. },
  14965. offsetFrom: function(marker) {
  14966. return this.parentOffset + this.offset - (marker.offset + marker.getParentOffset());
  14967. },
  14968. skip: function(amount) {
  14969. this.offset += amount;
  14970. },
  14971. branch: function(offset, length) {
  14972. length = typeof length === 'number' ? length : this.arrayBuffer.byteLength - (this.offset + offset);
  14973. return new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset);
  14974. }
  14975. };
  14976. module.exports = DOMBufferStream;
  14977. },{}],244:[function(require,module,exports){
  14978. module.exports = {
  14979. exif : {
  14980. 0x0001 : "InteropIndex",
  14981. 0x0002 : "InteropVersion",
  14982. 0x000B : "ProcessingSoftware",
  14983. 0x00FE : "SubfileType",
  14984. 0x00FF : "OldSubfileType",
  14985. 0x0100 : "ImageWidth",
  14986. 0x0101 : "ImageHeight",
  14987. 0x0102 : "BitsPerSample",
  14988. 0x0103 : "Compression",
  14989. 0x0106 : "PhotometricInterpretation",
  14990. 0x0107 : "Thresholding",
  14991. 0x0108 : "CellWidth",
  14992. 0x0109 : "CellLength",
  14993. 0x010A : "FillOrder",
  14994. 0x010D : "DocumentName",
  14995. 0x010E : "ImageDescription",
  14996. 0x010F : "Make",
  14997. 0x0110 : "Model",
  14998. 0x0111 : "StripOffsets",
  14999. 0x0112 : "Orientation",
  15000. 0x0115 : "SamplesPerPixel",
  15001. 0x0116 : "RowsPerStrip",
  15002. 0x0117 : "StripByteCounts",
  15003. 0x0118 : "MinSampleValue",
  15004. 0x0119 : "MaxSampleValue",
  15005. 0x011A : "XResolution",
  15006. 0x011B : "YResolution",
  15007. 0x011C : "PlanarConfiguration",
  15008. 0x011D : "PageName",
  15009. 0x011E : "XPosition",
  15010. 0x011F : "YPosition",
  15011. 0x0120 : "FreeOffsets",
  15012. 0x0121 : "FreeByteCounts",
  15013. 0x0122 : "GrayResponseUnit",
  15014. 0x0123 : "GrayResponseCurve",
  15015. 0x0124 : "T4Options",
  15016. 0x0125 : "T6Options",
  15017. 0x0128 : "ResolutionUnit",
  15018. 0x0129 : "PageNumber",
  15019. 0x012C : "ColorResponseUnit",
  15020. 0x012D : "TransferFunction",
  15021. 0x0131 : "Software",
  15022. 0x0132 : "ModifyDate",
  15023. 0x013B : "Artist",
  15024. 0x013C : "HostComputer",
  15025. 0x013D : "Predictor",
  15026. 0x013E : "WhitePoint",
  15027. 0x013F : "PrimaryChromaticities",
  15028. 0x0140 : "ColorMap",
  15029. 0x0141 : "HalftoneHints",
  15030. 0x0142 : "TileWidth",
  15031. 0x0143 : "TileLength",
  15032. 0x0144 : "TileOffsets",
  15033. 0x0145 : "TileByteCounts",
  15034. 0x0146 : "BadFaxLines",
  15035. 0x0147 : "CleanFaxData",
  15036. 0x0148 : "ConsecutiveBadFaxLines",
  15037. 0x014A : "SubIFD",
  15038. 0x014C : "InkSet",
  15039. 0x014D : "InkNames",
  15040. 0x014E : "NumberofInks",
  15041. 0x0150 : "DotRange",
  15042. 0x0151 : "TargetPrinter",
  15043. 0x0152 : "ExtraSamples",
  15044. 0x0153 : "SampleFormat",
  15045. 0x0154 : "SMinSampleValue",
  15046. 0x0155 : "SMaxSampleValue",
  15047. 0x0156 : "TransferRange",
  15048. 0x0157 : "ClipPath",
  15049. 0x0158 : "XClipPathUnits",
  15050. 0x0159 : "YClipPathUnits",
  15051. 0x015A : "Indexed",
  15052. 0x015B : "JPEGTables",
  15053. 0x015F : "OPIProxy",
  15054. 0x0190 : "GlobalParametersIFD",
  15055. 0x0191 : "ProfileType",
  15056. 0x0192 : "FaxProfile",
  15057. 0x0193 : "CodingMethods",
  15058. 0x0194 : "VersionYear",
  15059. 0x0195 : "ModeNumber",
  15060. 0x01B1 : "Decode",
  15061. 0x01B2 : "DefaultImageColor",
  15062. 0x01B3 : "T82Options",
  15063. 0x01B5 : "JPEGTables",
  15064. 0x0200 : "JPEGProc",
  15065. 0x0201 : "ThumbnailOffset",
  15066. 0x0202 : "ThumbnailLength",
  15067. 0x0203 : "JPEGRestartInterval",
  15068. 0x0205 : "JPEGLosslessPredictors",
  15069. 0x0206 : "JPEGPointTransforms",
  15070. 0x0207 : "JPEGQTables",
  15071. 0x0208 : "JPEGDCTables",
  15072. 0x0209 : "JPEGACTables",
  15073. 0x0211 : "YCbCrCoefficients",
  15074. 0x0212 : "YCbCrSubSampling",
  15075. 0x0213 : "YCbCrPositioning",
  15076. 0x0214 : "ReferenceBlackWhite",
  15077. 0x022F : "StripRowCounts",
  15078. 0x02BC : "ApplicationNotes",
  15079. 0x03E7 : "USPTOMiscellaneous",
  15080. 0x1000 : "RelatedImageFileFormat",
  15081. 0x1001 : "RelatedImageWidth",
  15082. 0x1002 : "RelatedImageHeight",
  15083. 0x4746 : "Rating",
  15084. 0x4747 : "XP_DIP_XML",
  15085. 0x4748 : "StitchInfo",
  15086. 0x4749 : "RatingPercent",
  15087. 0x800D : "ImageID",
  15088. 0x80A3 : "WangTag1",
  15089. 0x80A4 : "WangAnnotation",
  15090. 0x80A5 : "WangTag3",
  15091. 0x80A6 : "WangTag4",
  15092. 0x80E3 : "Matteing",
  15093. 0x80E4 : "DataType",
  15094. 0x80E5 : "ImageDepth",
  15095. 0x80E6 : "TileDepth",
  15096. 0x827D : "Model2",
  15097. 0x828D : "CFARepeatPatternDim",
  15098. 0x828E : "CFAPattern2",
  15099. 0x828F : "BatteryLevel",
  15100. 0x8290 : "KodakIFD",
  15101. 0x8298 : "Copyright",
  15102. 0x829A : "ExposureTime",
  15103. 0x829D : "FNumber",
  15104. 0x82A5 : "MDFileTag",
  15105. 0x82A6 : "MDScalePixel",
  15106. 0x82A7 : "MDColorTable",
  15107. 0x82A8 : "MDLabName",
  15108. 0x82A9 : "MDSampleInfo",
  15109. 0x82AA : "MDPrepDate",
  15110. 0x82AB : "MDPrepTime",
  15111. 0x82AC : "MDFileUnits",
  15112. 0x830E : "PixelScale",
  15113. 0x8335 : "AdventScale",
  15114. 0x8336 : "AdventRevision",
  15115. 0x835C : "UIC1Tag",
  15116. 0x835D : "UIC2Tag",
  15117. 0x835E : "UIC3Tag",
  15118. 0x835F : "UIC4Tag",
  15119. 0x83BB : "IPTC-NAA",
  15120. 0x847E : "IntergraphPacketData",
  15121. 0x847F : "IntergraphFlagRegisters",
  15122. 0x8480 : "IntergraphMatrix",
  15123. 0x8481 : "INGRReserved",
  15124. 0x8482 : "ModelTiePoint",
  15125. 0x84E0 : "Site",
  15126. 0x84E1 : "ColorSequence",
  15127. 0x84E2 : "IT8Header",
  15128. 0x84E3 : "RasterPadding",
  15129. 0x84E4 : "BitsPerRunLength",
  15130. 0x84E5 : "BitsPerExtendedRunLength",
  15131. 0x84E6 : "ColorTable",
  15132. 0x84E7 : "ImageColorIndicator",
  15133. 0x84E8 : "BackgroundColorIndicator",
  15134. 0x84E9 : "ImageColorValue",
  15135. 0x84EA : "BackgroundColorValue",
  15136. 0x84EB : "PixelIntensityRange",
  15137. 0x84EC : "TransparencyIndicator",
  15138. 0x84ED : "ColorCharacterization",
  15139. 0x84EE : "HCUsage",
  15140. 0x84EF : "TrapIndicator",
  15141. 0x84F0 : "CMYKEquivalent",
  15142. 0x8546 : "SEMInfo",
  15143. 0x8568 : "AFCP_IPTC",
  15144. 0x85B8 : "PixelMagicJBIGOptions",
  15145. 0x85D8 : "ModelTransform",
  15146. 0x8602 : "WB_GRGBLevels",
  15147. 0x8606 : "LeafData",
  15148. 0x8649 : "PhotoshopSettings",
  15149. 0x8769 : "ExifOffset",
  15150. 0x8773 : "ICC_Profile",
  15151. 0x877F : "TIFF_FXExtensions",
  15152. 0x8780 : "MultiProfiles",
  15153. 0x8781 : "SharedData",
  15154. 0x8782 : "T88Options",
  15155. 0x87AC : "ImageLayer",
  15156. 0x87AF : "GeoTiffDirectory",
  15157. 0x87B0 : "GeoTiffDoubleParams",
  15158. 0x87B1 : "GeoTiffAsciiParams",
  15159. 0x8822 : "ExposureProgram",
  15160. 0x8824 : "SpectralSensitivity",
  15161. 0x8825 : "GPSInfo",
  15162. 0x8827 : "ISO",
  15163. 0x8828 : "Opto-ElectricConvFactor",
  15164. 0x8829 : "Interlace",
  15165. 0x882A : "TimeZoneOffset",
  15166. 0x882B : "SelfTimerMode",
  15167. 0x8830 : "SensitivityType",
  15168. 0x8831 : "StandardOutputSensitivity",
  15169. 0x8832 : "RecommendedExposureIndex",
  15170. 0x8833 : "ISOSpeed",
  15171. 0x8834 : "ISOSpeedLatitudeyyy",
  15172. 0x8835 : "ISOSpeedLatitudezzz",
  15173. 0x885C : "FaxRecvParams",
  15174. 0x885D : "FaxSubAddress",
  15175. 0x885E : "FaxRecvTime",
  15176. 0x888A : "LeafSubIFD",
  15177. 0x9000 : "ExifVersion",
  15178. 0x9003 : "DateTimeOriginal",
  15179. 0x9004 : "CreateDate",
  15180. 0x9101 : "ComponentsConfiguration",
  15181. 0x9102 : "CompressedBitsPerPixel",
  15182. 0x9201 : "ShutterSpeedValue",
  15183. 0x9202 : "ApertureValue",
  15184. 0x9203 : "BrightnessValue",
  15185. 0x9204 : "ExposureCompensation",
  15186. 0x9205 : "MaxApertureValue",
  15187. 0x9206 : "SubjectDistance",
  15188. 0x9207 : "MeteringMode",
  15189. 0x9208 : "LightSource",
  15190. 0x9209 : "Flash",
  15191. 0x920A : "FocalLength",
  15192. 0x920B : "FlashEnergy",
  15193. 0x920C : "SpatialFrequencyResponse",
  15194. 0x920D : "Noise",
  15195. 0x920E : "FocalPlaneXResolution",
  15196. 0x920F : "FocalPlaneYResolution",
  15197. 0x9210 : "FocalPlaneResolutionUnit",
  15198. 0x9211 : "ImageNumber",
  15199. 0x9212 : "SecurityClassification",
  15200. 0x9213 : "ImageHistory",
  15201. 0x9214 : "SubjectArea",
  15202. 0x9215 : "ExposureIndex",
  15203. 0x9216 : "TIFF-EPStandardID",
  15204. 0x9217 : "SensingMethod",
  15205. 0x923A : "CIP3DataFile",
  15206. 0x923B : "CIP3Sheet",
  15207. 0x923C : "CIP3Side",
  15208. 0x923F : "StoNits",
  15209. 0x927C : "MakerNote",
  15210. 0x9286 : "UserComment",
  15211. 0x9290 : "SubSecTime",
  15212. 0x9291 : "SubSecTimeOriginal",
  15213. 0x9292 : "SubSecTimeDigitized",
  15214. 0x932F : "MSDocumentText",
  15215. 0x9330 : "MSPropertySetStorage",
  15216. 0x9331 : "MSDocumentTextPosition",
  15217. 0x935C : "ImageSourceData",
  15218. 0x9C9B : "XPTitle",
  15219. 0x9C9C : "XPComment",
  15220. 0x9C9D : "XPAuthor",
  15221. 0x9C9E : "XPKeywords",
  15222. 0x9C9F : "XPSubject",
  15223. 0xA000 : "FlashpixVersion",
  15224. 0xA001 : "ColorSpace",
  15225. 0xA002 : "ExifImageWidth",
  15226. 0xA003 : "ExifImageHeight",
  15227. 0xA004 : "RelatedSoundFile",
  15228. 0xA005 : "InteropOffset",
  15229. 0xA20B : "FlashEnergy",
  15230. 0xA20C : "SpatialFrequencyResponse",
  15231. 0xA20D : "Noise",
  15232. 0xA20E : "FocalPlaneXResolution",
  15233. 0xA20F : "FocalPlaneYResolution",
  15234. 0xA210 : "FocalPlaneResolutionUnit",
  15235. 0xA211 : "ImageNumber",
  15236. 0xA212 : "SecurityClassification",
  15237. 0xA213 : "ImageHistory",
  15238. 0xA214 : "SubjectLocation",
  15239. 0xA215 : "ExposureIndex",
  15240. 0xA216 : "TIFF-EPStandardID",
  15241. 0xA217 : "SensingMethod",
  15242. 0xA300 : "FileSource",
  15243. 0xA301 : "SceneType",
  15244. 0xA302 : "CFAPattern",
  15245. 0xA401 : "CustomRendered",
  15246. 0xA402 : "ExposureMode",
  15247. 0xA403 : "WhiteBalance",
  15248. 0xA404 : "DigitalZoomRatio",
  15249. 0xA405 : "FocalLengthIn35mmFormat",
  15250. 0xA406 : "SceneCaptureType",
  15251. 0xA407 : "GainControl",
  15252. 0xA408 : "Contrast",
  15253. 0xA409 : "Saturation",
  15254. 0xA40A : "Sharpness",
  15255. 0xA40B : "DeviceSettingDescription",
  15256. 0xA40C : "SubjectDistanceRange",
  15257. 0xA420 : "ImageUniqueID",
  15258. 0xA430 : "OwnerName",
  15259. 0xA431 : "SerialNumber",
  15260. 0xA432 : "LensInfo",
  15261. 0xA433 : "LensMake",
  15262. 0xA434 : "LensModel",
  15263. 0xA435 : "LensSerialNumber",
  15264. 0xA480 : "GDALMetadata",
  15265. 0xA481 : "GDALNoData",
  15266. 0xA500 : "Gamma",
  15267. 0xAFC0 : "ExpandSoftware",
  15268. 0xAFC1 : "ExpandLens",
  15269. 0xAFC2 : "ExpandFilm",
  15270. 0xAFC3 : "ExpandFilterLens",
  15271. 0xAFC4 : "ExpandScanner",
  15272. 0xAFC5 : "ExpandFlashLamp",
  15273. 0xBC01 : "PixelFormat",
  15274. 0xBC02 : "Transformation",
  15275. 0xBC03 : "Uncompressed",
  15276. 0xBC04 : "ImageType",
  15277. 0xBC80 : "ImageWidth",
  15278. 0xBC81 : "ImageHeight",
  15279. 0xBC82 : "WidthResolution",
  15280. 0xBC83 : "HeightResolution",
  15281. 0xBCC0 : "ImageOffset",
  15282. 0xBCC1 : "ImageByteCount",
  15283. 0xBCC2 : "AlphaOffset",
  15284. 0xBCC3 : "AlphaByteCount",
  15285. 0xBCC4 : "ImageDataDiscard",
  15286. 0xBCC5 : "AlphaDataDiscard",
  15287. 0xC427 : "OceScanjobDesc",
  15288. 0xC428 : "OceApplicationSelector",
  15289. 0xC429 : "OceIDNumber",
  15290. 0xC42A : "OceImageLogic",
  15291. 0xC44F : "Annotations",
  15292. 0xC4A5 : "PrintIM",
  15293. 0xC580 : "USPTOOriginalContentType",
  15294. 0xC612 : "DNGVersion",
  15295. 0xC613 : "DNGBackwardVersion",
  15296. 0xC614 : "UniqueCameraModel",
  15297. 0xC615 : "LocalizedCameraModel",
  15298. 0xC616 : "CFAPlaneColor",
  15299. 0xC617 : "CFALayout",
  15300. 0xC618 : "LinearizationTable",
  15301. 0xC619 : "BlackLevelRepeatDim",
  15302. 0xC61A : "BlackLevel",
  15303. 0xC61B : "BlackLevelDeltaH",
  15304. 0xC61C : "BlackLevelDeltaV",
  15305. 0xC61D : "WhiteLevel",
  15306. 0xC61E : "DefaultScale",
  15307. 0xC61F : "DefaultCropOrigin",
  15308. 0xC620 : "DefaultCropSize",
  15309. 0xC621 : "ColorMatrix1",
  15310. 0xC622 : "ColorMatrix2",
  15311. 0xC623 : "CameraCalibration1",
  15312. 0xC624 : "CameraCalibration2",
  15313. 0xC625 : "ReductionMatrix1",
  15314. 0xC626 : "ReductionMatrix2",
  15315. 0xC627 : "AnalogBalance",
  15316. 0xC628 : "AsShotNeutral",
  15317. 0xC629 : "AsShotWhiteXY",
  15318. 0xC62A : "BaselineExposure",
  15319. 0xC62B : "BaselineNoise",
  15320. 0xC62C : "BaselineSharpness",
  15321. 0xC62D : "BayerGreenSplit",
  15322. 0xC62E : "LinearResponseLimit",
  15323. 0xC62F : "CameraSerialNumber",
  15324. 0xC630 : "DNGLensInfo",
  15325. 0xC631 : "ChromaBlurRadius",
  15326. 0xC632 : "AntiAliasStrength",
  15327. 0xC633 : "ShadowScale",
  15328. 0xC634 : "DNGPrivateData",
  15329. 0xC635 : "MakerNoteSafety",
  15330. 0xC640 : "RawImageSegmentation",
  15331. 0xC65A : "CalibrationIlluminant1",
  15332. 0xC65B : "CalibrationIlluminant2",
  15333. 0xC65C : "BestQualityScale",
  15334. 0xC65D : "RawDataUniqueID",
  15335. 0xC660 : "AliasLayerMetadata",
  15336. 0xC68B : "OriginalRawFileName",
  15337. 0xC68C : "OriginalRawFileData",
  15338. 0xC68D : "ActiveArea",
  15339. 0xC68E : "MaskedAreas",
  15340. 0xC68F : "AsShotICCProfile",
  15341. 0xC690 : "AsShotPreProfileMatrix",
  15342. 0xC691 : "CurrentICCProfile",
  15343. 0xC692 : "CurrentPreProfileMatrix",
  15344. 0xC6BF : "ColorimetricReference",
  15345. 0xC6D2 : "PanasonicTitle",
  15346. 0xC6D3 : "PanasonicTitle2",
  15347. 0xC6F3 : "CameraCalibrationSig",
  15348. 0xC6F4 : "ProfileCalibrationSig",
  15349. 0xC6F5 : "ProfileIFD",
  15350. 0xC6F6 : "AsShotProfileName",
  15351. 0xC6F7 : "NoiseReductionApplied",
  15352. 0xC6F8 : "ProfileName",
  15353. 0xC6F9 : "ProfileHueSatMapDims",
  15354. 0xC6FA : "ProfileHueSatMapData1",
  15355. 0xC6FB : "ProfileHueSatMapData2",
  15356. 0xC6FC : "ProfileToneCurve",
  15357. 0xC6FD : "ProfileEmbedPolicy",
  15358. 0xC6FE : "ProfileCopyright",
  15359. 0xC714 : "ForwardMatrix1",
  15360. 0xC715 : "ForwardMatrix2",
  15361. 0xC716 : "PreviewApplicationName",
  15362. 0xC717 : "PreviewApplicationVersion",
  15363. 0xC718 : "PreviewSettingsName",
  15364. 0xC719 : "PreviewSettingsDigest",
  15365. 0xC71A : "PreviewColorSpace",
  15366. 0xC71B : "PreviewDateTime",
  15367. 0xC71C : "RawImageDigest",
  15368. 0xC71D : "OriginalRawFileDigest",
  15369. 0xC71E : "SubTileBlockSize",
  15370. 0xC71F : "RowInterleaveFactor",
  15371. 0xC725 : "ProfileLookTableDims",
  15372. 0xC726 : "ProfileLookTableData",
  15373. 0xC740 : "OpcodeList1",
  15374. 0xC741 : "OpcodeList2",
  15375. 0xC74E : "OpcodeList3",
  15376. 0xC761 : "NoiseProfile",
  15377. 0xC763 : "TimeCodes",
  15378. 0xC764 : "FrameRate",
  15379. 0xC772 : "TStop",
  15380. 0xC789 : "ReelName",
  15381. 0xC791 : "OriginalDefaultFinalSize",
  15382. 0xC792 : "OriginalBestQualitySize",
  15383. 0xC793 : "OriginalDefaultCropSize",
  15384. 0xC7A1 : "CameraLabel",
  15385. 0xC7A3 : "ProfileHueSatMapEncoding",
  15386. 0xC7A4 : "ProfileLookTableEncoding",
  15387. 0xC7A5 : "BaselineExposureOffset",
  15388. 0xC7A6 : "DefaultBlackRender",
  15389. 0xC7A7 : "NewRawImageDigest",
  15390. 0xC7A8 : "RawToPreviewGain",
  15391. 0xC7B5 : "DefaultUserCrop",
  15392. 0xEA1C : "Padding",
  15393. 0xEA1D : "OffsetSchema",
  15394. 0xFDE8 : "OwnerName",
  15395. 0xFDE9 : "SerialNumber",
  15396. 0xFDEA : "Lens",
  15397. 0xFE00 : "KDC_IFD",
  15398. 0xFE4C : "RawFile",
  15399. 0xFE4D : "Converter",
  15400. 0xFE4E : "WhiteBalance",
  15401. 0xFE51 : "Exposure",
  15402. 0xFE52 : "Shadows",
  15403. 0xFE53 : "Brightness",
  15404. 0xFE54 : "Contrast",
  15405. 0xFE55 : "Saturation",
  15406. 0xFE56 : "Sharpness",
  15407. 0xFE57 : "Smoothness",
  15408. 0xFE58 : "MoireFilter"
  15409. },
  15410. gps : {
  15411. 0x0000 : 'GPSVersionID',
  15412. 0x0001 : 'GPSLatitudeRef',
  15413. 0x0002 : 'GPSLatitude',
  15414. 0x0003 : 'GPSLongitudeRef',
  15415. 0x0004 : 'GPSLongitude',
  15416. 0x0005 : 'GPSAltitudeRef',
  15417. 0x0006 : 'GPSAltitude',
  15418. 0x0007 : 'GPSTimeStamp',
  15419. 0x0008 : 'GPSSatellites',
  15420. 0x0009 : 'GPSStatus',
  15421. 0x000A : 'GPSMeasureMode',
  15422. 0x000B : 'GPSDOP',
  15423. 0x000C : 'GPSSpeedRef',
  15424. 0x000D : 'GPSSpeed',
  15425. 0x000E : 'GPSTrackRef',
  15426. 0x000F : 'GPSTrack',
  15427. 0x0010 : 'GPSImgDirectionRef',
  15428. 0x0011 : 'GPSImgDirection',
  15429. 0x0012 : 'GPSMapDatum',
  15430. 0x0013 : 'GPSDestLatitudeRef',
  15431. 0x0014 : 'GPSDestLatitude',
  15432. 0x0015 : 'GPSDestLongitudeRef',
  15433. 0x0016 : 'GPSDestLongitude',
  15434. 0x0017 : 'GPSDestBearingRef',
  15435. 0x0018 : 'GPSDestBearing',
  15436. 0x0019 : 'GPSDestDistanceRef',
  15437. 0x001A : 'GPSDestDistance',
  15438. 0x001B : 'GPSProcessingMethod',
  15439. 0x001C : 'GPSAreaInformation',
  15440. 0x001D : 'GPSDateStamp',
  15441. 0x001E : 'GPSDifferential',
  15442. 0x001F : 'GPSHPositioningError'
  15443. }
  15444. };
  15445. },{}],245:[function(require,module,exports){
  15446. /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
  15447. function readExifValue(format, stream) {
  15448. switch(format) {
  15449. case 1: return stream.nextUInt8();
  15450. case 3: return stream.nextUInt16();
  15451. case 4: return stream.nextUInt32();
  15452. case 5: return [stream.nextUInt32(), stream.nextUInt32()];
  15453. case 6: return stream.nextInt8();
  15454. case 8: return stream.nextUInt16();
  15455. case 9: return stream.nextUInt32();
  15456. case 10: return [stream.nextInt32(), stream.nextInt32()];
  15457. case 11: return stream.nextFloat();
  15458. case 12: return stream.nextDouble();
  15459. default: throw new Error('Invalid format while decoding: ' + format);
  15460. }
  15461. }
  15462. function getBytesPerComponent(format) {
  15463. switch(format) {
  15464. case 1:
  15465. case 2:
  15466. case 6:
  15467. case 7:
  15468. return 1;
  15469. case 3:
  15470. case 8:
  15471. return 2;
  15472. case 4:
  15473. case 9:
  15474. case 11:
  15475. return 4;
  15476. case 5:
  15477. case 10:
  15478. case 12:
  15479. return 8;
  15480. default:
  15481. return 0;
  15482. }
  15483. }
  15484. function readExifTag(tiffMarker, stream) {
  15485. var tagType = stream.nextUInt16(),
  15486. format = stream.nextUInt16(),
  15487. bytesPerComponent = getBytesPerComponent(format),
  15488. components = stream.nextUInt32(),
  15489. valueBytes = bytesPerComponent * components,
  15490. values,
  15491. value,
  15492. c;
  15493. /* if the value is bigger then 4 bytes, the value is in the data section of the IFD
  15494. and the value present in the tag is the offset starting from the tiff header. So we replace the stream
  15495. with a stream that is located at the given offset in the data section. s*/
  15496. if(valueBytes > 4) {
  15497. stream = tiffMarker.openWithOffset(stream.nextUInt32());
  15498. }
  15499. //we don't want to read strings as arrays
  15500. if(format === 2) {
  15501. values = stream.nextString(components);
  15502. //cut off \0 characters
  15503. var lastNull = values.indexOf('\0');
  15504. if(lastNull !== -1) {
  15505. values = values.substr(0, lastNull);
  15506. }
  15507. }
  15508. else if(format === 7) {
  15509. values = stream.nextBuffer(components);
  15510. }
  15511. else if(format !== 0) {
  15512. values = [];
  15513. for(c = 0; c < components; ++c) {
  15514. values.push(readExifValue(format, stream));
  15515. }
  15516. }
  15517. //since our stream is a stateful object, we need to skip remaining bytes
  15518. //so our offset stays correct
  15519. if(valueBytes < 4) {
  15520. stream.skip(4 - valueBytes);
  15521. }
  15522. return [tagType, values, format];
  15523. }
  15524. function readIFDSection(tiffMarker, stream, iterator) {
  15525. var numberOfEntries = stream.nextUInt16(), tag, i;
  15526. for(i = 0; i < numberOfEntries; ++i) {
  15527. tag = readExifTag(tiffMarker, stream);
  15528. iterator(tag[0], tag[1], tag[2]);
  15529. }
  15530. }
  15531. function readHeader(stream) {
  15532. var exifHeader = stream.nextString(6);
  15533. if(exifHeader !== 'Exif\0\0') {
  15534. throw new Error('Invalid EXIF header');
  15535. }
  15536. var tiffMarker = stream.mark();
  15537. var tiffHeader = stream.nextUInt16();
  15538. if(tiffHeader === 0x4949) {
  15539. stream.setBigEndian(false);
  15540. } else if(tiffHeader === 0x4D4D) {
  15541. stream.setBigEndian(true);
  15542. } else {
  15543. throw new Error('Invalid TIFF header');
  15544. }
  15545. if(stream.nextUInt16() !== 0x002A) {
  15546. throw new Error('Invalid TIFF data');
  15547. }
  15548. return tiffMarker;
  15549. }
  15550. module.exports = {
  15551. IFD0: 1,
  15552. IFD1: 2,
  15553. GPSIFD: 3,
  15554. SubIFD: 4,
  15555. InteropIFD: 5,
  15556. parseTags: function(stream, iterator) {
  15557. var tiffMarker;
  15558. try {
  15559. tiffMarker = readHeader(stream);
  15560. } catch(e) {
  15561. return false; //ignore APP1 sections with invalid headers
  15562. }
  15563. var subIfdOffset, gpsOffset, interopOffset;
  15564. var ifd0Stream = tiffMarker.openWithOffset(stream.nextUInt32()),
  15565. IFD0 = this.IFD0;
  15566. readIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) {
  15567. switch(tagType) {
  15568. case 0x8825: gpsOffset = value[0]; break;
  15569. case 0x8769: subIfdOffset = value[0]; break;
  15570. default: iterator(IFD0, tagType, value, format); break;
  15571. }
  15572. });
  15573. var ifd1Offset = ifd0Stream.nextUInt32();
  15574. if(ifd1Offset !== 0) {
  15575. var ifd1Stream = tiffMarker.openWithOffset(ifd1Offset);
  15576. readIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1));
  15577. }
  15578. if(gpsOffset) {
  15579. var gpsStream = tiffMarker.openWithOffset(gpsOffset);
  15580. readIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD));
  15581. }
  15582. if(subIfdOffset) {
  15583. var subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD;
  15584. readIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) {
  15585. if(tagType === 0xA005) {
  15586. interopOffset = value[0];
  15587. } else {
  15588. iterator(InteropIFD, tagType, value, format);
  15589. }
  15590. });
  15591. }
  15592. if(interopOffset) {
  15593. var interopStream = tiffMarker.openWithOffset(interopOffset);
  15594. readIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD));
  15595. }
  15596. return true;
  15597. }
  15598. };
  15599. },{}],246:[function(require,module,exports){
  15600. /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
  15601. module.exports = {
  15602. parseSections: function(stream, iterator) {
  15603. var len, markerType;
  15604. stream.setBigEndian(true);
  15605. //stop reading the stream at the SOS (Start of Stream) marker,
  15606. //because its length is not stored in the header so we can't
  15607. //know where to jump to. The only marker after that is just EOI (End Of Image) anyway
  15608. while(stream.remainingLength() > 0 && markerType !== 0xDA) {
  15609. if(stream.nextUInt8() !== 0xFF) {
  15610. throw new Error('Invalid JPEG section offset');
  15611. }
  15612. markerType = stream.nextUInt8();
  15613. //don't read size from markers that have no datas
  15614. if((markerType >= 0xD0 && markerType <= 0xD9) || markerType === 0xDA) {
  15615. len = 0;
  15616. } else {
  15617. len = stream.nextUInt16() - 2;
  15618. }
  15619. iterator(markerType, stream.branch(0, len));
  15620. stream.skip(len);
  15621. }
  15622. },
  15623. //stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator
  15624. getSizeFromSOFSection: function(stream) {
  15625. stream.skip(1);
  15626. return {
  15627. height: stream.nextUInt16(),
  15628. width: stream.nextUInt16()
  15629. };
  15630. },
  15631. getSectionName: function(markerType) {
  15632. var name, index;
  15633. switch(markerType) {
  15634. case 0xD8: name = 'SOI'; break;
  15635. case 0xC4: name = 'DHT'; break;
  15636. case 0xDB: name = 'DQT'; break;
  15637. case 0xDD: name = 'DRI'; break;
  15638. case 0xDA: name = 'SOS'; break;
  15639. case 0xFE: name = 'COM'; break;
  15640. case 0xD9: name = 'EOI'; break;
  15641. default:
  15642. if(markerType >= 0xE0 && markerType <= 0xEF) {
  15643. name = 'APP';
  15644. index = markerType - 0xE0;
  15645. }
  15646. else if(markerType >= 0xC0 && markerType <= 0xCF && markerType !== 0xC4 && markerType !== 0xC8 && markerType !== 0xCC) {
  15647. name = 'SOF';
  15648. index = markerType - 0xC0;
  15649. }
  15650. else if(markerType >= 0xD0 && markerType <= 0xD7) {
  15651. name = 'RST';
  15652. index = markerType - 0xD0;
  15653. }
  15654. break;
  15655. }
  15656. var nameStruct = {
  15657. name: name
  15658. };
  15659. if(typeof index === 'number') {
  15660. nameStruct.index = index;
  15661. }
  15662. return nameStruct;
  15663. }
  15664. };
  15665. },{}],247:[function(require,module,exports){
  15666. /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
  15667. var jpeg = require('./jpeg'),
  15668. exif = require('./exif'),
  15669. simplify = require('./simplify');
  15670. function ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) {
  15671. this.startMarker = startMarker;
  15672. this.tags = tags;
  15673. this.imageSize = imageSize;
  15674. this.thumbnailOffset = thumbnailOffset;
  15675. this.thumbnailLength = thumbnailLength;
  15676. this.thumbnailType = thumbnailType;
  15677. this.app1Offset = app1Offset;
  15678. }
  15679. ExifResult.prototype = {
  15680. hasThumbnail: function(mime) {
  15681. if(!this.thumbnailOffset || !this.thumbnailLength) {
  15682. return false;
  15683. }
  15684. if(typeof mime !== 'string') {
  15685. return true;
  15686. }
  15687. if(mime.toLowerCase().trim() === 'image/jpeg') {
  15688. return this.thumbnailType === 6;
  15689. }
  15690. if(mime.toLowerCase().trim() === 'image/tiff') {
  15691. return this.thumbnailType === 1;
  15692. }
  15693. return false;
  15694. },
  15695. getThumbnailOffset: function() {
  15696. return this.app1Offset + 6 + this.thumbnailOffset;
  15697. },
  15698. getThumbnailLength: function() {
  15699. return this.thumbnailLength;
  15700. },
  15701. getThumbnailBuffer: function() {
  15702. return this._getThumbnailStream().nextBuffer(this.thumbnailLength);
  15703. },
  15704. _getThumbnailStream: function() {
  15705. return this.startMarker.openWithOffset(this.getThumbnailOffset());
  15706. },
  15707. getImageSize: function() {
  15708. return this.imageSize;
  15709. },
  15710. getThumbnailSize: function() {
  15711. var stream = this._getThumbnailStream(), size;
  15712. jpeg.parseSections(stream, function(sectionType, sectionStream) {
  15713. if(jpeg.getSectionName(sectionType).name === 'SOF') {
  15714. size = jpeg.getSizeFromSOFSection(sectionStream);
  15715. }
  15716. });
  15717. return size;
  15718. }
  15719. };
  15720. function Parser(stream) {
  15721. this.stream = stream;
  15722. this.flags = {
  15723. readBinaryTags: false,
  15724. resolveTagNames: true,
  15725. simplifyValues: true,
  15726. imageSize: true,
  15727. hidePointers: true,
  15728. returnTags: true
  15729. };
  15730. }
  15731. Parser.prototype = {
  15732. enableBinaryFields: function(enable) {
  15733. this.flags.readBinaryTags = !!enable;
  15734. return this;
  15735. },
  15736. enablePointers: function(enable) {
  15737. this.flags.hidePointers = !enable;
  15738. return this;
  15739. },
  15740. enableTagNames: function(enable) {
  15741. this.flags.resolveTagNames = !!enable;
  15742. return this;
  15743. },
  15744. enableImageSize: function(enable) {
  15745. this.flags.imageSize = !!enable;
  15746. return this;
  15747. },
  15748. enableReturnTags: function(enable) {
  15749. this.flags.returnTags = !!enable;
  15750. return this;
  15751. },
  15752. enableSimpleValues: function(enable) {
  15753. this.flags.simplifyValues = !!enable;
  15754. return this;
  15755. },
  15756. parse: function() {
  15757. var start = this.stream.mark(),
  15758. stream = start.openWithOffset(0),
  15759. flags = this.flags,
  15760. tags,
  15761. imageSize,
  15762. thumbnailOffset,
  15763. thumbnailLength,
  15764. thumbnailType,
  15765. app1Offset,
  15766. tagNames,
  15767. getTagValue, setTagValue;
  15768. if(flags.resolveTagNames) {
  15769. tagNames = require('./exif-tags');
  15770. }
  15771. if(flags.resolveTagNames) {
  15772. tags = {};
  15773. getTagValue = function(t) {
  15774. return tags[t.name];
  15775. };
  15776. setTagValue = function(t, value) {
  15777. tags[t.name] = value;
  15778. };
  15779. } else {
  15780. tags = [];
  15781. getTagValue = function(t) {
  15782. var i;
  15783. for(i = 0; i < tags.length; ++i) {
  15784. if(tags[i].type === t.type && tags[i].section === t.section) {
  15785. return tags.value;
  15786. }
  15787. }
  15788. };
  15789. setTagValue = function(t, value) {
  15790. var i;
  15791. for(i = 0; i < tags.length; ++i) {
  15792. if(tags[i].type === t.type && tags[i].section === t.section) {
  15793. tags.value = value;
  15794. return;
  15795. }
  15796. }
  15797. };
  15798. }
  15799. jpeg.parseSections(stream, function(sectionType, sectionStream) {
  15800. var validExifHeaders, sectionOffset = sectionStream.offsetFrom(start);
  15801. if(sectionType === 0xE1) {
  15802. validExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {
  15803. //ignore binary fields if disabled
  15804. if(!flags.readBinaryTags && format === 7) {
  15805. return;
  15806. }
  15807. if(tagType === 0x0201) {
  15808. thumbnailOffset = value[0];
  15809. if(flags.hidePointers) {return;}
  15810. } else if(tagType === 0x0202) {
  15811. thumbnailLength = value[0];
  15812. if(flags.hidePointers) {return;}
  15813. } else if(tagType === 0x0103) {
  15814. thumbnailType = value[0];
  15815. if(flags.hidePointers) {return;}
  15816. }
  15817. //if flag is set to not store tags, return here after storing pointers
  15818. if(!flags.returnTags) {
  15819. return;
  15820. }
  15821. if(flags.simplifyValues) {
  15822. value = simplify.simplifyValue(value, format);
  15823. }
  15824. if(flags.resolveTagNames) {
  15825. var sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif;
  15826. var name = sectionTagNames[tagType];
  15827. if(!name) {
  15828. name = tagNames.exif[tagType];
  15829. }
  15830. if (!tags.hasOwnProperty(name)) {
  15831. tags[name] = value;
  15832. }
  15833. } else {
  15834. tags.push({
  15835. section: ifdSection,
  15836. type: tagType,
  15837. value: value
  15838. });
  15839. }
  15840. });
  15841. if(validExifHeaders) {
  15842. app1Offset = sectionOffset;
  15843. }
  15844. }
  15845. else if(flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') {
  15846. imageSize = jpeg.getSizeFromSOFSection(sectionStream);
  15847. }
  15848. });
  15849. if(flags.simplifyValues) {
  15850. simplify.castDegreeValues(getTagValue, setTagValue);
  15851. simplify.castDateValues(getTagValue, setTagValue);
  15852. }
  15853. return new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset);
  15854. }
  15855. };
  15856. module.exports = Parser;
  15857. },{"./exif":245,"./exif-tags":244,"./jpeg":246,"./simplify":248}],248:[function(require,module,exports){
  15858. var exif = require('./exif');
  15859. var date = require('./date');
  15860. var degreeTags = [{
  15861. section: exif.GPSIFD,
  15862. type: 0x0002,
  15863. name: 'GPSLatitude',
  15864. refType: 0x0001,
  15865. refName: 'GPSLatitudeRef',
  15866. posVal: 'N'
  15867. },
  15868. {
  15869. section: exif.GPSIFD,
  15870. type: 0x0004,
  15871. name: 'GPSLongitude',
  15872. refType: 0x0003,
  15873. refName: 'GPSLongitudeRef',
  15874. posVal: 'E'
  15875. }];
  15876. var dateTags = [{
  15877. section: exif.SubIFD,
  15878. type: 0x0132,
  15879. name: 'ModifyDate'
  15880. },
  15881. {
  15882. section: exif.SubIFD,
  15883. type: 0x9003,
  15884. name: 'DateTimeOriginal'
  15885. },
  15886. {
  15887. section: exif.SubIFD,
  15888. type: 0x9004,
  15889. name: 'CreateDate'
  15890. },
  15891. {
  15892. section: exif.SubIFD,
  15893. type: 0x0132,
  15894. name : 'ModifyDate',
  15895. }];
  15896. module.exports = {
  15897. castDegreeValues: function(getTagValue, setTagValue) {
  15898. degreeTags.forEach(function(t) {
  15899. var degreeVal = getTagValue(t);
  15900. if(degreeVal) {
  15901. var degreeRef = getTagValue({section: t.section, type: t.refType, name: t.refName});
  15902. var degreeNumRef = degreeRef === t.posVal ? 1 : -1;
  15903. var degree = (degreeVal[0] + (degreeVal[1] / 60) + (degreeVal[2] / 3600)) * degreeNumRef;
  15904. setTagValue(t, degree);
  15905. }
  15906. });
  15907. },
  15908. castDateValues: function(getTagValue, setTagValue) {
  15909. dateTags.forEach(function(t) {
  15910. var dateStrVal = getTagValue(t);
  15911. if(dateStrVal) {
  15912. //some easy checks to determine two common date formats
  15913. var timestamp = date.parseExifDate(dateStrVal);
  15914. if(typeof timestamp !== 'undefined') {
  15915. setTagValue(t, timestamp);
  15916. }
  15917. }
  15918. });
  15919. },
  15920. simplifyValue: function(values, format) {
  15921. if(Array.isArray(values)) {
  15922. values = values.map(function(value) {
  15923. if(format === 10 || format === 5) {
  15924. return value[0] / value[1];
  15925. }
  15926. return value;
  15927. });
  15928. if(values.length === 1) {
  15929. values = values[0];
  15930. }
  15931. }
  15932. return values;
  15933. }
  15934. };
  15935. },{"./date":242,"./exif":245}],249:[function(require,module,exports){
  15936. 'use strict';
  15937. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  15938. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  15939. var toBytes = function toBytes(s) {
  15940. return (0, _toConsumableArray2["default"])(s).map(function (c) {
  15941. return c.charCodeAt(0);
  15942. });
  15943. };
  15944. var xpiZipFilename = toBytes('META-INF/mozilla.rsa');
  15945. var oxmlContentTypes = toBytes('[Content_Types].xml');
  15946. var oxmlRels = toBytes('_rels/.rels');
  15947. module.exports = function (input) {
  15948. var buf = input instanceof Uint8Array ? input : new Uint8Array(input);
  15949. if (!(buf && buf.length > 1)) {
  15950. return null;
  15951. }
  15952. var check = function check(header, options) {
  15953. options = Object.assign({
  15954. offset: 0
  15955. }, options);
  15956. for (var i = 0; i < header.length; i++) {
  15957. // If a bitmask is set
  15958. if (options.mask) {
  15959. // If header doesn't equal `buf` with bits masked off
  15960. if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
  15961. return false;
  15962. }
  15963. } else if (header[i] !== buf[i + options.offset]) {
  15964. return false;
  15965. }
  15966. }
  15967. return true;
  15968. };
  15969. var checkString = function checkString(header, options) {
  15970. return check(toBytes(header), options);
  15971. };
  15972. if (check([0xFF, 0xD8, 0xFF])) {
  15973. return {
  15974. ext: 'jpg',
  15975. mime: 'image/jpeg'
  15976. };
  15977. }
  15978. if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
  15979. return {
  15980. ext: 'png',
  15981. mime: 'image/png'
  15982. };
  15983. }
  15984. if (check([0x47, 0x49, 0x46])) {
  15985. return {
  15986. ext: 'gif',
  15987. mime: 'image/gif'
  15988. };
  15989. }
  15990. if (check([0x57, 0x45, 0x42, 0x50], {
  15991. offset: 8
  15992. })) {
  15993. return {
  15994. ext: 'webp',
  15995. mime: 'image/webp'
  15996. };
  15997. }
  15998. if (check([0x46, 0x4C, 0x49, 0x46])) {
  15999. return {
  16000. ext: 'flif',
  16001. mime: 'image/flif'
  16002. };
  16003. } // Needs to be before `tif` check
  16004. if ((check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {
  16005. offset: 8
  16006. })) {
  16007. return {
  16008. ext: 'cr2',
  16009. mime: 'image/x-canon-cr2'
  16010. };
  16011. }
  16012. if (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) {
  16013. return {
  16014. ext: 'tif',
  16015. mime: 'image/tiff'
  16016. };
  16017. }
  16018. if (check([0x42, 0x4D])) {
  16019. return {
  16020. ext: 'bmp',
  16021. mime: 'image/bmp'
  16022. };
  16023. }
  16024. if (check([0x49, 0x49, 0xBC])) {
  16025. return {
  16026. ext: 'jxr',
  16027. mime: 'image/vnd.ms-photo'
  16028. };
  16029. }
  16030. if (check([0x38, 0x42, 0x50, 0x53])) {
  16031. return {
  16032. ext: 'psd',
  16033. mime: 'image/vnd.adobe.photoshop'
  16034. };
  16035. } // Zip-based file formats
  16036. // Need to be before the `zip` check
  16037. if (check([0x50, 0x4B, 0x3, 0x4])) {
  16038. if (check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {
  16039. offset: 30
  16040. })) {
  16041. return {
  16042. ext: 'epub',
  16043. mime: 'application/epub+zip'
  16044. };
  16045. } // Assumes signed `.xpi` from addons.mozilla.org
  16046. if (check(xpiZipFilename, {
  16047. offset: 30
  16048. })) {
  16049. return {
  16050. ext: 'xpi',
  16051. mime: 'application/x-xpinstall'
  16052. };
  16053. }
  16054. if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {
  16055. offset: 30
  16056. })) {
  16057. return {
  16058. ext: 'odt',
  16059. mime: 'application/vnd.oasis.opendocument.text'
  16060. };
  16061. }
  16062. if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {
  16063. offset: 30
  16064. })) {
  16065. return {
  16066. ext: 'ods',
  16067. mime: 'application/vnd.oasis.opendocument.spreadsheet'
  16068. };
  16069. }
  16070. if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {
  16071. offset: 30
  16072. })) {
  16073. return {
  16074. ext: 'odp',
  16075. mime: 'application/vnd.oasis.opendocument.presentation'
  16076. };
  16077. } // The docx, xlsx and pptx file types extend the Office Open XML file format:
  16078. // https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
  16079. // We look for:
  16080. // - one entry named '[Content_Types].xml' or '_rels/.rels',
  16081. // - one entry indicating specific type of file.
  16082. // MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.
  16083. var findNextZipHeaderIndex = function findNextZipHeaderIndex(arr) {
  16084. var startAt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  16085. return arr.findIndex(function (el, i, arr) {
  16086. return i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4;
  16087. });
  16088. };
  16089. var zipHeaderIndex = 0; // The first zip header was already found at index 0
  16090. var oxmlFound = false;
  16091. var type = null;
  16092. do {
  16093. var offset = zipHeaderIndex + 30;
  16094. if (!oxmlFound) {
  16095. oxmlFound = check(oxmlContentTypes, {
  16096. offset: offset
  16097. }) || check(oxmlRels, {
  16098. offset: offset
  16099. });
  16100. }
  16101. if (!type) {
  16102. if (checkString('word/', {
  16103. offset: offset
  16104. })) {
  16105. type = {
  16106. ext: 'docx',
  16107. mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  16108. };
  16109. } else if (checkString('ppt/', {
  16110. offset: offset
  16111. })) {
  16112. type = {
  16113. ext: 'pptx',
  16114. mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  16115. };
  16116. } else if (checkString('xl/', {
  16117. offset: offset
  16118. })) {
  16119. type = {
  16120. ext: 'xlsx',
  16121. mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  16122. };
  16123. }
  16124. }
  16125. if (oxmlFound && type) {
  16126. return type;
  16127. }
  16128. zipHeaderIndex = findNextZipHeaderIndex(buf, offset);
  16129. } while (zipHeaderIndex >= 0); // No more zip parts available in the buffer, but maybe we are almost certain about the type?
  16130. if (type) {
  16131. return type;
  16132. }
  16133. }
  16134. if (check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)) {
  16135. return {
  16136. ext: 'zip',
  16137. mime: 'application/zip'
  16138. };
  16139. }
  16140. if (check([0x75, 0x73, 0x74, 0x61, 0x72], {
  16141. offset: 257
  16142. })) {
  16143. return {
  16144. ext: 'tar',
  16145. mime: 'application/x-tar'
  16146. };
  16147. }
  16148. if (check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1)) {
  16149. return {
  16150. ext: 'rar',
  16151. mime: 'application/x-rar-compressed'
  16152. };
  16153. }
  16154. if (check([0x1F, 0x8B, 0x8])) {
  16155. return {
  16156. ext: 'gz',
  16157. mime: 'application/gzip'
  16158. };
  16159. }
  16160. if (check([0x42, 0x5A, 0x68])) {
  16161. return {
  16162. ext: 'bz2',
  16163. mime: 'application/x-bzip2'
  16164. };
  16165. }
  16166. if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
  16167. return {
  16168. ext: '7z',
  16169. mime: 'application/x-7z-compressed'
  16170. };
  16171. }
  16172. if (check([0x78, 0x01])) {
  16173. return {
  16174. ext: 'dmg',
  16175. mime: 'application/x-apple-diskimage'
  16176. };
  16177. }
  16178. if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5
  16179. check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {
  16180. offset: 4
  16181. }) && (check([0x6D, 0x70, 0x34, 0x31], {
  16182. offset: 8
  16183. }) || // MP41
  16184. check([0x6D, 0x70, 0x34, 0x32], {
  16185. offset: 8
  16186. }) || // MP42
  16187. check([0x69, 0x73, 0x6F, 0x6D], {
  16188. offset: 8
  16189. }) || // ISOM
  16190. check([0x69, 0x73, 0x6F, 0x32], {
  16191. offset: 8
  16192. }) || // ISO2
  16193. check([0x6D, 0x6D, 0x70, 0x34], {
  16194. offset: 8
  16195. }) || // MMP4
  16196. check([0x4D, 0x34, 0x56], {
  16197. offset: 8
  16198. }) || // M4V
  16199. check([0x64, 0x61, 0x73, 0x68], {
  16200. offset: 8
  16201. }) // DASH
  16202. )) {
  16203. return {
  16204. ext: 'mp4',
  16205. mime: 'video/mp4'
  16206. };
  16207. }
  16208. if (check([0x4D, 0x54, 0x68, 0x64])) {
  16209. return {
  16210. ext: 'mid',
  16211. mime: 'audio/midi'
  16212. };
  16213. } // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
  16214. if (check([0x1A, 0x45, 0xDF, 0xA3])) {
  16215. var sliced = buf.subarray(4, 4 + 4096);
  16216. var idPos = sliced.findIndex(function (el, i, arr) {
  16217. return arr[i] === 0x42 && arr[i + 1] === 0x82;
  16218. });
  16219. if (idPos !== -1) {
  16220. var docTypePos = idPos + 3;
  16221. var findDocType = function findDocType(type) {
  16222. return (0, _toConsumableArray2["default"])(type).every(function (c, i) {
  16223. return sliced[docTypePos + i] === c.charCodeAt(0);
  16224. });
  16225. };
  16226. if (findDocType('matroska')) {
  16227. return {
  16228. ext: 'mkv',
  16229. mime: 'video/x-matroska'
  16230. };
  16231. }
  16232. if (findDocType('webm')) {
  16233. return {
  16234. ext: 'webm',
  16235. mime: 'video/webm'
  16236. };
  16237. }
  16238. }
  16239. }
  16240. if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {
  16241. offset: 4
  16242. }) || check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {
  16243. offset: 4
  16244. }) || check([0x6D, 0x64, 0x61, 0x74], {
  16245. offset: 4
  16246. }) || // MJPEG
  16247. check([0x77, 0x69, 0x64, 0x65], {
  16248. offset: 4
  16249. })) {
  16250. return {
  16251. ext: 'mov',
  16252. mime: 'video/quicktime'
  16253. };
  16254. } // RIFF file format which might be AVI, WAV, QCP, etc
  16255. if (check([0x52, 0x49, 0x46, 0x46])) {
  16256. if (check([0x41, 0x56, 0x49], {
  16257. offset: 8
  16258. })) {
  16259. return {
  16260. ext: 'avi',
  16261. mime: 'video/vnd.avi'
  16262. };
  16263. }
  16264. if (check([0x57, 0x41, 0x56, 0x45], {
  16265. offset: 8
  16266. })) {
  16267. return {
  16268. ext: 'wav',
  16269. mime: 'audio/vnd.wave'
  16270. };
  16271. } // QLCM, QCP file
  16272. if (check([0x51, 0x4C, 0x43, 0x4D], {
  16273. offset: 8
  16274. })) {
  16275. return {
  16276. ext: 'qcp',
  16277. mime: 'audio/qcelp'
  16278. };
  16279. }
  16280. }
  16281. if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
  16282. return {
  16283. ext: 'wmv',
  16284. mime: 'video/x-ms-wmv'
  16285. };
  16286. }
  16287. if (check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3])) {
  16288. return {
  16289. ext: 'mpg',
  16290. mime: 'video/mpeg'
  16291. };
  16292. }
  16293. if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {
  16294. offset: 4
  16295. })) {
  16296. return {
  16297. ext: '3gp',
  16298. mime: 'video/3gpp'
  16299. };
  16300. } // Check for MPEG header at different starting offsets
  16301. for (var start = 0; start < 2 && start < buf.length - 16; start++) {
  16302. if (check([0x49, 0x44, 0x33], {
  16303. offset: start
  16304. }) || // ID3 header
  16305. check([0xFF, 0xE2], {
  16306. offset: start,
  16307. mask: [0xFF, 0xE2]
  16308. }) // MPEG 1 or 2 Layer 3 header
  16309. ) {
  16310. return {
  16311. ext: 'mp3',
  16312. mime: 'audio/mpeg'
  16313. };
  16314. }
  16315. if (check([0xFF, 0xE4], {
  16316. offset: start,
  16317. mask: [0xFF, 0xE4]
  16318. }) // MPEG 1 or 2 Layer 2 header
  16319. ) {
  16320. return {
  16321. ext: 'mp2',
  16322. mime: 'audio/mpeg'
  16323. };
  16324. }
  16325. if (check([0xFF, 0xF8], {
  16326. offset: start,
  16327. mask: [0xFF, 0xFC]
  16328. }) // MPEG 2 layer 0 using ADTS
  16329. ) {
  16330. return {
  16331. ext: 'mp2',
  16332. mime: 'audio/mpeg'
  16333. };
  16334. }
  16335. if (check([0xFF, 0xF0], {
  16336. offset: start,
  16337. mask: [0xFF, 0xFC]
  16338. }) // MPEG 4 layer 0 using ADTS
  16339. ) {
  16340. return {
  16341. ext: 'mp4',
  16342. mime: 'audio/mpeg'
  16343. };
  16344. }
  16345. }
  16346. if (check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {
  16347. offset: 4
  16348. }) || check([0x4D, 0x34, 0x41, 0x20])) {
  16349. return {
  16350. // MPEG-4 layer 3 (audio)
  16351. ext: 'm4a',
  16352. mime: 'audio/mp4' // RFC 4337
  16353. };
  16354. } // Needs to be before `ogg` check
  16355. if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {
  16356. offset: 28
  16357. })) {
  16358. return {
  16359. ext: 'opus',
  16360. mime: 'audio/opus'
  16361. };
  16362. } // If 'OggS' in first bytes, then OGG container
  16363. if (check([0x4F, 0x67, 0x67, 0x53])) {
  16364. // This is a OGG container
  16365. // If ' theora' in header.
  16366. if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
  16367. offset: 28
  16368. })) {
  16369. return {
  16370. ext: 'ogv',
  16371. mime: 'video/ogg'
  16372. };
  16373. } // If '\x01video' in header.
  16374. if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {
  16375. offset: 28
  16376. })) {
  16377. return {
  16378. ext: 'ogm',
  16379. mime: 'video/ogg'
  16380. };
  16381. } // If ' FLAC' in header https://xiph.org/flac/faq.html
  16382. if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {
  16383. offset: 28
  16384. })) {
  16385. return {
  16386. ext: 'oga',
  16387. mime: 'audio/ogg'
  16388. };
  16389. } // 'Speex ' in header https://en.wikipedia.org/wiki/Speex
  16390. if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {
  16391. offset: 28
  16392. })) {
  16393. return {
  16394. ext: 'spx',
  16395. mime: 'audio/ogg'
  16396. };
  16397. } // If '\x01vorbis' in header
  16398. if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
  16399. offset: 28
  16400. })) {
  16401. return {
  16402. ext: 'ogg',
  16403. mime: 'audio/ogg'
  16404. };
  16405. } // Default OGG container https://www.iana.org/assignments/media-types/application/ogg
  16406. return {
  16407. ext: 'ogx',
  16408. mime: 'application/ogg'
  16409. };
  16410. }
  16411. if (check([0x66, 0x4C, 0x61, 0x43])) {
  16412. return {
  16413. ext: 'flac',
  16414. mime: 'audio/x-flac'
  16415. };
  16416. }
  16417. if (check([0x4D, 0x41, 0x43, 0x20])) {
  16418. // 'MAC '
  16419. return {
  16420. ext: 'ape',
  16421. mime: 'audio/ape'
  16422. };
  16423. }
  16424. if (check([0x77, 0x76, 0x70, 0x6B])) {
  16425. // 'wvpk'
  16426. return {
  16427. ext: 'wv',
  16428. mime: 'audio/wavpack'
  16429. };
  16430. }
  16431. if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
  16432. return {
  16433. ext: 'amr',
  16434. mime: 'audio/amr'
  16435. };
  16436. }
  16437. if (check([0x25, 0x50, 0x44, 0x46])) {
  16438. return {
  16439. ext: 'pdf',
  16440. mime: 'application/pdf'
  16441. };
  16442. }
  16443. if (check([0x4D, 0x5A])) {
  16444. return {
  16445. ext: 'exe',
  16446. mime: 'application/x-msdownload'
  16447. };
  16448. }
  16449. if ((buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {
  16450. offset: 1
  16451. })) {
  16452. return {
  16453. ext: 'swf',
  16454. mime: 'application/x-shockwave-flash'
  16455. };
  16456. }
  16457. if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
  16458. return {
  16459. ext: 'rtf',
  16460. mime: 'application/rtf'
  16461. };
  16462. }
  16463. if (check([0x00, 0x61, 0x73, 0x6D])) {
  16464. return {
  16465. ext: 'wasm',
  16466. mime: 'application/wasm'
  16467. };
  16468. }
  16469. if (check([0x77, 0x4F, 0x46, 0x46]) && (check([0x00, 0x01, 0x00, 0x00], {
  16470. offset: 4
  16471. }) || check([0x4F, 0x54, 0x54, 0x4F], {
  16472. offset: 4
  16473. }))) {
  16474. return {
  16475. ext: 'woff',
  16476. mime: 'font/woff'
  16477. };
  16478. }
  16479. if (check([0x77, 0x4F, 0x46, 0x32]) && (check([0x00, 0x01, 0x00, 0x00], {
  16480. offset: 4
  16481. }) || check([0x4F, 0x54, 0x54, 0x4F], {
  16482. offset: 4
  16483. }))) {
  16484. return {
  16485. ext: 'woff2',
  16486. mime: 'font/woff2'
  16487. };
  16488. }
  16489. if (check([0x4C, 0x50], {
  16490. offset: 34
  16491. }) && (check([0x00, 0x00, 0x01], {
  16492. offset: 8
  16493. }) || check([0x01, 0x00, 0x02], {
  16494. offset: 8
  16495. }) || check([0x02, 0x00, 0x02], {
  16496. offset: 8
  16497. }))) {
  16498. return {
  16499. ext: 'eot',
  16500. mime: 'application/vnd.ms-fontobject'
  16501. };
  16502. }
  16503. if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
  16504. return {
  16505. ext: 'ttf',
  16506. mime: 'font/ttf'
  16507. };
  16508. }
  16509. if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
  16510. return {
  16511. ext: 'otf',
  16512. mime: 'font/otf'
  16513. };
  16514. }
  16515. if (check([0x00, 0x00, 0x01, 0x00])) {
  16516. return {
  16517. ext: 'ico',
  16518. mime: 'image/x-icon'
  16519. };
  16520. }
  16521. if (check([0x00, 0x00, 0x02, 0x00])) {
  16522. return {
  16523. ext: 'cur',
  16524. mime: 'image/x-icon'
  16525. };
  16526. }
  16527. if (check([0x46, 0x4C, 0x56, 0x01])) {
  16528. return {
  16529. ext: 'flv',
  16530. mime: 'video/x-flv'
  16531. };
  16532. }
  16533. if (check([0x25, 0x21])) {
  16534. return {
  16535. ext: 'ps',
  16536. mime: 'application/postscript'
  16537. };
  16538. }
  16539. if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
  16540. return {
  16541. ext: 'xz',
  16542. mime: 'application/x-xz'
  16543. };
  16544. }
  16545. if (check([0x53, 0x51, 0x4C, 0x69])) {
  16546. return {
  16547. ext: 'sqlite',
  16548. mime: 'application/x-sqlite3'
  16549. };
  16550. }
  16551. if (check([0x4E, 0x45, 0x53, 0x1A])) {
  16552. return {
  16553. ext: 'nes',
  16554. mime: 'application/x-nintendo-nes-rom'
  16555. };
  16556. }
  16557. if (check([0x43, 0x72, 0x32, 0x34])) {
  16558. return {
  16559. ext: 'crx',
  16560. mime: 'application/x-google-chrome-extension'
  16561. };
  16562. }
  16563. if (check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28])) {
  16564. return {
  16565. ext: 'cab',
  16566. mime: 'application/vnd.ms-cab-compressed'
  16567. };
  16568. } // Needs to be before `ar` check
  16569. if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
  16570. return {
  16571. ext: 'deb',
  16572. mime: 'application/x-deb'
  16573. };
  16574. }
  16575. if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
  16576. return {
  16577. ext: 'ar',
  16578. mime: 'application/x-unix-archive'
  16579. };
  16580. }
  16581. if (check([0xED, 0xAB, 0xEE, 0xDB])) {
  16582. return {
  16583. ext: 'rpm',
  16584. mime: 'application/x-rpm'
  16585. };
  16586. }
  16587. if (check([0x1F, 0xA0]) || check([0x1F, 0x9D])) {
  16588. return {
  16589. ext: 'Z',
  16590. mime: 'application/x-compress'
  16591. };
  16592. }
  16593. if (check([0x4C, 0x5A, 0x49, 0x50])) {
  16594. return {
  16595. ext: 'lz',
  16596. mime: 'application/x-lzip'
  16597. };
  16598. }
  16599. if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
  16600. return {
  16601. ext: 'msi',
  16602. mime: 'application/x-msi'
  16603. };
  16604. }
  16605. if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
  16606. return {
  16607. ext: 'mxf',
  16608. mime: 'application/mxf'
  16609. };
  16610. }
  16611. if (check([0x47], {
  16612. offset: 4
  16613. }) && (check([0x47], {
  16614. offset: 192
  16615. }) || check([0x47], {
  16616. offset: 196
  16617. }))) {
  16618. return {
  16619. ext: 'mts',
  16620. mime: 'video/mp2t'
  16621. };
  16622. }
  16623. if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
  16624. return {
  16625. ext: 'blend',
  16626. mime: 'application/x-blender'
  16627. };
  16628. }
  16629. if (check([0x42, 0x50, 0x47, 0xFB])) {
  16630. return {
  16631. ext: 'bpg',
  16632. mime: 'image/bpg'
  16633. };
  16634. }
  16635. if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
  16636. // JPEG-2000 family
  16637. if (check([0x6A, 0x70, 0x32, 0x20], {
  16638. offset: 20
  16639. })) {
  16640. return {
  16641. ext: 'jp2',
  16642. mime: 'image/jp2'
  16643. };
  16644. }
  16645. if (check([0x6A, 0x70, 0x78, 0x20], {
  16646. offset: 20
  16647. })) {
  16648. return {
  16649. ext: 'jpx',
  16650. mime: 'image/jpx'
  16651. };
  16652. }
  16653. if (check([0x6A, 0x70, 0x6D, 0x20], {
  16654. offset: 20
  16655. })) {
  16656. return {
  16657. ext: 'jpm',
  16658. mime: 'image/jpm'
  16659. };
  16660. }
  16661. if (check([0x6D, 0x6A, 0x70, 0x32], {
  16662. offset: 20
  16663. })) {
  16664. return {
  16665. ext: 'mj2',
  16666. mime: 'image/mj2'
  16667. };
  16668. }
  16669. }
  16670. if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) {
  16671. return {
  16672. ext: 'aif',
  16673. mime: 'audio/aiff'
  16674. };
  16675. }
  16676. if (checkString('<?xml ')) {
  16677. return {
  16678. ext: 'xml',
  16679. mime: 'application/xml'
  16680. };
  16681. }
  16682. if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {
  16683. offset: 60
  16684. })) {
  16685. return {
  16686. ext: 'mobi',
  16687. mime: 'application/x-mobipocket-ebook'
  16688. };
  16689. } // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
  16690. if (check([0x66, 0x74, 0x79, 0x70], {
  16691. offset: 4
  16692. })) {
  16693. if (check([0x6D, 0x69, 0x66, 0x31], {
  16694. offset: 8
  16695. })) {
  16696. return {
  16697. ext: 'heic',
  16698. mime: 'image/heif'
  16699. };
  16700. }
  16701. if (check([0x6D, 0x73, 0x66, 0x31], {
  16702. offset: 8
  16703. })) {
  16704. return {
  16705. ext: 'heic',
  16706. mime: 'image/heif-sequence'
  16707. };
  16708. }
  16709. if (check([0x68, 0x65, 0x69, 0x63], {
  16710. offset: 8
  16711. }) || check([0x68, 0x65, 0x69, 0x78], {
  16712. offset: 8
  16713. })) {
  16714. return {
  16715. ext: 'heic',
  16716. mime: 'image/heic'
  16717. };
  16718. }
  16719. if (check([0x68, 0x65, 0x76, 0x63], {
  16720. offset: 8
  16721. }) || check([0x68, 0x65, 0x76, 0x78], {
  16722. offset: 8
  16723. })) {
  16724. return {
  16725. ext: 'heic',
  16726. mime: 'image/heic-sequence'
  16727. };
  16728. }
  16729. }
  16730. if (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
  16731. return {
  16732. ext: 'ktx',
  16733. mime: 'image/ktx'
  16734. };
  16735. }
  16736. return null;
  16737. };
  16738. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19}],250:[function(require,module,exports){
  16739. 'use strict';
  16740. var isCallable = require('is-callable');
  16741. var toStr = Object.prototype.toString;
  16742. var hasOwnProperty = Object.prototype.hasOwnProperty;
  16743. var forEachArray = function forEachArray(array, iterator, receiver) {
  16744. for (var i = 0, len = array.length; i < len; i++) {
  16745. if (hasOwnProperty.call(array, i)) {
  16746. if (receiver == null) {
  16747. iterator(array[i], i, array);
  16748. } else {
  16749. iterator.call(receiver, array[i], i, array);
  16750. }
  16751. }
  16752. }
  16753. };
  16754. var forEachString = function forEachString(string, iterator, receiver) {
  16755. for (var i = 0, len = string.length; i < len; i++) {
  16756. // no such thing as a sparse string.
  16757. if (receiver == null) {
  16758. iterator(string.charAt(i), i, string);
  16759. } else {
  16760. iterator.call(receiver, string.charAt(i), i, string);
  16761. }
  16762. }
  16763. };
  16764. var forEachObject = function forEachObject(object, iterator, receiver) {
  16765. for (var k in object) {
  16766. if (hasOwnProperty.call(object, k)) {
  16767. if (receiver == null) {
  16768. iterator(object[k], k, object);
  16769. } else {
  16770. iterator.call(receiver, object[k], k, object);
  16771. }
  16772. }
  16773. }
  16774. };
  16775. var forEach = function forEach(list, iterator, thisArg) {
  16776. if (!isCallable(iterator)) {
  16777. throw new TypeError('iterator must be a function');
  16778. }
  16779. var receiver;
  16780. if (arguments.length >= 3) {
  16781. receiver = thisArg;
  16782. }
  16783. if (toStr.call(list) === '[object Array]') {
  16784. forEachArray(list, iterator, receiver);
  16785. } else if (typeof list === 'string') {
  16786. forEachString(list, iterator, receiver);
  16787. } else {
  16788. forEachObject(list, iterator, receiver);
  16789. }
  16790. };
  16791. module.exports = forEach;
  16792. },{"is-callable":256}],251:[function(require,module,exports){
  16793. (function (global){
  16794. var win;
  16795. if (typeof window !== "undefined") {
  16796. win = window;
  16797. } else if (typeof global !== "undefined") {
  16798. win = global;
  16799. } else if (typeof self !== "undefined"){
  16800. win = self;
  16801. } else {
  16802. win = {};
  16803. }
  16804. module.exports = win;
  16805. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  16806. },{}],252:[function(require,module,exports){
  16807. var http = require('http')
  16808. var url = require('url')
  16809. var https = module.exports
  16810. for (var key in http) {
  16811. if (http.hasOwnProperty(key)) https[key] = http[key]
  16812. }
  16813. https.request = function (params, cb) {
  16814. params = validateParams(params)
  16815. return http.request.call(this, params, cb)
  16816. }
  16817. https.get = function (params, cb) {
  16818. params = validateParams(params)
  16819. return http.get.call(this, params, cb)
  16820. }
  16821. function validateParams (params) {
  16822. if (typeof params === 'string') {
  16823. params = url.parse(params)
  16824. }
  16825. if (!params.protocol) {
  16826. params.protocol = 'https:'
  16827. }
  16828. if (params.protocol !== 'https:') {
  16829. throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
  16830. }
  16831. return params
  16832. }
  16833. },{"http":335,"url":359}],253:[function(require,module,exports){
  16834. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  16835. var e, m
  16836. var eLen = (nBytes * 8) - mLen - 1
  16837. var eMax = (1 << eLen) - 1
  16838. var eBias = eMax >> 1
  16839. var nBits = -7
  16840. var i = isLE ? (nBytes - 1) : 0
  16841. var d = isLE ? -1 : 1
  16842. var s = buffer[offset + i]
  16843. i += d
  16844. e = s & ((1 << (-nBits)) - 1)
  16845. s >>= (-nBits)
  16846. nBits += eLen
  16847. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  16848. m = e & ((1 << (-nBits)) - 1)
  16849. e >>= (-nBits)
  16850. nBits += mLen
  16851. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  16852. if (e === 0) {
  16853. e = 1 - eBias
  16854. } else if (e === eMax) {
  16855. return m ? NaN : ((s ? -1 : 1) * Infinity)
  16856. } else {
  16857. m = m + Math.pow(2, mLen)
  16858. e = e - eBias
  16859. }
  16860. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  16861. }
  16862. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  16863. var e, m, c
  16864. var eLen = (nBytes * 8) - mLen - 1
  16865. var eMax = (1 << eLen) - 1
  16866. var eBias = eMax >> 1
  16867. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  16868. var i = isLE ? 0 : (nBytes - 1)
  16869. var d = isLE ? 1 : -1
  16870. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  16871. value = Math.abs(value)
  16872. if (isNaN(value) || value === Infinity) {
  16873. m = isNaN(value) ? 1 : 0
  16874. e = eMax
  16875. } else {
  16876. e = Math.floor(Math.log(value) / Math.LN2)
  16877. if (value * (c = Math.pow(2, -e)) < 1) {
  16878. e--
  16879. c *= 2
  16880. }
  16881. if (e + eBias >= 1) {
  16882. value += rt / c
  16883. } else {
  16884. value += rt * Math.pow(2, 1 - eBias)
  16885. }
  16886. if (value * c >= 2) {
  16887. e++
  16888. c /= 2
  16889. }
  16890. if (e + eBias >= eMax) {
  16891. m = 0
  16892. e = eMax
  16893. } else if (e + eBias >= 1) {
  16894. m = ((value * c) - 1) * Math.pow(2, mLen)
  16895. e = e + eBias
  16896. } else {
  16897. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  16898. e = 0
  16899. }
  16900. }
  16901. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  16902. e = (e << mLen) | m
  16903. eLen += mLen
  16904. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  16905. buffer[offset + i - d] |= s * 128
  16906. }
  16907. },{}],254:[function(require,module,exports){
  16908. if (typeof Object.create === 'function') {
  16909. // implementation from standard node.js 'util' module
  16910. module.exports = function inherits(ctor, superCtor) {
  16911. if (superCtor) {
  16912. ctor.super_ = superCtor
  16913. ctor.prototype = Object.create(superCtor.prototype, {
  16914. constructor: {
  16915. value: ctor,
  16916. enumerable: false,
  16917. writable: true,
  16918. configurable: true
  16919. }
  16920. })
  16921. }
  16922. };
  16923. } else {
  16924. // old school shim for old browsers
  16925. module.exports = function inherits(ctor, superCtor) {
  16926. if (superCtor) {
  16927. ctor.super_ = superCtor
  16928. var TempCtor = function () {}
  16929. TempCtor.prototype = superCtor.prototype
  16930. ctor.prototype = new TempCtor()
  16931. ctor.prototype.constructor = ctor
  16932. }
  16933. }
  16934. }
  16935. },{}],255:[function(require,module,exports){
  16936. /*!
  16937. * Determine if an object is a Buffer
  16938. *
  16939. * @author Feross Aboukhadijeh <https://feross.org>
  16940. * @license MIT
  16941. */
  16942. // The _isBuffer check is for Safari 5-7 support, because it's missing
  16943. // Object.prototype.constructor. Remove this eventually
  16944. module.exports = function (obj) {
  16945. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  16946. }
  16947. function isBuffer (obj) {
  16948. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  16949. }
  16950. // For Node v0.10 support. Remove this eventually.
  16951. function isSlowBuffer (obj) {
  16952. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  16953. }
  16954. },{}],256:[function(require,module,exports){
  16955. 'use strict';
  16956. var fnToStr = Function.prototype.toString;
  16957. var constructorRegex = /^\s*class\b/;
  16958. var isES6ClassFn = function isES6ClassFunction(value) {
  16959. try {
  16960. var fnStr = fnToStr.call(value);
  16961. return constructorRegex.test(fnStr);
  16962. } catch (e) {
  16963. return false; // not a function
  16964. }
  16965. };
  16966. var tryFunctionObject = function tryFunctionToStr(value) {
  16967. try {
  16968. if (isES6ClassFn(value)) { return false; }
  16969. fnToStr.call(value);
  16970. return true;
  16971. } catch (e) {
  16972. return false;
  16973. }
  16974. };
  16975. var toStr = Object.prototype.toString;
  16976. var fnClass = '[object Function]';
  16977. var genClass = '[object GeneratorFunction]';
  16978. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  16979. module.exports = function isCallable(value) {
  16980. if (!value) { return false; }
  16981. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  16982. if (typeof value === 'function' && !value.prototype) { return true; }
  16983. if (hasToStringTag) { return tryFunctionObject(value); }
  16984. if (isES6ClassFn(value)) { return false; }
  16985. var strClass = toStr.call(value);
  16986. return strClass === fnClass || strClass === genClass;
  16987. };
  16988. },{}],257:[function(require,module,exports){
  16989. module.exports = isFunction
  16990. var toString = Object.prototype.toString
  16991. function isFunction (fn) {
  16992. var string = toString.call(fn)
  16993. return string === '[object Function]' ||
  16994. (typeof fn === 'function' && string !== '[object RegExp]') ||
  16995. (typeof window !== 'undefined' &&
  16996. // IE8 and below
  16997. (fn === window.setTimeout ||
  16998. fn === window.alert ||
  16999. fn === window.confirm ||
  17000. fn === window.prompt))
  17001. };
  17002. },{}],258:[function(require,module,exports){
  17003. var toString = {}.toString;
  17004. module.exports = Array.isArray || function (arr) {
  17005. return toString.call(arr) == '[object Array]';
  17006. };
  17007. },{}],259:[function(require,module,exports){
  17008. var encode = require('./lib/encoder'),
  17009. decode = require('./lib/decoder');
  17010. module.exports = {
  17011. encode: encode,
  17012. decode: decode
  17013. };
  17014. },{"./lib/decoder":260,"./lib/encoder":261}],260:[function(require,module,exports){
  17015. (function (Buffer){
  17016. /* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
  17017. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  17018. /*
  17019. Copyright 2011 notmasteryet
  17020. Licensed under the Apache License, Version 2.0 (the "License");
  17021. you may not use this file except in compliance with the License.
  17022. You may obtain a copy of the License at
  17023. http://www.apache.org/licenses/LICENSE-2.0
  17024. Unless required by applicable law or agreed to in writing, software
  17025. distributed under the License is distributed on an "AS IS" BASIS,
  17026. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17027. See the License for the specific language governing permissions and
  17028. limitations under the License.
  17029. */
  17030. // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
  17031. // (www.w3.org/Graphics/JPEG/itu-t81.pdf)
  17032. // - The JFIF specification can be found in the JPEG File Interchange Format
  17033. // (www.w3.org/Graphics/JPEG/jfif3.pdf)
  17034. // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
  17035. // in PostScript Level 2, Technical Note #5116
  17036. // (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
  17037. var JpegImage = (function jpegImage() {
  17038. "use strict";
  17039. var dctZigZag = new Int32Array([
  17040. 0,
  17041. 1, 8,
  17042. 16, 9, 2,
  17043. 3, 10, 17, 24,
  17044. 32, 25, 18, 11, 4,
  17045. 5, 12, 19, 26, 33, 40,
  17046. 48, 41, 34, 27, 20, 13, 6,
  17047. 7, 14, 21, 28, 35, 42, 49, 56,
  17048. 57, 50, 43, 36, 29, 22, 15,
  17049. 23, 30, 37, 44, 51, 58,
  17050. 59, 52, 45, 38, 31,
  17051. 39, 46, 53, 60,
  17052. 61, 54, 47,
  17053. 55, 62,
  17054. 63
  17055. ]);
  17056. var dctCos1 = 4017 // cos(pi/16)
  17057. var dctSin1 = 799 // sin(pi/16)
  17058. var dctCos3 = 3406 // cos(3*pi/16)
  17059. var dctSin3 = 2276 // sin(3*pi/16)
  17060. var dctCos6 = 1567 // cos(6*pi/16)
  17061. var dctSin6 = 3784 // sin(6*pi/16)
  17062. var dctSqrt2 = 5793 // sqrt(2)
  17063. var dctSqrt1d2 = 2896 // sqrt(2) / 2
  17064. function constructor() {
  17065. }
  17066. function buildHuffmanTable(codeLengths, values) {
  17067. var k = 0, code = [], i, j, length = 16;
  17068. while (length > 0 && !codeLengths[length - 1])
  17069. length--;
  17070. code.push({children: [], index: 0});
  17071. var p = code[0], q;
  17072. for (i = 0; i < length; i++) {
  17073. for (j = 0; j < codeLengths[i]; j++) {
  17074. p = code.pop();
  17075. p.children[p.index] = values[k];
  17076. while (p.index > 0) {
  17077. p = code.pop();
  17078. }
  17079. p.index++;
  17080. code.push(p);
  17081. while (code.length <= i) {
  17082. code.push(q = {children: [], index: 0});
  17083. p.children[p.index] = q.children;
  17084. p = q;
  17085. }
  17086. k++;
  17087. }
  17088. if (i + 1 < length) {
  17089. // p here points to last code
  17090. code.push(q = {children: [], index: 0});
  17091. p.children[p.index] = q.children;
  17092. p = q;
  17093. }
  17094. }
  17095. return code[0].children;
  17096. }
  17097. function decodeScan(data, offset,
  17098. frame, components, resetInterval,
  17099. spectralStart, spectralEnd,
  17100. successivePrev, successive) {
  17101. var precision = frame.precision;
  17102. var samplesPerLine = frame.samplesPerLine;
  17103. var scanLines = frame.scanLines;
  17104. var mcusPerLine = frame.mcusPerLine;
  17105. var progressive = frame.progressive;
  17106. var maxH = frame.maxH, maxV = frame.maxV;
  17107. var startOffset = offset, bitsData = 0, bitsCount = 0;
  17108. function readBit() {
  17109. if (bitsCount > 0) {
  17110. bitsCount--;
  17111. return (bitsData >> bitsCount) & 1;
  17112. }
  17113. bitsData = data[offset++];
  17114. if (bitsData == 0xFF) {
  17115. var nextByte = data[offset++];
  17116. if (nextByte) {
  17117. throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16));
  17118. }
  17119. // unstuff 0
  17120. }
  17121. bitsCount = 7;
  17122. return bitsData >>> 7;
  17123. }
  17124. function decodeHuffman(tree) {
  17125. var node = tree, bit;
  17126. while ((bit = readBit()) !== null) {
  17127. node = node[bit];
  17128. if (typeof node === 'number')
  17129. return node;
  17130. if (typeof node !== 'object')
  17131. throw new Error("invalid huffman sequence");
  17132. }
  17133. return null;
  17134. }
  17135. function receive(length) {
  17136. var n = 0;
  17137. while (length > 0) {
  17138. var bit = readBit();
  17139. if (bit === null) return;
  17140. n = (n << 1) | bit;
  17141. length--;
  17142. }
  17143. return n;
  17144. }
  17145. function receiveAndExtend(length) {
  17146. var n = receive(length);
  17147. if (n >= 1 << (length - 1))
  17148. return n;
  17149. return n + (-1 << length) + 1;
  17150. }
  17151. function decodeBaseline(component, zz) {
  17152. var t = decodeHuffman(component.huffmanTableDC);
  17153. var diff = t === 0 ? 0 : receiveAndExtend(t);
  17154. zz[0]= (component.pred += diff);
  17155. var k = 1;
  17156. while (k < 64) {
  17157. var rs = decodeHuffman(component.huffmanTableAC);
  17158. var s = rs & 15, r = rs >> 4;
  17159. if (s === 0) {
  17160. if (r < 15)
  17161. break;
  17162. k += 16;
  17163. continue;
  17164. }
  17165. k += r;
  17166. var z = dctZigZag[k];
  17167. zz[z] = receiveAndExtend(s);
  17168. k++;
  17169. }
  17170. }
  17171. function decodeDCFirst(component, zz) {
  17172. var t = decodeHuffman(component.huffmanTableDC);
  17173. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  17174. zz[0] = (component.pred += diff);
  17175. }
  17176. function decodeDCSuccessive(component, zz) {
  17177. zz[0] |= readBit() << successive;
  17178. }
  17179. var eobrun = 0;
  17180. function decodeACFirst(component, zz) {
  17181. if (eobrun > 0) {
  17182. eobrun--;
  17183. return;
  17184. }
  17185. var k = spectralStart, e = spectralEnd;
  17186. while (k <= e) {
  17187. var rs = decodeHuffman(component.huffmanTableAC);
  17188. var s = rs & 15, r = rs >> 4;
  17189. if (s === 0) {
  17190. if (r < 15) {
  17191. eobrun = receive(r) + (1 << r) - 1;
  17192. break;
  17193. }
  17194. k += 16;
  17195. continue;
  17196. }
  17197. k += r;
  17198. var z = dctZigZag[k];
  17199. zz[z] = receiveAndExtend(s) * (1 << successive);
  17200. k++;
  17201. }
  17202. }
  17203. var successiveACState = 0, successiveACNextValue;
  17204. function decodeACSuccessive(component, zz) {
  17205. var k = spectralStart, e = spectralEnd, r = 0;
  17206. while (k <= e) {
  17207. var z = dctZigZag[k];
  17208. var direction = zz[z] < 0 ? -1 : 1;
  17209. switch (successiveACState) {
  17210. case 0: // initial state
  17211. var rs = decodeHuffman(component.huffmanTableAC);
  17212. var s = rs & 15, r = rs >> 4;
  17213. if (s === 0) {
  17214. if (r < 15) {
  17215. eobrun = receive(r) + (1 << r);
  17216. successiveACState = 4;
  17217. } else {
  17218. r = 16;
  17219. successiveACState = 1;
  17220. }
  17221. } else {
  17222. if (s !== 1)
  17223. throw new Error("invalid ACn encoding");
  17224. successiveACNextValue = receiveAndExtend(s);
  17225. successiveACState = r ? 2 : 3;
  17226. }
  17227. continue;
  17228. case 1: // skipping r zero items
  17229. case 2:
  17230. if (zz[z])
  17231. zz[z] += (readBit() << successive) * direction;
  17232. else {
  17233. r--;
  17234. if (r === 0)
  17235. successiveACState = successiveACState == 2 ? 3 : 0;
  17236. }
  17237. break;
  17238. case 3: // set value for a zero item
  17239. if (zz[z])
  17240. zz[z] += (readBit() << successive) * direction;
  17241. else {
  17242. zz[z] = successiveACNextValue << successive;
  17243. successiveACState = 0;
  17244. }
  17245. break;
  17246. case 4: // eob
  17247. if (zz[z])
  17248. zz[z] += (readBit() << successive) * direction;
  17249. break;
  17250. }
  17251. k++;
  17252. }
  17253. if (successiveACState === 4) {
  17254. eobrun--;
  17255. if (eobrun === 0)
  17256. successiveACState = 0;
  17257. }
  17258. }
  17259. function decodeMcu(component, decode, mcu, row, col) {
  17260. var mcuRow = (mcu / mcusPerLine) | 0;
  17261. var mcuCol = mcu % mcusPerLine;
  17262. var blockRow = mcuRow * component.v + row;
  17263. var blockCol = mcuCol * component.h + col;
  17264. decode(component, component.blocks[blockRow][blockCol]);
  17265. }
  17266. function decodeBlock(component, decode, mcu) {
  17267. var blockRow = (mcu / component.blocksPerLine) | 0;
  17268. var blockCol = mcu % component.blocksPerLine;
  17269. decode(component, component.blocks[blockRow][blockCol]);
  17270. }
  17271. var componentsLength = components.length;
  17272. var component, i, j, k, n;
  17273. var decodeFn;
  17274. if (progressive) {
  17275. if (spectralStart === 0)
  17276. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  17277. else
  17278. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  17279. } else {
  17280. decodeFn = decodeBaseline;
  17281. }
  17282. var mcu = 0, marker;
  17283. var mcuExpected;
  17284. if (componentsLength == 1) {
  17285. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  17286. } else {
  17287. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  17288. }
  17289. if (!resetInterval) resetInterval = mcuExpected;
  17290. var h, v;
  17291. while (mcu < mcuExpected) {
  17292. // reset interval stuff
  17293. for (i = 0; i < componentsLength; i++)
  17294. components[i].pred = 0;
  17295. eobrun = 0;
  17296. if (componentsLength == 1) {
  17297. component = components[0];
  17298. for (n = 0; n < resetInterval; n++) {
  17299. decodeBlock(component, decodeFn, mcu);
  17300. mcu++;
  17301. }
  17302. } else {
  17303. for (n = 0; n < resetInterval; n++) {
  17304. for (i = 0; i < componentsLength; i++) {
  17305. component = components[i];
  17306. h = component.h;
  17307. v = component.v;
  17308. for (j = 0; j < v; j++) {
  17309. for (k = 0; k < h; k++) {
  17310. decodeMcu(component, decodeFn, mcu, j, k);
  17311. }
  17312. }
  17313. }
  17314. mcu++;
  17315. // If we've reached our expected MCU's, stop decoding
  17316. if (mcu === mcuExpected) break;
  17317. }
  17318. }
  17319. // find marker
  17320. bitsCount = 0;
  17321. marker = (data[offset] << 8) | data[offset + 1];
  17322. if (marker < 0xFF00) {
  17323. throw new Error("marker was not found");
  17324. }
  17325. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  17326. offset += 2;
  17327. }
  17328. else
  17329. break;
  17330. }
  17331. return offset - startOffset;
  17332. }
  17333. function buildComponentData(frame, component) {
  17334. var lines = [];
  17335. var blocksPerLine = component.blocksPerLine;
  17336. var blocksPerColumn = component.blocksPerColumn;
  17337. var samplesPerLine = blocksPerLine << 3;
  17338. var R = new Int32Array(64), r = new Uint8Array(64);
  17339. // A port of poppler's IDCT method which in turn is taken from:
  17340. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  17341. // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
  17342. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  17343. // 988-991.
  17344. function quantizeAndInverse(zz, dataOut, dataIn) {
  17345. var qt = component.quantizationTable;
  17346. var v0, v1, v2, v3, v4, v5, v6, v7, t;
  17347. var p = dataIn;
  17348. var i;
  17349. // dequant
  17350. for (i = 0; i < 64; i++)
  17351. p[i] = zz[i] * qt[i];
  17352. // inverse DCT on rows
  17353. for (i = 0; i < 8; ++i) {
  17354. var row = 8 * i;
  17355. // check for all-zero AC coefficients
  17356. if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&
  17357. p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&
  17358. p[7 + row] == 0) {
  17359. t = (dctSqrt2 * p[0 + row] + 512) >> 10;
  17360. p[0 + row] = t;
  17361. p[1 + row] = t;
  17362. p[2 + row] = t;
  17363. p[3 + row] = t;
  17364. p[4 + row] = t;
  17365. p[5 + row] = t;
  17366. p[6 + row] = t;
  17367. p[7 + row] = t;
  17368. continue;
  17369. }
  17370. // stage 4
  17371. v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
  17372. v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
  17373. v2 = p[2 + row];
  17374. v3 = p[6 + row];
  17375. v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
  17376. v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
  17377. v5 = p[3 + row] << 4;
  17378. v6 = p[5 + row] << 4;
  17379. // stage 3
  17380. t = (v0 - v1+ 1) >> 1;
  17381. v0 = (v0 + v1 + 1) >> 1;
  17382. v1 = t;
  17383. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  17384. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  17385. v3 = t;
  17386. t = (v4 - v6 + 1) >> 1;
  17387. v4 = (v4 + v6 + 1) >> 1;
  17388. v6 = t;
  17389. t = (v7 + v5 + 1) >> 1;
  17390. v5 = (v7 - v5 + 1) >> 1;
  17391. v7 = t;
  17392. // stage 2
  17393. t = (v0 - v3 + 1) >> 1;
  17394. v0 = (v0 + v3 + 1) >> 1;
  17395. v3 = t;
  17396. t = (v1 - v2 + 1) >> 1;
  17397. v1 = (v1 + v2 + 1) >> 1;
  17398. v2 = t;
  17399. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  17400. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  17401. v7 = t;
  17402. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  17403. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  17404. v6 = t;
  17405. // stage 1
  17406. p[0 + row] = v0 + v7;
  17407. p[7 + row] = v0 - v7;
  17408. p[1 + row] = v1 + v6;
  17409. p[6 + row] = v1 - v6;
  17410. p[2 + row] = v2 + v5;
  17411. p[5 + row] = v2 - v5;
  17412. p[3 + row] = v3 + v4;
  17413. p[4 + row] = v3 - v4;
  17414. }
  17415. // inverse DCT on columns
  17416. for (i = 0; i < 8; ++i) {
  17417. var col = i;
  17418. // check for all-zero AC coefficients
  17419. if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&
  17420. p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&
  17421. p[7*8 + col] == 0) {
  17422. t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
  17423. p[0*8 + col] = t;
  17424. p[1*8 + col] = t;
  17425. p[2*8 + col] = t;
  17426. p[3*8 + col] = t;
  17427. p[4*8 + col] = t;
  17428. p[5*8 + col] = t;
  17429. p[6*8 + col] = t;
  17430. p[7*8 + col] = t;
  17431. continue;
  17432. }
  17433. // stage 4
  17434. v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;
  17435. v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;
  17436. v2 = p[2*8 + col];
  17437. v3 = p[6*8 + col];
  17438. v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;
  17439. v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;
  17440. v5 = p[3*8 + col];
  17441. v6 = p[5*8 + col];
  17442. // stage 3
  17443. t = (v0 - v1 + 1) >> 1;
  17444. v0 = (v0 + v1 + 1) >> 1;
  17445. v1 = t;
  17446. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  17447. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  17448. v3 = t;
  17449. t = (v4 - v6 + 1) >> 1;
  17450. v4 = (v4 + v6 + 1) >> 1;
  17451. v6 = t;
  17452. t = (v7 + v5 + 1) >> 1;
  17453. v5 = (v7 - v5 + 1) >> 1;
  17454. v7 = t;
  17455. // stage 2
  17456. t = (v0 - v3 + 1) >> 1;
  17457. v0 = (v0 + v3 + 1) >> 1;
  17458. v3 = t;
  17459. t = (v1 - v2 + 1) >> 1;
  17460. v1 = (v1 + v2 + 1) >> 1;
  17461. v2 = t;
  17462. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  17463. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  17464. v7 = t;
  17465. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  17466. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  17467. v6 = t;
  17468. // stage 1
  17469. p[0*8 + col] = v0 + v7;
  17470. p[7*8 + col] = v0 - v7;
  17471. p[1*8 + col] = v1 + v6;
  17472. p[6*8 + col] = v1 - v6;
  17473. p[2*8 + col] = v2 + v5;
  17474. p[5*8 + col] = v2 - v5;
  17475. p[3*8 + col] = v3 + v4;
  17476. p[4*8 + col] = v3 - v4;
  17477. }
  17478. // convert to 8-bit integers
  17479. for (i = 0; i < 64; ++i) {
  17480. var sample = 128 + ((p[i] + 8) >> 4);
  17481. dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
  17482. }
  17483. }
  17484. var i, j;
  17485. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  17486. var scanLine = blockRow << 3;
  17487. for (i = 0; i < 8; i++)
  17488. lines.push(new Uint8Array(samplesPerLine));
  17489. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  17490. quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
  17491. var offset = 0, sample = blockCol << 3;
  17492. for (j = 0; j < 8; j++) {
  17493. var line = lines[scanLine + j];
  17494. for (i = 0; i < 8; i++)
  17495. line[sample + i] = r[offset++];
  17496. }
  17497. }
  17498. }
  17499. return lines;
  17500. }
  17501. function clampTo8bit(a) {
  17502. return a < 0 ? 0 : a > 255 ? 255 : a;
  17503. }
  17504. constructor.prototype = {
  17505. load: function load(path) {
  17506. var xhr = new XMLHttpRequest();
  17507. xhr.open("GET", path, true);
  17508. xhr.responseType = "arraybuffer";
  17509. xhr.onload = (function() {
  17510. // TODO catch parse error
  17511. var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  17512. this.parse(data);
  17513. if (this.onload)
  17514. this.onload();
  17515. }).bind(this);
  17516. xhr.send(null);
  17517. },
  17518. parse: function parse(data) {
  17519. var offset = 0, length = data.length;
  17520. function readUint16() {
  17521. var value = (data[offset] << 8) | data[offset + 1];
  17522. offset += 2;
  17523. return value;
  17524. }
  17525. function readDataBlock() {
  17526. var length = readUint16();
  17527. var array = data.subarray(offset, offset + length - 2);
  17528. offset += array.length;
  17529. return array;
  17530. }
  17531. function prepareComponents(frame) {
  17532. var maxH = 0, maxV = 0;
  17533. var component, componentId;
  17534. for (componentId in frame.components) {
  17535. if (frame.components.hasOwnProperty(componentId)) {
  17536. component = frame.components[componentId];
  17537. if (maxH < component.h) maxH = component.h;
  17538. if (maxV < component.v) maxV = component.v;
  17539. }
  17540. }
  17541. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
  17542. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
  17543. for (componentId in frame.components) {
  17544. if (frame.components.hasOwnProperty(componentId)) {
  17545. component = frame.components[componentId];
  17546. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
  17547. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
  17548. var blocksPerLineForMcu = mcusPerLine * component.h;
  17549. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  17550. var blocks = [];
  17551. for (var i = 0; i < blocksPerColumnForMcu; i++) {
  17552. var row = [];
  17553. for (var j = 0; j < blocksPerLineForMcu; j++)
  17554. row.push(new Int32Array(64));
  17555. blocks.push(row);
  17556. }
  17557. component.blocksPerLine = blocksPerLine;
  17558. component.blocksPerColumn = blocksPerColumn;
  17559. component.blocks = blocks;
  17560. }
  17561. }
  17562. frame.maxH = maxH;
  17563. frame.maxV = maxV;
  17564. frame.mcusPerLine = mcusPerLine;
  17565. frame.mcusPerColumn = mcusPerColumn;
  17566. }
  17567. var jfif = null;
  17568. var adobe = null;
  17569. var pixels = null;
  17570. var frame, resetInterval;
  17571. var quantizationTables = [], frames = [];
  17572. var huffmanTablesAC = [], huffmanTablesDC = [];
  17573. var fileMarker = readUint16();
  17574. if (fileMarker != 0xFFD8) { // SOI (Start of Image)
  17575. throw new Error("SOI not found");
  17576. }
  17577. fileMarker = readUint16();
  17578. while (fileMarker != 0xFFD9) { // EOI (End of image)
  17579. var i, j, l;
  17580. switch(fileMarker) {
  17581. case 0xFF00: break;
  17582. case 0xFFE0: // APP0 (Application Specific)
  17583. case 0xFFE1: // APP1
  17584. case 0xFFE2: // APP2
  17585. case 0xFFE3: // APP3
  17586. case 0xFFE4: // APP4
  17587. case 0xFFE5: // APP5
  17588. case 0xFFE6: // APP6
  17589. case 0xFFE7: // APP7
  17590. case 0xFFE8: // APP8
  17591. case 0xFFE9: // APP9
  17592. case 0xFFEA: // APP10
  17593. case 0xFFEB: // APP11
  17594. case 0xFFEC: // APP12
  17595. case 0xFFED: // APP13
  17596. case 0xFFEE: // APP14
  17597. case 0xFFEF: // APP15
  17598. case 0xFFFE: // COM (Comment)
  17599. var appData = readDataBlock();
  17600. if (fileMarker === 0xFFE0) {
  17601. if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
  17602. appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
  17603. jfif = {
  17604. version: { major: appData[5], minor: appData[6] },
  17605. densityUnits: appData[7],
  17606. xDensity: (appData[8] << 8) | appData[9],
  17607. yDensity: (appData[10] << 8) | appData[11],
  17608. thumbWidth: appData[12],
  17609. thumbHeight: appData[13],
  17610. thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
  17611. };
  17612. }
  17613. }
  17614. // TODO APP1 - Exif
  17615. if (fileMarker === 0xFFEE) {
  17616. if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
  17617. appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
  17618. adobe = {
  17619. version: appData[6],
  17620. flags0: (appData[7] << 8) | appData[8],
  17621. flags1: (appData[9] << 8) | appData[10],
  17622. transformCode: appData[11]
  17623. };
  17624. }
  17625. }
  17626. break;
  17627. case 0xFFDB: // DQT (Define Quantization Tables)
  17628. var quantizationTablesLength = readUint16();
  17629. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  17630. while (offset < quantizationTablesEnd) {
  17631. var quantizationTableSpec = data[offset++];
  17632. var tableData = new Int32Array(64);
  17633. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  17634. for (j = 0; j < 64; j++) {
  17635. var z = dctZigZag[j];
  17636. tableData[z] = data[offset++];
  17637. }
  17638. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  17639. for (j = 0; j < 64; j++) {
  17640. var z = dctZigZag[j];
  17641. tableData[z] = readUint16();
  17642. }
  17643. } else
  17644. throw new Error("DQT: invalid table spec");
  17645. quantizationTables[quantizationTableSpec & 15] = tableData;
  17646. }
  17647. break;
  17648. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  17649. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  17650. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  17651. readUint16(); // skip data length
  17652. frame = {};
  17653. frame.extended = (fileMarker === 0xFFC1);
  17654. frame.progressive = (fileMarker === 0xFFC2);
  17655. frame.precision = data[offset++];
  17656. frame.scanLines = readUint16();
  17657. frame.samplesPerLine = readUint16();
  17658. frame.components = {};
  17659. frame.componentsOrder = [];
  17660. var componentsCount = data[offset++], componentId;
  17661. var maxH = 0, maxV = 0;
  17662. for (i = 0; i < componentsCount; i++) {
  17663. componentId = data[offset];
  17664. var h = data[offset + 1] >> 4;
  17665. var v = data[offset + 1] & 15;
  17666. var qId = data[offset + 2];
  17667. frame.componentsOrder.push(componentId);
  17668. frame.components[componentId] = {
  17669. h: h,
  17670. v: v,
  17671. quantizationIdx: qId
  17672. };
  17673. offset += 3;
  17674. }
  17675. prepareComponents(frame);
  17676. frames.push(frame);
  17677. break;
  17678. case 0xFFC4: // DHT (Define Huffman Tables)
  17679. var huffmanLength = readUint16();
  17680. for (i = 2; i < huffmanLength;) {
  17681. var huffmanTableSpec = data[offset++];
  17682. var codeLengths = new Uint8Array(16);
  17683. var codeLengthSum = 0;
  17684. for (j = 0; j < 16; j++, offset++)
  17685. codeLengthSum += (codeLengths[j] = data[offset]);
  17686. var huffmanValues = new Uint8Array(codeLengthSum);
  17687. for (j = 0; j < codeLengthSum; j++, offset++)
  17688. huffmanValues[j] = data[offset];
  17689. i += 17 + codeLengthSum;
  17690. ((huffmanTableSpec >> 4) === 0 ?
  17691. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  17692. buildHuffmanTable(codeLengths, huffmanValues);
  17693. }
  17694. break;
  17695. case 0xFFDD: // DRI (Define Restart Interval)
  17696. readUint16(); // skip data length
  17697. resetInterval = readUint16();
  17698. break;
  17699. case 0xFFDA: // SOS (Start of Scan)
  17700. var scanLength = readUint16();
  17701. var selectorsCount = data[offset++];
  17702. var components = [], component;
  17703. for (i = 0; i < selectorsCount; i++) {
  17704. component = frame.components[data[offset++]];
  17705. var tableSpec = data[offset++];
  17706. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  17707. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  17708. components.push(component);
  17709. }
  17710. var spectralStart = data[offset++];
  17711. var spectralEnd = data[offset++];
  17712. var successiveApproximation = data[offset++];
  17713. var processed = decodeScan(data, offset,
  17714. frame, components, resetInterval,
  17715. spectralStart, spectralEnd,
  17716. successiveApproximation >> 4, successiveApproximation & 15);
  17717. offset += processed;
  17718. break;
  17719. case 0xFFFF: // Fill bytes
  17720. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  17721. offset--;
  17722. }
  17723. break;
  17724. default:
  17725. if (data[offset - 3] == 0xFF &&
  17726. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  17727. // could be incorrect encoding -- last 0xFF byte of the previous
  17728. // block was eaten by the encoder
  17729. offset -= 3;
  17730. break;
  17731. }
  17732. throw new Error("unknown JPEG marker " + fileMarker.toString(16));
  17733. }
  17734. fileMarker = readUint16();
  17735. }
  17736. if (frames.length != 1)
  17737. throw new Error("only single frame JPEGs supported");
  17738. // set each frame's components quantization table
  17739. for (var i = 0; i < frames.length; i++) {
  17740. var cp = frames[i].components;
  17741. for (var j in cp) {
  17742. cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
  17743. delete cp[j].quantizationIdx;
  17744. }
  17745. }
  17746. this.width = frame.samplesPerLine;
  17747. this.height = frame.scanLines;
  17748. this.jfif = jfif;
  17749. this.adobe = adobe;
  17750. this.components = [];
  17751. for (var i = 0; i < frame.componentsOrder.length; i++) {
  17752. var component = frame.components[frame.componentsOrder[i]];
  17753. this.components.push({
  17754. lines: buildComponentData(frame, component),
  17755. scaleX: component.h / frame.maxH,
  17756. scaleY: component.v / frame.maxV
  17757. });
  17758. }
  17759. },
  17760. getData: function getData(width, height) {
  17761. var scaleX = this.width / width, scaleY = this.height / height;
  17762. var component1, component2, component3, component4;
  17763. var component1Line, component2Line, component3Line, component4Line;
  17764. var x, y;
  17765. var offset = 0;
  17766. var Y, Cb, Cr, K, C, M, Ye, R, G, B;
  17767. var colorTransform;
  17768. var dataLength = width * height * this.components.length;
  17769. var data = new Uint8Array(dataLength);
  17770. switch (this.components.length) {
  17771. case 1:
  17772. component1 = this.components[0];
  17773. for (y = 0; y < height; y++) {
  17774. component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
  17775. for (x = 0; x < width; x++) {
  17776. Y = component1Line[0 | (x * component1.scaleX * scaleX)];
  17777. data[offset++] = Y;
  17778. }
  17779. }
  17780. break;
  17781. case 2:
  17782. // PDF might compress two component data in custom colorspace
  17783. component1 = this.components[0];
  17784. component2 = this.components[1];
  17785. for (y = 0; y < height; y++) {
  17786. component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
  17787. component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
  17788. for (x = 0; x < width; x++) {
  17789. Y = component1Line[0 | (x * component1.scaleX * scaleX)];
  17790. data[offset++] = Y;
  17791. Y = component2Line[0 | (x * component2.scaleX * scaleX)];
  17792. data[offset++] = Y;
  17793. }
  17794. }
  17795. break;
  17796. case 3:
  17797. // The default transform for three components is true
  17798. colorTransform = true;
  17799. // The adobe transform marker overrides any previous setting
  17800. if (this.adobe && this.adobe.transformCode)
  17801. colorTransform = true;
  17802. else if (typeof this.colorTransform !== 'undefined')
  17803. colorTransform = !!this.colorTransform;
  17804. component1 = this.components[0];
  17805. component2 = this.components[1];
  17806. component3 = this.components[2];
  17807. for (y = 0; y < height; y++) {
  17808. component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
  17809. component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
  17810. component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
  17811. for (x = 0; x < width; x++) {
  17812. if (!colorTransform) {
  17813. R = component1Line[0 | (x * component1.scaleX * scaleX)];
  17814. G = component2Line[0 | (x * component2.scaleX * scaleX)];
  17815. B = component3Line[0 | (x * component3.scaleX * scaleX)];
  17816. } else {
  17817. Y = component1Line[0 | (x * component1.scaleX * scaleX)];
  17818. Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
  17819. Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
  17820. R = clampTo8bit(Y + 1.402 * (Cr - 128));
  17821. G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
  17822. B = clampTo8bit(Y + 1.772 * (Cb - 128));
  17823. }
  17824. data[offset++] = R;
  17825. data[offset++] = G;
  17826. data[offset++] = B;
  17827. }
  17828. }
  17829. break;
  17830. case 4:
  17831. if (!this.adobe)
  17832. throw 'Unsupported color mode (4 components)';
  17833. // The default transform for four components is false
  17834. colorTransform = false;
  17835. // The adobe transform marker overrides any previous setting
  17836. if (this.adobe && this.adobe.transformCode)
  17837. colorTransform = true;
  17838. else if (typeof this.colorTransform !== 'undefined')
  17839. colorTransform = !!this.colorTransform;
  17840. component1 = this.components[0];
  17841. component2 = this.components[1];
  17842. component3 = this.components[2];
  17843. component4 = this.components[3];
  17844. for (y = 0; y < height; y++) {
  17845. component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
  17846. component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
  17847. component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
  17848. component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];
  17849. for (x = 0; x < width; x++) {
  17850. if (!colorTransform) {
  17851. C = component1Line[0 | (x * component1.scaleX * scaleX)];
  17852. M = component2Line[0 | (x * component2.scaleX * scaleX)];
  17853. Ye = component3Line[0 | (x * component3.scaleX * scaleX)];
  17854. K = component4Line[0 | (x * component4.scaleX * scaleX)];
  17855. } else {
  17856. Y = component1Line[0 | (x * component1.scaleX * scaleX)];
  17857. Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
  17858. Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
  17859. K = component4Line[0 | (x * component4.scaleX * scaleX)];
  17860. C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
  17861. M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
  17862. Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
  17863. }
  17864. data[offset++] = 255-C;
  17865. data[offset++] = 255-M;
  17866. data[offset++] = 255-Ye;
  17867. data[offset++] = 255-K;
  17868. }
  17869. }
  17870. break;
  17871. default:
  17872. throw 'Unsupported color mode';
  17873. }
  17874. return data;
  17875. },
  17876. copyToImageData: function copyToImageData(imageData) {
  17877. var width = imageData.width, height = imageData.height;
  17878. var imageDataArray = imageData.data;
  17879. var data = this.getData(width, height);
  17880. var i = 0, j = 0, x, y;
  17881. var Y, K, C, M, R, G, B;
  17882. switch (this.components.length) {
  17883. case 1:
  17884. for (y = 0; y < height; y++) {
  17885. for (x = 0; x < width; x++) {
  17886. Y = data[i++];
  17887. imageDataArray[j++] = Y;
  17888. imageDataArray[j++] = Y;
  17889. imageDataArray[j++] = Y;
  17890. imageDataArray[j++] = 255;
  17891. }
  17892. }
  17893. break;
  17894. case 3:
  17895. for (y = 0; y < height; y++) {
  17896. for (x = 0; x < width; x++) {
  17897. R = data[i++];
  17898. G = data[i++];
  17899. B = data[i++];
  17900. imageDataArray[j++] = R;
  17901. imageDataArray[j++] = G;
  17902. imageDataArray[j++] = B;
  17903. imageDataArray[j++] = 255;
  17904. }
  17905. }
  17906. break;
  17907. case 4:
  17908. for (y = 0; y < height; y++) {
  17909. for (x = 0; x < width; x++) {
  17910. C = data[i++];
  17911. M = data[i++];
  17912. Y = data[i++];
  17913. K = data[i++];
  17914. R = 255 - clampTo8bit(C * (1 - K / 255) + K);
  17915. G = 255 - clampTo8bit(M * (1 - K / 255) + K);
  17916. B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
  17917. imageDataArray[j++] = R;
  17918. imageDataArray[j++] = G;
  17919. imageDataArray[j++] = B;
  17920. imageDataArray[j++] = 255;
  17921. }
  17922. }
  17923. break;
  17924. default:
  17925. throw 'Unsupported color mode';
  17926. }
  17927. }
  17928. };
  17929. return constructor;
  17930. })();
  17931. module.exports = decode;
  17932. function decode(jpegData, useTArray) {
  17933. var arr = new Uint8Array(jpegData);
  17934. var decoder = new JpegImage();
  17935. decoder.parse(arr);
  17936. var image = {
  17937. width: decoder.width,
  17938. height: decoder.height,
  17939. data: useTArray ?
  17940. new Uint8Array(decoder.width * decoder.height * 4) :
  17941. new Buffer(decoder.width * decoder.height * 4)
  17942. };
  17943. decoder.copyToImageData(image);
  17944. return image;
  17945. }
  17946. }).call(this,require("buffer").Buffer)
  17947. },{"buffer":47}],261:[function(require,module,exports){
  17948. (function (Buffer){
  17949. /*
  17950. Copyright (c) 2008, Adobe Systems Incorporated
  17951. All rights reserved.
  17952. Redistribution and use in source and binary forms, with or without
  17953. modification, are permitted provided that the following conditions are
  17954. met:
  17955. * Redistributions of source code must retain the above copyright notice,
  17956. this list of conditions and the following disclaimer.
  17957. * Redistributions in binary form must reproduce the above copyright
  17958. notice, this list of conditions and the following disclaimer in the
  17959. documentation and/or other materials provided with the distribution.
  17960. * Neither the name of Adobe Systems Incorporated nor the names of its
  17961. contributors may be used to endorse or promote products derived from
  17962. this software without specific prior written permission.
  17963. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  17964. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  17965. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17966. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  17967. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  17968. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  17969. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17970. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  17971. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  17972. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  17973. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  17974. */
  17975. /*
  17976. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  17977. Basic GUI blocking jpeg encoder
  17978. */
  17979. var btoa = btoa || function(buf) {
  17980. return new Buffer(buf).toString('base64');
  17981. };
  17982. function JPEGEncoder(quality) {
  17983. var self = this;
  17984. var fround = Math.round;
  17985. var ffloor = Math.floor;
  17986. var YTable = new Array(64);
  17987. var UVTable = new Array(64);
  17988. var fdtbl_Y = new Array(64);
  17989. var fdtbl_UV = new Array(64);
  17990. var YDC_HT;
  17991. var UVDC_HT;
  17992. var YAC_HT;
  17993. var UVAC_HT;
  17994. var bitcode = new Array(65535);
  17995. var category = new Array(65535);
  17996. var outputfDCTQuant = new Array(64);
  17997. var DU = new Array(64);
  17998. var byteout = [];
  17999. var bytenew = 0;
  18000. var bytepos = 7;
  18001. var YDU = new Array(64);
  18002. var UDU = new Array(64);
  18003. var VDU = new Array(64);
  18004. var clt = new Array(256);
  18005. var RGB_YUV_TABLE = new Array(2048);
  18006. var currentQuality;
  18007. var ZigZag = [
  18008. 0, 1, 5, 6,14,15,27,28,
  18009. 2, 4, 7,13,16,26,29,42,
  18010. 3, 8,12,17,25,30,41,43,
  18011. 9,11,18,24,31,40,44,53,
  18012. 10,19,23,32,39,45,52,54,
  18013. 20,22,33,38,46,51,55,60,
  18014. 21,34,37,47,50,56,59,61,
  18015. 35,36,48,49,57,58,62,63
  18016. ];
  18017. var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
  18018. var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  18019. var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
  18020. var std_ac_luminance_values = [
  18021. 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
  18022. 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
  18023. 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
  18024. 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
  18025. 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
  18026. 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
  18027. 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
  18028. 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
  18029. 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
  18030. 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
  18031. 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
  18032. 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
  18033. 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
  18034. 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
  18035. 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
  18036. 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
  18037. 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
  18038. 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
  18039. 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
  18040. 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  18041. 0xf9,0xfa
  18042. ];
  18043. var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
  18044. var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  18045. var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
  18046. var std_ac_chrominance_values = [
  18047. 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
  18048. 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
  18049. 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
  18050. 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
  18051. 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
  18052. 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
  18053. 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
  18054. 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
  18055. 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
  18056. 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
  18057. 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
  18058. 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
  18059. 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
  18060. 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
  18061. 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
  18062. 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
  18063. 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
  18064. 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
  18065. 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
  18066. 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  18067. 0xf9,0xfa
  18068. ];
  18069. function initQuantTables(sf){
  18070. var YQT = [
  18071. 16, 11, 10, 16, 24, 40, 51, 61,
  18072. 12, 12, 14, 19, 26, 58, 60, 55,
  18073. 14, 13, 16, 24, 40, 57, 69, 56,
  18074. 14, 17, 22, 29, 51, 87, 80, 62,
  18075. 18, 22, 37, 56, 68,109,103, 77,
  18076. 24, 35, 55, 64, 81,104,113, 92,
  18077. 49, 64, 78, 87,103,121,120,101,
  18078. 72, 92, 95, 98,112,100,103, 99
  18079. ];
  18080. for (var i = 0; i < 64; i++) {
  18081. var t = ffloor((YQT[i]*sf+50)/100);
  18082. if (t < 1) {
  18083. t = 1;
  18084. } else if (t > 255) {
  18085. t = 255;
  18086. }
  18087. YTable[ZigZag[i]] = t;
  18088. }
  18089. var UVQT = [
  18090. 17, 18, 24, 47, 99, 99, 99, 99,
  18091. 18, 21, 26, 66, 99, 99, 99, 99,
  18092. 24, 26, 56, 99, 99, 99, 99, 99,
  18093. 47, 66, 99, 99, 99, 99, 99, 99,
  18094. 99, 99, 99, 99, 99, 99, 99, 99,
  18095. 99, 99, 99, 99, 99, 99, 99, 99,
  18096. 99, 99, 99, 99, 99, 99, 99, 99,
  18097. 99, 99, 99, 99, 99, 99, 99, 99
  18098. ];
  18099. for (var j = 0; j < 64; j++) {
  18100. var u = ffloor((UVQT[j]*sf+50)/100);
  18101. if (u < 1) {
  18102. u = 1;
  18103. } else if (u > 255) {
  18104. u = 255;
  18105. }
  18106. UVTable[ZigZag[j]] = u;
  18107. }
  18108. var aasf = [
  18109. 1.0, 1.387039845, 1.306562965, 1.175875602,
  18110. 1.0, 0.785694958, 0.541196100, 0.275899379
  18111. ];
  18112. var k = 0;
  18113. for (var row = 0; row < 8; row++)
  18114. {
  18115. for (var col = 0; col < 8; col++)
  18116. {
  18117. fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  18118. fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  18119. k++;
  18120. }
  18121. }
  18122. }
  18123. function computeHuffmanTbl(nrcodes, std_table){
  18124. var codevalue = 0;
  18125. var pos_in_table = 0;
  18126. var HT = new Array();
  18127. for (var k = 1; k <= 16; k++) {
  18128. for (var j = 1; j <= nrcodes[k]; j++) {
  18129. HT[std_table[pos_in_table]] = [];
  18130. HT[std_table[pos_in_table]][0] = codevalue;
  18131. HT[std_table[pos_in_table]][1] = k;
  18132. pos_in_table++;
  18133. codevalue++;
  18134. }
  18135. codevalue*=2;
  18136. }
  18137. return HT;
  18138. }
  18139. function initHuffmanTbl()
  18140. {
  18141. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
  18142. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
  18143. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
  18144. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
  18145. }
  18146. function initCategoryNumber()
  18147. {
  18148. var nrlower = 1;
  18149. var nrupper = 2;
  18150. for (var cat = 1; cat <= 15; cat++) {
  18151. //Positive numbers
  18152. for (var nr = nrlower; nr<nrupper; nr++) {
  18153. category[32767+nr] = cat;
  18154. bitcode[32767+nr] = [];
  18155. bitcode[32767+nr][1] = cat;
  18156. bitcode[32767+nr][0] = nr;
  18157. }
  18158. //Negative numbers
  18159. for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
  18160. category[32767+nrneg] = cat;
  18161. bitcode[32767+nrneg] = [];
  18162. bitcode[32767+nrneg][1] = cat;
  18163. bitcode[32767+nrneg][0] = nrupper-1+nrneg;
  18164. }
  18165. nrlower <<= 1;
  18166. nrupper <<= 1;
  18167. }
  18168. }
  18169. function initRGBYUVTable() {
  18170. for(var i = 0; i < 256;i++) {
  18171. RGB_YUV_TABLE[i] = 19595 * i;
  18172. RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
  18173. RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
  18174. RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
  18175. RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
  18176. RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
  18177. RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
  18178. RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
  18179. }
  18180. }
  18181. // IO functions
  18182. function writeBits(bs)
  18183. {
  18184. var value = bs[0];
  18185. var posval = bs[1]-1;
  18186. while ( posval >= 0 ) {
  18187. if (value & (1 << posval) ) {
  18188. bytenew |= (1 << bytepos);
  18189. }
  18190. posval--;
  18191. bytepos--;
  18192. if (bytepos < 0) {
  18193. if (bytenew == 0xFF) {
  18194. writeByte(0xFF);
  18195. writeByte(0);
  18196. }
  18197. else {
  18198. writeByte(bytenew);
  18199. }
  18200. bytepos=7;
  18201. bytenew=0;
  18202. }
  18203. }
  18204. }
  18205. function writeByte(value)
  18206. {
  18207. //byteout.push(clt[value]); // write char directly instead of converting later
  18208. byteout.push(value);
  18209. }
  18210. function writeWord(value)
  18211. {
  18212. writeByte((value>>8)&0xFF);
  18213. writeByte((value )&0xFF);
  18214. }
  18215. // DCT & quantization core
  18216. function fDCTQuant(data, fdtbl)
  18217. {
  18218. var d0, d1, d2, d3, d4, d5, d6, d7;
  18219. /* Pass 1: process rows. */
  18220. var dataOff=0;
  18221. var i;
  18222. var I8 = 8;
  18223. var I64 = 64;
  18224. for (i=0; i<I8; ++i)
  18225. {
  18226. d0 = data[dataOff];
  18227. d1 = data[dataOff+1];
  18228. d2 = data[dataOff+2];
  18229. d3 = data[dataOff+3];
  18230. d4 = data[dataOff+4];
  18231. d5 = data[dataOff+5];
  18232. d6 = data[dataOff+6];
  18233. d7 = data[dataOff+7];
  18234. var tmp0 = d0 + d7;
  18235. var tmp7 = d0 - d7;
  18236. var tmp1 = d1 + d6;
  18237. var tmp6 = d1 - d6;
  18238. var tmp2 = d2 + d5;
  18239. var tmp5 = d2 - d5;
  18240. var tmp3 = d3 + d4;
  18241. var tmp4 = d3 - d4;
  18242. /* Even part */
  18243. var tmp10 = tmp0 + tmp3; /* phase 2 */
  18244. var tmp13 = tmp0 - tmp3;
  18245. var tmp11 = tmp1 + tmp2;
  18246. var tmp12 = tmp1 - tmp2;
  18247. data[dataOff] = tmp10 + tmp11; /* phase 3 */
  18248. data[dataOff+4] = tmp10 - tmp11;
  18249. var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
  18250. data[dataOff+2] = tmp13 + z1; /* phase 5 */
  18251. data[dataOff+6] = tmp13 - z1;
  18252. /* Odd part */
  18253. tmp10 = tmp4 + tmp5; /* phase 2 */
  18254. tmp11 = tmp5 + tmp6;
  18255. tmp12 = tmp6 + tmp7;
  18256. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  18257. var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
  18258. var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
  18259. var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
  18260. var z3 = tmp11 * 0.707106781; /* c4 */
  18261. var z11 = tmp7 + z3; /* phase 5 */
  18262. var z13 = tmp7 - z3;
  18263. data[dataOff+5] = z13 + z2; /* phase 6 */
  18264. data[dataOff+3] = z13 - z2;
  18265. data[dataOff+1] = z11 + z4;
  18266. data[dataOff+7] = z11 - z4;
  18267. dataOff += 8; /* advance pointer to next row */
  18268. }
  18269. /* Pass 2: process columns. */
  18270. dataOff = 0;
  18271. for (i=0; i<I8; ++i)
  18272. {
  18273. d0 = data[dataOff];
  18274. d1 = data[dataOff + 8];
  18275. d2 = data[dataOff + 16];
  18276. d3 = data[dataOff + 24];
  18277. d4 = data[dataOff + 32];
  18278. d5 = data[dataOff + 40];
  18279. d6 = data[dataOff + 48];
  18280. d7 = data[dataOff + 56];
  18281. var tmp0p2 = d0 + d7;
  18282. var tmp7p2 = d0 - d7;
  18283. var tmp1p2 = d1 + d6;
  18284. var tmp6p2 = d1 - d6;
  18285. var tmp2p2 = d2 + d5;
  18286. var tmp5p2 = d2 - d5;
  18287. var tmp3p2 = d3 + d4;
  18288. var tmp4p2 = d3 - d4;
  18289. /* Even part */
  18290. var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
  18291. var tmp13p2 = tmp0p2 - tmp3p2;
  18292. var tmp11p2 = tmp1p2 + tmp2p2;
  18293. var tmp12p2 = tmp1p2 - tmp2p2;
  18294. data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
  18295. data[dataOff+32] = tmp10p2 - tmp11p2;
  18296. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
  18297. data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
  18298. data[dataOff+48] = tmp13p2 - z1p2;
  18299. /* Odd part */
  18300. tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
  18301. tmp11p2 = tmp5p2 + tmp6p2;
  18302. tmp12p2 = tmp6p2 + tmp7p2;
  18303. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  18304. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
  18305. var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
  18306. var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
  18307. var z3p2 = tmp11p2 * 0.707106781; /* c4 */
  18308. var z11p2 = tmp7p2 + z3p2; /* phase 5 */
  18309. var z13p2 = tmp7p2 - z3p2;
  18310. data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
  18311. data[dataOff+24] = z13p2 - z2p2;
  18312. data[dataOff+ 8] = z11p2 + z4p2;
  18313. data[dataOff+56] = z11p2 - z4p2;
  18314. dataOff++; /* advance pointer to next column */
  18315. }
  18316. // Quantize/descale the coefficients
  18317. var fDCTQuant;
  18318. for (i=0; i<I64; ++i)
  18319. {
  18320. // Apply the quantization and scaling factor & Round to nearest integer
  18321. fDCTQuant = data[i]*fdtbl[i];
  18322. outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
  18323. //outputfDCTQuant[i] = fround(fDCTQuant);
  18324. }
  18325. return outputfDCTQuant;
  18326. }
  18327. function writeAPP0()
  18328. {
  18329. writeWord(0xFFE0); // marker
  18330. writeWord(16); // length
  18331. writeByte(0x4A); // J
  18332. writeByte(0x46); // F
  18333. writeByte(0x49); // I
  18334. writeByte(0x46); // F
  18335. writeByte(0); // = "JFIF",'\0'
  18336. writeByte(1); // versionhi
  18337. writeByte(1); // versionlo
  18338. writeByte(0); // xyunits
  18339. writeWord(1); // xdensity
  18340. writeWord(1); // ydensity
  18341. writeByte(0); // thumbnwidth
  18342. writeByte(0); // thumbnheight
  18343. }
  18344. function writeSOF0(width, height)
  18345. {
  18346. writeWord(0xFFC0); // marker
  18347. writeWord(17); // length, truecolor YUV JPG
  18348. writeByte(8); // precision
  18349. writeWord(height);
  18350. writeWord(width);
  18351. writeByte(3); // nrofcomponents
  18352. writeByte(1); // IdY
  18353. writeByte(0x11); // HVY
  18354. writeByte(0); // QTY
  18355. writeByte(2); // IdU
  18356. writeByte(0x11); // HVU
  18357. writeByte(1); // QTU
  18358. writeByte(3); // IdV
  18359. writeByte(0x11); // HVV
  18360. writeByte(1); // QTV
  18361. }
  18362. function writeDQT()
  18363. {
  18364. writeWord(0xFFDB); // marker
  18365. writeWord(132); // length
  18366. writeByte(0);
  18367. for (var i=0; i<64; i++) {
  18368. writeByte(YTable[i]);
  18369. }
  18370. writeByte(1);
  18371. for (var j=0; j<64; j++) {
  18372. writeByte(UVTable[j]);
  18373. }
  18374. }
  18375. function writeDHT()
  18376. {
  18377. writeWord(0xFFC4); // marker
  18378. writeWord(0x01A2); // length
  18379. writeByte(0); // HTYDCinfo
  18380. for (var i=0; i<16; i++) {
  18381. writeByte(std_dc_luminance_nrcodes[i+1]);
  18382. }
  18383. for (var j=0; j<=11; j++) {
  18384. writeByte(std_dc_luminance_values[j]);
  18385. }
  18386. writeByte(0x10); // HTYACinfo
  18387. for (var k=0; k<16; k++) {
  18388. writeByte(std_ac_luminance_nrcodes[k+1]);
  18389. }
  18390. for (var l=0; l<=161; l++) {
  18391. writeByte(std_ac_luminance_values[l]);
  18392. }
  18393. writeByte(1); // HTUDCinfo
  18394. for (var m=0; m<16; m++) {
  18395. writeByte(std_dc_chrominance_nrcodes[m+1]);
  18396. }
  18397. for (var n=0; n<=11; n++) {
  18398. writeByte(std_dc_chrominance_values[n]);
  18399. }
  18400. writeByte(0x11); // HTUACinfo
  18401. for (var o=0; o<16; o++) {
  18402. writeByte(std_ac_chrominance_nrcodes[o+1]);
  18403. }
  18404. for (var p=0; p<=161; p++) {
  18405. writeByte(std_ac_chrominance_values[p]);
  18406. }
  18407. }
  18408. function writeSOS()
  18409. {
  18410. writeWord(0xFFDA); // marker
  18411. writeWord(12); // length
  18412. writeByte(3); // nrofcomponents
  18413. writeByte(1); // IdY
  18414. writeByte(0); // HTY
  18415. writeByte(2); // IdU
  18416. writeByte(0x11); // HTU
  18417. writeByte(3); // IdV
  18418. writeByte(0x11); // HTV
  18419. writeByte(0); // Ss
  18420. writeByte(0x3f); // Se
  18421. writeByte(0); // Bf
  18422. }
  18423. function processDU(CDU, fdtbl, DC, HTDC, HTAC){
  18424. var EOB = HTAC[0x00];
  18425. var M16zeroes = HTAC[0xF0];
  18426. var pos;
  18427. var I16 = 16;
  18428. var I63 = 63;
  18429. var I64 = 64;
  18430. var DU_DCT = fDCTQuant(CDU, fdtbl);
  18431. //ZigZag reorder
  18432. for (var j=0;j<I64;++j) {
  18433. DU[ZigZag[j]]=DU_DCT[j];
  18434. }
  18435. var Diff = DU[0] - DC; DC = DU[0];
  18436. //Encode DC
  18437. if (Diff==0) {
  18438. writeBits(HTDC[0]); // Diff might be 0
  18439. } else {
  18440. pos = 32767+Diff;
  18441. writeBits(HTDC[category[pos]]);
  18442. writeBits(bitcode[pos]);
  18443. }
  18444. //Encode ACs
  18445. var end0pos = 63; // was const... which is crazy
  18446. for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {};
  18447. //end0pos = first element in reverse order !=0
  18448. if ( end0pos == 0) {
  18449. writeBits(EOB);
  18450. return DC;
  18451. }
  18452. var i = 1;
  18453. var lng;
  18454. while ( i <= end0pos ) {
  18455. var startpos = i;
  18456. for (; (DU[i]==0) && (i<=end0pos); ++i) {}
  18457. var nrzeroes = i-startpos;
  18458. if ( nrzeroes >= I16 ) {
  18459. lng = nrzeroes>>4;
  18460. for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
  18461. writeBits(M16zeroes);
  18462. nrzeroes = nrzeroes&0xF;
  18463. }
  18464. pos = 32767+DU[i];
  18465. writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
  18466. writeBits(bitcode[pos]);
  18467. i++;
  18468. }
  18469. if ( end0pos != I63 ) {
  18470. writeBits(EOB);
  18471. }
  18472. return DC;
  18473. }
  18474. function initCharLookupTable(){
  18475. var sfcc = String.fromCharCode;
  18476. for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
  18477. clt[i] = sfcc(i);
  18478. }
  18479. }
  18480. this.encode = function(image,quality) // image data object
  18481. {
  18482. var time_start = new Date().getTime();
  18483. if(quality) setQuality(quality);
  18484. // Initialize bit writer
  18485. byteout = new Array();
  18486. bytenew=0;
  18487. bytepos=7;
  18488. // Add JPEG headers
  18489. writeWord(0xFFD8); // SOI
  18490. writeAPP0();
  18491. writeDQT();
  18492. writeSOF0(image.width,image.height);
  18493. writeDHT();
  18494. writeSOS();
  18495. // Encode 8x8 macroblocks
  18496. var DCY=0;
  18497. var DCU=0;
  18498. var DCV=0;
  18499. bytenew=0;
  18500. bytepos=7;
  18501. this.encode.displayName = "_encode_";
  18502. var imageData = image.data;
  18503. var width = image.width;
  18504. var height = image.height;
  18505. var quadWidth = width*4;
  18506. var tripleWidth = width*3;
  18507. var x, y = 0;
  18508. var r, g, b;
  18509. var start,p, col,row,pos;
  18510. while(y < height){
  18511. x = 0;
  18512. while(x < quadWidth){
  18513. start = quadWidth * y + x;
  18514. p = start;
  18515. col = -1;
  18516. row = 0;
  18517. for(pos=0; pos < 64; pos++){
  18518. row = pos >> 3;// /8
  18519. col = ( pos & 7 ) * 4; // %8
  18520. p = start + ( row * quadWidth ) + col;
  18521. if(y+row >= height){ // padding bottom
  18522. p-= (quadWidth*(y+1+row-height));
  18523. }
  18524. if(x+col >= quadWidth){ // padding right
  18525. p-= ((x+col) - quadWidth +4)
  18526. }
  18527. r = imageData[ p++ ];
  18528. g = imageData[ p++ ];
  18529. b = imageData[ p++ ];
  18530. /* // calculate YUV values dynamically
  18531. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  18532. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  18533. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  18534. */
  18535. // use lookup table (slightly faster)
  18536. YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
  18537. UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
  18538. VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
  18539. }
  18540. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  18541. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  18542. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  18543. x+=32;
  18544. }
  18545. y+=8;
  18546. }
  18547. ////////////////////////////////////////////////////////////////
  18548. // Do the bit alignment of the EOI marker
  18549. if ( bytepos >= 0 ) {
  18550. var fillbits = [];
  18551. fillbits[1] = bytepos+1;
  18552. fillbits[0] = (1<<(bytepos+1))-1;
  18553. writeBits(fillbits);
  18554. }
  18555. writeWord(0xFFD9); //EOI
  18556. //return new Uint8Array(byteout);
  18557. return new Buffer(byteout);
  18558. var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
  18559. byteout = [];
  18560. // benchmarking
  18561. var duration = new Date().getTime() - time_start;
  18562. //console.log('Encoding time: '+ duration + 'ms');
  18563. //
  18564. return jpegDataUri
  18565. }
  18566. function setQuality(quality){
  18567. if (quality <= 0) {
  18568. quality = 1;
  18569. }
  18570. if (quality > 100) {
  18571. quality = 100;
  18572. }
  18573. if(currentQuality == quality) return // don't recalc if unchanged
  18574. var sf = 0;
  18575. if (quality < 50) {
  18576. sf = Math.floor(5000 / quality);
  18577. } else {
  18578. sf = Math.floor(200 - quality*2);
  18579. }
  18580. initQuantTables(sf);
  18581. currentQuality = quality;
  18582. //console.log('Quality set to: '+quality +'%');
  18583. }
  18584. function init(){
  18585. var time_start = new Date().getTime();
  18586. if(!quality) quality = 50;
  18587. // Create tables
  18588. initCharLookupTable()
  18589. initHuffmanTbl();
  18590. initCategoryNumber();
  18591. initRGBYUVTable();
  18592. setQuality(quality);
  18593. var duration = new Date().getTime() - time_start;
  18594. //console.log('Initialization '+ duration + 'ms');
  18595. }
  18596. init();
  18597. };
  18598. module.exports = encode;
  18599. function encode(imgData, qu) {
  18600. if (typeof qu === 'undefined') qu = 50;
  18601. var encoder = new JPEGEncoder(qu);
  18602. var data = encoder.encode(imgData, qu);
  18603. return {
  18604. data: data,
  18605. width: imgData.width,
  18606. height: imgData.height
  18607. };
  18608. }
  18609. // helper function to get the imageData of an existing image on the current page.
  18610. function getImageDataFromImage(idOrElement){
  18611. var theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;
  18612. var cvs = document.createElement('canvas');
  18613. cvs.width = theImg.width;
  18614. cvs.height = theImg.height;
  18615. var ctx = cvs.getContext("2d");
  18616. ctx.drawImage(theImg,0,0);
  18617. return (ctx.getImageData(0, 0, cvs.width, cvs.height));
  18618. }
  18619. }).call(this,require("buffer").Buffer)
  18620. },{"buffer":47}],262:[function(require,module,exports){
  18621. (function (process){
  18622. var path = require('path');
  18623. var fs = require('fs');
  18624. var _0777 = parseInt('0777', 8);
  18625. module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
  18626. function mkdirP (p, opts, f, made) {
  18627. if (typeof opts === 'function') {
  18628. f = opts;
  18629. opts = {};
  18630. }
  18631. else if (!opts || typeof opts !== 'object') {
  18632. opts = { mode: opts };
  18633. }
  18634. var mode = opts.mode;
  18635. var xfs = opts.fs || fs;
  18636. if (mode === undefined) {
  18637. mode = _0777 & (~process.umask());
  18638. }
  18639. if (!made) made = null;
  18640. var cb = f || function () {};
  18641. p = path.resolve(p);
  18642. xfs.mkdir(p, mode, function (er) {
  18643. if (!er) {
  18644. made = made || p;
  18645. return cb(null, made);
  18646. }
  18647. switch (er.code) {
  18648. case 'ENOENT':
  18649. mkdirP(path.dirname(p), opts, function (er, made) {
  18650. if (er) cb(er, made);
  18651. else mkdirP(p, opts, cb, made);
  18652. });
  18653. break;
  18654. // In the case of any other error, just see if there's a dir
  18655. // there already. If so, then hooray! If not, then something
  18656. // is borked.
  18657. default:
  18658. xfs.stat(p, function (er2, stat) {
  18659. // if the stat fails, then that's super weird.
  18660. // let the original error be the failure reason.
  18661. if (er2 || !stat.isDirectory()) cb(er, made)
  18662. else cb(null, made);
  18663. });
  18664. break;
  18665. }
  18666. });
  18667. }
  18668. mkdirP.sync = function sync (p, opts, made) {
  18669. if (!opts || typeof opts !== 'object') {
  18670. opts = { mode: opts };
  18671. }
  18672. var mode = opts.mode;
  18673. var xfs = opts.fs || fs;
  18674. if (mode === undefined) {
  18675. mode = _0777 & (~process.umask());
  18676. }
  18677. if (!made) made = null;
  18678. p = path.resolve(p);
  18679. try {
  18680. xfs.mkdirSync(p, mode);
  18681. made = made || p;
  18682. }
  18683. catch (err0) {
  18684. switch (err0.code) {
  18685. case 'ENOENT' :
  18686. made = sync(path.dirname(p), opts, made);
  18687. sync(p, opts, made);
  18688. break;
  18689. // In the case of any other error, just see if there's a dir
  18690. // there already. If so, then hooray! If not, then something
  18691. // is borked.
  18692. default:
  18693. var stat;
  18694. try {
  18695. stat = xfs.statSync(p);
  18696. }
  18697. catch (err1) {
  18698. throw err0;
  18699. }
  18700. if (!stat.isDirectory()) throw err0;
  18701. break;
  18702. }
  18703. }
  18704. return made;
  18705. };
  18706. }).call(this,require('_process'))
  18707. },{"_process":312,"fs":46,"path":286}],263:[function(require,module,exports){
  18708. /*
  18709. object-assign
  18710. (c) Sindre Sorhus
  18711. @license MIT
  18712. */
  18713. 'use strict';
  18714. /* eslint-disable no-unused-vars */
  18715. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  18716. var hasOwnProperty = Object.prototype.hasOwnProperty;
  18717. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  18718. function toObject(val) {
  18719. if (val === null || val === undefined) {
  18720. throw new TypeError('Object.assign cannot be called with null or undefined');
  18721. }
  18722. return Object(val);
  18723. }
  18724. function shouldUseNative() {
  18725. try {
  18726. if (!Object.assign) {
  18727. return false;
  18728. }
  18729. // Detect buggy property enumeration order in older V8 versions.
  18730. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  18731. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  18732. test1[5] = 'de';
  18733. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  18734. return false;
  18735. }
  18736. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  18737. var test2 = {};
  18738. for (var i = 0; i < 10; i++) {
  18739. test2['_' + String.fromCharCode(i)] = i;
  18740. }
  18741. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  18742. return test2[n];
  18743. });
  18744. if (order2.join('') !== '0123456789') {
  18745. return false;
  18746. }
  18747. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  18748. var test3 = {};
  18749. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  18750. test3[letter] = letter;
  18751. });
  18752. if (Object.keys(Object.assign({}, test3)).join('') !==
  18753. 'abcdefghijklmnopqrst') {
  18754. return false;
  18755. }
  18756. return true;
  18757. } catch (err) {
  18758. // We don't expect any of the above to throw, but better to be safe.
  18759. return false;
  18760. }
  18761. }
  18762. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  18763. var from;
  18764. var to = toObject(target);
  18765. var symbols;
  18766. for (var s = 1; s < arguments.length; s++) {
  18767. from = Object(arguments[s]);
  18768. for (var key in from) {
  18769. if (hasOwnProperty.call(from, key)) {
  18770. to[key] = from[key];
  18771. }
  18772. }
  18773. if (getOwnPropertySymbols) {
  18774. symbols = getOwnPropertySymbols(from);
  18775. for (var i = 0; i < symbols.length; i++) {
  18776. if (propIsEnumerable.call(from, symbols[i])) {
  18777. to[symbols[i]] = from[symbols[i]];
  18778. }
  18779. }
  18780. }
  18781. }
  18782. return to;
  18783. };
  18784. },{}],264:[function(require,module,exports){
  18785. // (c) Dean McNamee <dean@gmail.com>, 2013.
  18786. //
  18787. // https://github.com/deanm/omggif
  18788. //
  18789. // Permission is hereby granted, free of charge, to any person obtaining a copy
  18790. // of this software and associated documentation files (the "Software"), to
  18791. // deal in the Software without restriction, including without limitation the
  18792. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  18793. // sell copies of the Software, and to permit persons to whom the Software is
  18794. // furnished to do so, subject to the following conditions:
  18795. //
  18796. // The above copyright notice and this permission notice shall be included in
  18797. // all copies or substantial portions of the Software.
  18798. //
  18799. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18800. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18801. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18802. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18803. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18804. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  18805. // IN THE SOFTWARE.
  18806. //
  18807. // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
  18808. // including animation and compression. It does not rely on any specific
  18809. // underlying system, so should run in the browser, Node, or Plask.
  18810. "use strict";
  18811. function GifWriter(buf, width, height, gopts) {
  18812. var p = 0;
  18813. var gopts = gopts === undefined ? { } : gopts;
  18814. var loop_count = gopts.loop === undefined ? null : gopts.loop;
  18815. var global_palette = gopts.palette === undefined ? null : gopts.palette;
  18816. if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
  18817. throw new Error("Width/Height invalid.");
  18818. function check_palette_and_num_colors(palette) {
  18819. var num_colors = palette.length;
  18820. if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) {
  18821. throw new Error(
  18822. "Invalid code/color length, must be power of 2 and 2 .. 256.");
  18823. }
  18824. return num_colors;
  18825. }
  18826. // - Header.
  18827. buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF
  18828. buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a
  18829. // Handling of Global Color Table (palette) and background index.
  18830. var gp_num_colors_pow2 = 0;
  18831. var background = 0;
  18832. if (global_palette !== null) {
  18833. var gp_num_colors = check_palette_and_num_colors(global_palette);
  18834. while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
  18835. gp_num_colors = 1 << gp_num_colors_pow2;
  18836. --gp_num_colors_pow2;
  18837. if (gopts.background !== undefined) {
  18838. background = gopts.background;
  18839. if (background >= gp_num_colors)
  18840. throw new Error("Background index out of range.");
  18841. // The GIF spec states that a background index of 0 should be ignored, so
  18842. // this is probably a mistake and you really want to set it to another
  18843. // slot in the palette. But actually in the end most browsers, etc end
  18844. // up ignoring this almost completely (including for dispose background).
  18845. if (background === 0)
  18846. throw new Error("Background index explicitly passed as 0.");
  18847. }
  18848. }
  18849. // - Logical Screen Descriptor.
  18850. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
  18851. buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;
  18852. buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;
  18853. // NOTE: Indicates 0-bpp original color resolution (unused?).
  18854. buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
  18855. gp_num_colors_pow2; // NOTE: No sort flag (unused?).
  18856. buf[p++] = background; // Background Color Index.
  18857. buf[p++] = 0; // Pixel aspect ratio (unused?).
  18858. // - Global Color Table
  18859. if (global_palette !== null) {
  18860. for (var i = 0, il = global_palette.length; i < il; ++i) {
  18861. var rgb = global_palette[i];
  18862. buf[p++] = rgb >> 16 & 0xff;
  18863. buf[p++] = rgb >> 8 & 0xff;
  18864. buf[p++] = rgb & 0xff;
  18865. }
  18866. }
  18867. if (loop_count !== null) { // Netscape block for looping.
  18868. if (loop_count < 0 || loop_count > 65535)
  18869. throw new Error("Loop count invalid.")
  18870. // Extension code, label, and length.
  18871. buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;
  18872. // NETSCAPE2.0
  18873. buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;
  18874. buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;
  18875. buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;
  18876. // Sub-block
  18877. buf[p++] = 0x03; buf[p++] = 0x01;
  18878. buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;
  18879. buf[p++] = 0x00; // Terminator.
  18880. }
  18881. var ended = false;
  18882. this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
  18883. if (ended === true) { --p; ended = false; } // Un-end.
  18884. opts = opts === undefined ? { } : opts;
  18885. // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
  18886. // canvas width/height, I imagine?
  18887. if (x < 0 || y < 0 || x > 65535 || y > 65535)
  18888. throw new Error("x/y invalid.")
  18889. if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
  18890. throw new Error("Width/Height invalid.")
  18891. if (indexed_pixels.length < w * h)
  18892. throw new Error("Not enough pixels for the frame size.");
  18893. var using_local_palette = true;
  18894. var palette = opts.palette;
  18895. if (palette === undefined || palette === null) {
  18896. using_local_palette = false;
  18897. palette = global_palette;
  18898. }
  18899. if (palette === undefined || palette === null)
  18900. throw new Error("Must supply either a local or global palette.");
  18901. var num_colors = check_palette_and_num_colors(palette);
  18902. // Compute the min_code_size (power of 2), destroying num_colors.
  18903. var min_code_size = 0;
  18904. while (num_colors >>= 1) ++min_code_size;
  18905. num_colors = 1 << min_code_size; // Now we can easily get it back.
  18906. var delay = opts.delay === undefined ? 0 : opts.delay;
  18907. // From the spec:
  18908. // 0 - No disposal specified. The decoder is
  18909. // not required to take any action.
  18910. // 1 - Do not dispose. The graphic is to be left
  18911. // in place.
  18912. // 2 - Restore to background color. The area used by the
  18913. // graphic must be restored to the background color.
  18914. // 3 - Restore to previous. The decoder is required to
  18915. // restore the area overwritten by the graphic with
  18916. // what was there prior to rendering the graphic.
  18917. // 4-7 - To be defined.
  18918. // NOTE(deanm): Dispose background doesn't really work, apparently most
  18919. // browsers ignore the background palette index and clear to transparency.
  18920. var disposal = opts.disposal === undefined ? 0 : opts.disposal;
  18921. if (disposal < 0 || disposal > 3) // 4-7 is reserved.
  18922. throw new Error("Disposal out of range.");
  18923. var use_transparency = false;
  18924. var transparent_index = 0;
  18925. if (opts.transparent !== undefined && opts.transparent !== null) {
  18926. use_transparency = true;
  18927. transparent_index = opts.transparent;
  18928. if (transparent_index < 0 || transparent_index >= num_colors)
  18929. throw new Error("Transparent color index.");
  18930. }
  18931. if (disposal !== 0 || use_transparency || delay !== 0) {
  18932. // - Graphics Control Extension
  18933. buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.
  18934. buf[p++] = 4; // Byte size.
  18935. buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
  18936. buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;
  18937. buf[p++] = transparent_index; // Transparent color index.
  18938. buf[p++] = 0; // Block Terminator.
  18939. }
  18940. // - Image Descriptor
  18941. buf[p++] = 0x2c; // Image Seperator.
  18942. buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.
  18943. buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.
  18944. buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;
  18945. buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;
  18946. // NOTE: No sort flag (unused?).
  18947. // TODO(deanm): Support interlace.
  18948. buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;
  18949. // - Local Color Table
  18950. if (using_local_palette === true) {
  18951. for (var i = 0, il = palette.length; i < il; ++i) {
  18952. var rgb = palette[i];
  18953. buf[p++] = rgb >> 16 & 0xff;
  18954. buf[p++] = rgb >> 8 & 0xff;
  18955. buf[p++] = rgb & 0xff;
  18956. }
  18957. }
  18958. p = GifWriterOutputLZWCodeStream(
  18959. buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
  18960. return p;
  18961. };
  18962. this.end = function() {
  18963. if (ended === false) {
  18964. buf[p++] = 0x3b; // Trailer.
  18965. ended = true;
  18966. }
  18967. return p;
  18968. };
  18969. this.getOutputBuffer = function() { return buf; };
  18970. this.setOutputBuffer = function(v) { buf = v; };
  18971. this.getOutputBufferPosition = function() { return p; };
  18972. this.setOutputBufferPosition = function(v) { p = v; };
  18973. }
  18974. // Main compression routine, palette indexes -> LZW code stream.
  18975. // |index_stream| must have at least one entry.
  18976. function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
  18977. buf[p++] = min_code_size;
  18978. var cur_subblock = p++; // Pointing at the length field.
  18979. var clear_code = 1 << min_code_size;
  18980. var code_mask = clear_code - 1;
  18981. var eoi_code = clear_code + 1;
  18982. var next_code = eoi_code + 1;
  18983. var cur_code_size = min_code_size + 1; // Number of bits per code.
  18984. var cur_shift = 0;
  18985. // We have at most 12-bit codes, so we should have to hold a max of 19
  18986. // bits here (and then we would write out).
  18987. var cur = 0;
  18988. function emit_bytes_to_buffer(bit_block_size) {
  18989. while (cur_shift >= bit_block_size) {
  18990. buf[p++] = cur & 0xff;
  18991. cur >>= 8; cur_shift -= 8;
  18992. if (p === cur_subblock + 256) { // Finished a subblock.
  18993. buf[cur_subblock] = 255;
  18994. cur_subblock = p++;
  18995. }
  18996. }
  18997. }
  18998. function emit_code(c) {
  18999. cur |= c << cur_shift;
  19000. cur_shift += cur_code_size;
  19001. emit_bytes_to_buffer(8);
  19002. }
  19003. // I am not an expert on the topic, and I don't want to write a thesis.
  19004. // However, it is good to outline here the basic algorithm and the few data
  19005. // structures and optimizations here that make this implementation fast.
  19006. // The basic idea behind LZW is to build a table of previously seen runs
  19007. // addressed by a short id (herein called output code). All data is
  19008. // referenced by a code, which represents one or more values from the
  19009. // original input stream. All input bytes can be referenced as the same
  19010. // value as an output code. So if you didn't want any compression, you
  19011. // could more or less just output the original bytes as codes (there are
  19012. // some details to this, but it is the idea). In order to achieve
  19013. // compression, values greater then the input range (codes can be up to
  19014. // 12-bit while input only 8-bit) represent a sequence of previously seen
  19015. // inputs. The decompressor is able to build the same mapping while
  19016. // decoding, so there is always a shared common knowledge between the
  19017. // encoding and decoder, which is also important for "timing" aspects like
  19018. // how to handle variable bit width code encoding.
  19019. //
  19020. // One obvious but very important consequence of the table system is there
  19021. // is always a unique id (at most 12-bits) to map the runs. 'A' might be
  19022. // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
  19023. // can be used for an effecient lookup strategy for the code mapping. We
  19024. // need to know if a run has been seen before, and be able to map that run
  19025. // to the output code. Since we start with known unique ids (input bytes),
  19026. // and then from those build more unique ids (table entries), we can
  19027. // continue this chain (almost like a linked list) to always have small
  19028. // integer values that represent the current byte chains in the encoder.
  19029. // This means instead of tracking the input bytes (AAAABCD) to know our
  19030. // current state, we can track the table entry for AAAABC (it is guaranteed
  19031. // to exist by the nature of the algorithm) and the next character D.
  19032. // Therefor the tuple of (table_entry, byte) is guaranteed to also be
  19033. // unique. This allows us to create a simple lookup key for mapping input
  19034. // sequences to codes (table indices) without having to store or search
  19035. // any of the code sequences. So if 'AAAA' has a table entry of 12, the
  19036. // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
  19037. // key. This leads to a integer value at most 20-bits, which can always
  19038. // fit in an SMI value and be used as a fast sparse array / object key.
  19039. // Output code for the current contents of the index buffer.
  19040. var ib_code = index_stream[0] & code_mask; // Load first input index.
  19041. var code_table = { }; // Key'd on our 20-bit "tuple".
  19042. emit_code(clear_code); // Spec says first code should be a clear code.
  19043. // First index already loaded, process the rest of the stream.
  19044. for (var i = 1, il = index_stream.length; i < il; ++i) {
  19045. var k = index_stream[i] & code_mask;
  19046. var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.
  19047. var cur_code = code_table[cur_key]; // buffer + k.
  19048. // Check if we have to create a new code table entry.
  19049. if (cur_code === undefined) { // We don't have buffer + k.
  19050. // Emit index buffer (without k).
  19051. // This is an inline version of emit_code, because this is the core
  19052. // writing routine of the compressor (and V8 cannot inline emit_code
  19053. // because it is a closure here in a different context). Additionally
  19054. // we can call emit_byte_to_buffer less often, because we can have
  19055. // 30-bits (from our 31-bit signed SMI), and we know our codes will only
  19056. // be 12-bits, so can safely have 18-bits there without overflow.
  19057. // emit_code(ib_code);
  19058. cur |= ib_code << cur_shift;
  19059. cur_shift += cur_code_size;
  19060. while (cur_shift >= 8) {
  19061. buf[p++] = cur & 0xff;
  19062. cur >>= 8; cur_shift -= 8;
  19063. if (p === cur_subblock + 256) { // Finished a subblock.
  19064. buf[cur_subblock] = 255;
  19065. cur_subblock = p++;
  19066. }
  19067. }
  19068. if (next_code === 4096) { // Table full, need a clear.
  19069. emit_code(clear_code);
  19070. next_code = eoi_code + 1;
  19071. cur_code_size = min_code_size + 1;
  19072. code_table = { };
  19073. } else { // Table not full, insert a new entry.
  19074. // Increase our variable bit code sizes if necessary. This is a bit
  19075. // tricky as it is based on "timing" between the encoding and
  19076. // decoder. From the encoders perspective this should happen after
  19077. // we've already emitted the index buffer and are about to create the
  19078. // first table entry that would overflow our current code bit size.
  19079. if (next_code >= (1 << cur_code_size)) ++cur_code_size;
  19080. code_table[cur_key] = next_code++; // Insert into code table.
  19081. }
  19082. ib_code = k; // Index buffer to single input k.
  19083. } else {
  19084. ib_code = cur_code; // Index buffer to sequence in code table.
  19085. }
  19086. }
  19087. emit_code(ib_code); // There will still be something in the index buffer.
  19088. emit_code(eoi_code); // End Of Information.
  19089. // Flush / finalize the sub-blocks stream to the buffer.
  19090. emit_bytes_to_buffer(1);
  19091. // Finish the sub-blocks, writing out any unfinished lengths and
  19092. // terminating with a sub-block of length 0. If we have already started
  19093. // but not yet used a sub-block it can just become the terminator.
  19094. if (cur_subblock + 1 === p) { // Started but unused.
  19095. buf[cur_subblock] = 0;
  19096. } else { // Started and used, write length and additional terminator block.
  19097. buf[cur_subblock] = p - cur_subblock - 1;
  19098. buf[p++] = 0;
  19099. }
  19100. return p;
  19101. }
  19102. function GifReader(buf) {
  19103. var p = 0;
  19104. // - Header (GIF87a or GIF89a).
  19105. if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||
  19106. buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {
  19107. throw new Error("Invalid GIF 87a/89a header.");
  19108. }
  19109. // - Logical Screen Descriptor.
  19110. var width = buf[p++] | buf[p++] << 8;
  19111. var height = buf[p++] | buf[p++] << 8;
  19112. var pf0 = buf[p++]; // <Packed Fields>.
  19113. var global_palette_flag = pf0 >> 7;
  19114. var num_global_colors_pow2 = pf0 & 0x7;
  19115. var num_global_colors = 1 << (num_global_colors_pow2 + 1);
  19116. var background = buf[p++];
  19117. buf[p++]; // Pixel aspect ratio (unused?).
  19118. var global_palette_offset = null;
  19119. var global_palette_size = null;
  19120. if (global_palette_flag) {
  19121. global_palette_offset = p;
  19122. global_palette_size = num_global_colors;
  19123. p += num_global_colors * 3; // Seek past palette.
  19124. }
  19125. var no_eof = true;
  19126. var frames = [ ];
  19127. var delay = 0;
  19128. var transparent_index = null;
  19129. var disposal = 0; // 0 - No disposal specified.
  19130. var loop_count = null;
  19131. this.width = width;
  19132. this.height = height;
  19133. while (no_eof && p < buf.length) {
  19134. switch (buf[p++]) {
  19135. case 0x21: // Graphics Control Extension Block
  19136. switch (buf[p++]) {
  19137. case 0xff: // Application specific block
  19138. // Try if it's a Netscape block (with animation loop counter).
  19139. if (buf[p ] !== 0x0b || // 21 FF already read, check block size.
  19140. // NETSCAPE2.0
  19141. buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&
  19142. buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&
  19143. buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&
  19144. buf[p+10] == 0x2e && buf[p+11] == 0x30 &&
  19145. // Sub-block
  19146. buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {
  19147. p += 14;
  19148. loop_count = buf[p++] | buf[p++] << 8;
  19149. p++; // Skip terminator.
  19150. } else { // We don't know what it is, just try to get past it.
  19151. p += 12;
  19152. while (true) { // Seek through subblocks.
  19153. var block_size = buf[p++];
  19154. // Bad block size (ex: undefined from an out of bounds read).
  19155. if (!(block_size >= 0)) throw Error("Invalid block size");
  19156. if (block_size === 0) break; // 0 size is terminator
  19157. p += block_size;
  19158. }
  19159. }
  19160. break;
  19161. case 0xf9: // Graphics Control Extension
  19162. if (buf[p++] !== 0x4 || buf[p+4] !== 0)
  19163. throw new Error("Invalid graphics extension block.");
  19164. var pf1 = buf[p++];
  19165. delay = buf[p++] | buf[p++] << 8;
  19166. transparent_index = buf[p++];
  19167. if ((pf1 & 1) === 0) transparent_index = null;
  19168. disposal = pf1 >> 2 & 0x7;
  19169. p++; // Skip terminator.
  19170. break;
  19171. case 0xfe: // Comment Extension.
  19172. while (true) { // Seek through subblocks.
  19173. var block_size = buf[p++];
  19174. // Bad block size (ex: undefined from an out of bounds read).
  19175. if (!(block_size >= 0)) throw Error("Invalid block size");
  19176. if (block_size === 0) break; // 0 size is terminator
  19177. // console.log(buf.slice(p, p+block_size).toString('ascii'));
  19178. p += block_size;
  19179. }
  19180. break;
  19181. default:
  19182. throw new Error(
  19183. "Unknown graphic control label: 0x" + buf[p-1].toString(16));
  19184. }
  19185. break;
  19186. case 0x2c: // Image Descriptor.
  19187. var x = buf[p++] | buf[p++] << 8;
  19188. var y = buf[p++] | buf[p++] << 8;
  19189. var w = buf[p++] | buf[p++] << 8;
  19190. var h = buf[p++] | buf[p++] << 8;
  19191. var pf2 = buf[p++];
  19192. var local_palette_flag = pf2 >> 7;
  19193. var interlace_flag = pf2 >> 6 & 1;
  19194. var num_local_colors_pow2 = pf2 & 0x7;
  19195. var num_local_colors = 1 << (num_local_colors_pow2 + 1);
  19196. var palette_offset = global_palette_offset;
  19197. var palette_size = global_palette_size;
  19198. var has_local_palette = false;
  19199. if (local_palette_flag) {
  19200. var has_local_palette = true;
  19201. palette_offset = p; // Override with local palette.
  19202. palette_size = num_local_colors;
  19203. p += num_local_colors * 3; // Seek past palette.
  19204. }
  19205. var data_offset = p;
  19206. p++; // codesize
  19207. while (true) {
  19208. var block_size = buf[p++];
  19209. // Bad block size (ex: undefined from an out of bounds read).
  19210. if (!(block_size >= 0)) throw Error("Invalid block size");
  19211. if (block_size === 0) break; // 0 size is terminator
  19212. p += block_size;
  19213. }
  19214. frames.push({x: x, y: y, width: w, height: h,
  19215. has_local_palette: has_local_palette,
  19216. palette_offset: palette_offset,
  19217. palette_size: palette_size,
  19218. data_offset: data_offset,
  19219. data_length: p - data_offset,
  19220. transparent_index: transparent_index,
  19221. interlaced: !!interlace_flag,
  19222. delay: delay,
  19223. disposal: disposal});
  19224. break;
  19225. case 0x3b: // Trailer Marker (end of file).
  19226. no_eof = false;
  19227. break;
  19228. default:
  19229. throw new Error("Unknown gif block: 0x" + buf[p-1].toString(16));
  19230. break;
  19231. }
  19232. }
  19233. this.numFrames = function() {
  19234. return frames.length;
  19235. };
  19236. this.loopCount = function() {
  19237. return loop_count;
  19238. };
  19239. this.frameInfo = function(frame_num) {
  19240. if (frame_num < 0 || frame_num >= frames.length)
  19241. throw new Error("Frame index out of range.");
  19242. return frames[frame_num];
  19243. }
  19244. this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
  19245. var frame = this.frameInfo(frame_num);
  19246. var num_pixels = frame.width * frame.height;
  19247. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  19248. GifReaderLZWOutputIndexStream(
  19249. buf, frame.data_offset, index_stream, num_pixels);
  19250. var palette_offset = frame.palette_offset;
  19251. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  19252. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  19253. // the profile, not sure if it's related to using a Uint8Array.
  19254. var trans = frame.transparent_index;
  19255. if (trans === null) trans = 256;
  19256. // We are possibly just blitting to a portion of the entire frame.
  19257. // That is a subrect within the framerect, so the additional pixels
  19258. // must be skipped over after we finished a scanline.
  19259. var framewidth = frame.width;
  19260. var framestride = width - framewidth;
  19261. var xleft = framewidth; // Number of subrect pixels left in scanline.
  19262. // Output indicies of the top left and bottom right corners of the subrect.
  19263. var opbeg = ((frame.y * width) + frame.x) * 4;
  19264. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  19265. var op = opbeg;
  19266. var scanstride = framestride * 4;
  19267. // Use scanstride to skip past the rows when interlacing. This is skipping
  19268. // 7 rows for the first two passes, then 3 then 1.
  19269. if (frame.interlaced === true) {
  19270. scanstride += width * 4 * 7; // Pass 1.
  19271. }
  19272. var interlaceskip = 8; // Tracking the row interval in the current pass.
  19273. for (var i = 0, il = index_stream.length; i < il; ++i) {
  19274. var index = index_stream[i];
  19275. if (xleft === 0) { // Beginning of new scan line
  19276. op += scanstride;
  19277. xleft = framewidth;
  19278. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  19279. scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
  19280. // interlaceskip / 2 * 4 is interlaceskip << 1.
  19281. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  19282. interlaceskip >>= 1;
  19283. }
  19284. }
  19285. if (index === trans) {
  19286. op += 4;
  19287. } else {
  19288. var r = buf[palette_offset + index * 3];
  19289. var g = buf[palette_offset + index * 3 + 1];
  19290. var b = buf[palette_offset + index * 3 + 2];
  19291. pixels[op++] = b;
  19292. pixels[op++] = g;
  19293. pixels[op++] = r;
  19294. pixels[op++] = 255;
  19295. }
  19296. --xleft;
  19297. }
  19298. };
  19299. // I will go to copy and paste hell one day...
  19300. this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
  19301. var frame = this.frameInfo(frame_num);
  19302. var num_pixels = frame.width * frame.height;
  19303. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  19304. GifReaderLZWOutputIndexStream(
  19305. buf, frame.data_offset, index_stream, num_pixels);
  19306. var palette_offset = frame.palette_offset;
  19307. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  19308. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  19309. // the profile, not sure if it's related to using a Uint8Array.
  19310. var trans = frame.transparent_index;
  19311. if (trans === null) trans = 256;
  19312. // We are possibly just blitting to a portion of the entire frame.
  19313. // That is a subrect within the framerect, so the additional pixels
  19314. // must be skipped over after we finished a scanline.
  19315. var framewidth = frame.width;
  19316. var framestride = width - framewidth;
  19317. var xleft = framewidth; // Number of subrect pixels left in scanline.
  19318. // Output indicies of the top left and bottom right corners of the subrect.
  19319. var opbeg = ((frame.y * width) + frame.x) * 4;
  19320. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  19321. var op = opbeg;
  19322. var scanstride = framestride * 4;
  19323. // Use scanstride to skip past the rows when interlacing. This is skipping
  19324. // 7 rows for the first two passes, then 3 then 1.
  19325. if (frame.interlaced === true) {
  19326. scanstride += width * 4 * 7; // Pass 1.
  19327. }
  19328. var interlaceskip = 8; // Tracking the row interval in the current pass.
  19329. for (var i = 0, il = index_stream.length; i < il; ++i) {
  19330. var index = index_stream[i];
  19331. if (xleft === 0) { // Beginning of new scan line
  19332. op += scanstride;
  19333. xleft = framewidth;
  19334. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  19335. scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
  19336. // interlaceskip / 2 * 4 is interlaceskip << 1.
  19337. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  19338. interlaceskip >>= 1;
  19339. }
  19340. }
  19341. if (index === trans) {
  19342. op += 4;
  19343. } else {
  19344. var r = buf[palette_offset + index * 3];
  19345. var g = buf[palette_offset + index * 3 + 1];
  19346. var b = buf[palette_offset + index * 3 + 2];
  19347. pixels[op++] = r;
  19348. pixels[op++] = g;
  19349. pixels[op++] = b;
  19350. pixels[op++] = 255;
  19351. }
  19352. --xleft;
  19353. }
  19354. };
  19355. }
  19356. function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
  19357. var min_code_size = code_stream[p++];
  19358. var clear_code = 1 << min_code_size;
  19359. var eoi_code = clear_code + 1;
  19360. var next_code = eoi_code + 1;
  19361. var cur_code_size = min_code_size + 1; // Number of bits per code.
  19362. // NOTE: This shares the same name as the encoder, but has a different
  19363. // meaning here. Here this masks each code coming from the code stream.
  19364. var code_mask = (1 << cur_code_size) - 1;
  19365. var cur_shift = 0;
  19366. var cur = 0;
  19367. var op = 0; // Output pointer.
  19368. var subblock_size = code_stream[p++];
  19369. // TODO(deanm): Would using a TypedArray be any faster? At least it would
  19370. // solve the fast mode / backing store uncertainty.
  19371. // var code_table = Array(4096);
  19372. var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
  19373. var prev_code = null; // Track code-1.
  19374. while (true) {
  19375. // Read up to two bytes, making sure we always 12-bits for max sized code.
  19376. while (cur_shift < 16) {
  19377. if (subblock_size === 0) break; // No more data to be read.
  19378. cur |= code_stream[p++] << cur_shift;
  19379. cur_shift += 8;
  19380. if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
  19381. subblock_size = code_stream[p++]; // Next subblock.
  19382. } else {
  19383. --subblock_size;
  19384. }
  19385. }
  19386. // TODO(deanm): We should never really get here, we should have received
  19387. // and EOI.
  19388. if (cur_shift < cur_code_size)
  19389. break;
  19390. var code = cur & code_mask;
  19391. cur >>= cur_code_size;
  19392. cur_shift -= cur_code_size;
  19393. // TODO(deanm): Maybe should check that the first code was a clear code,
  19394. // at least this is what you're supposed to do. But actually our encoder
  19395. // now doesn't emit a clear code first anyway.
  19396. if (code === clear_code) {
  19397. // We don't actually have to clear the table. This could be a good idea
  19398. // for greater error checking, but we don't really do any anyway. We
  19399. // will just track it with next_code and overwrite old entries.
  19400. next_code = eoi_code + 1;
  19401. cur_code_size = min_code_size + 1;
  19402. code_mask = (1 << cur_code_size) - 1;
  19403. // Don't update prev_code ?
  19404. prev_code = null;
  19405. continue;
  19406. } else if (code === eoi_code) {
  19407. break;
  19408. }
  19409. // We have a similar situation as the decoder, where we want to store
  19410. // variable length entries (code table entries), but we want to do in a
  19411. // faster manner than an array of arrays. The code below stores sort of a
  19412. // linked list within the code table, and then "chases" through it to
  19413. // construct the dictionary entries. When a new entry is created, just the
  19414. // last byte is stored, and the rest (prefix) of the entry is only
  19415. // referenced by its table entry. Then the code chases through the
  19416. // prefixes until it reaches a single byte code. We have to chase twice,
  19417. // first to compute the length, and then to actually copy the data to the
  19418. // output (backwards, since we know the length). The alternative would be
  19419. // storing something in an intermediate stack, but that doesn't make any
  19420. // more sense. I implemented an approach where it also stored the length
  19421. // in the code table, although it's a bit tricky because you run out of
  19422. // bits (12 + 12 + 8), but I didn't measure much improvements (the table
  19423. // entries are generally not the long). Even when I created benchmarks for
  19424. // very long table entries the complexity did not seem worth it.
  19425. // The code table stores the prefix entry in 12 bits and then the suffix
  19426. // byte in 8 bits, so each entry is 20 bits.
  19427. var chase_code = code < next_code ? code : prev_code;
  19428. // Chase what we will output, either {CODE} or {CODE-1}.
  19429. var chase_length = 0;
  19430. var chase = chase_code;
  19431. while (chase > clear_code) {
  19432. chase = code_table[chase] >> 8;
  19433. ++chase_length;
  19434. }
  19435. var k = chase;
  19436. var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
  19437. if (op_end > output_length) {
  19438. console.log("Warning, gif stream longer than expected.");
  19439. return;
  19440. }
  19441. // Already have the first byte from the chase, might as well write it fast.
  19442. output[op++] = k;
  19443. op += chase_length;
  19444. var b = op; // Track pointer, writing backwards.
  19445. if (chase_code !== code) // The case of emitting {CODE-1} + k.
  19446. output[op++] = k;
  19447. chase = chase_code;
  19448. while (chase_length--) {
  19449. chase = code_table[chase];
  19450. output[--b] = chase & 0xff; // Write backwards.
  19451. chase >>= 8; // Pull down to the prefix code.
  19452. }
  19453. if (prev_code !== null && next_code < 4096) {
  19454. code_table[next_code++] = prev_code << 8 | k;
  19455. // TODO(deanm): Figure out this clearing vs code growth logic better. I
  19456. // have an feeling that it should just happen somewhere else, for now it
  19457. // is awkward between when we grow past the max and then hit a clear code.
  19458. // For now just check if we hit the max 12-bits (then a clear code should
  19459. // follow, also of course encoded in 12-bits).
  19460. if (next_code >= code_mask+1 && cur_code_size < 12) {
  19461. ++cur_code_size;
  19462. code_mask = code_mask << 1 | 1;
  19463. }
  19464. }
  19465. prev_code = code;
  19466. }
  19467. if (op !== output_length) {
  19468. console.log("Warning, gif stream shorter than expected.");
  19469. }
  19470. return output;
  19471. }
  19472. // CommonJS.
  19473. try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {}
  19474. },{}],265:[function(require,module,exports){
  19475. // Top level file is just a mixin of submodules & constants
  19476. 'use strict';
  19477. var assign = require('./lib/utils/common').assign;
  19478. var deflate = require('./lib/deflate');
  19479. var inflate = require('./lib/inflate');
  19480. var constants = require('./lib/zlib/constants');
  19481. var pako = {};
  19482. assign(pako, deflate, inflate, constants);
  19483. module.exports = pako;
  19484. },{"./lib/deflate":266,"./lib/inflate":267,"./lib/utils/common":268,"./lib/zlib/constants":271}],266:[function(require,module,exports){
  19485. 'use strict';
  19486. var zlib_deflate = require('./zlib/deflate');
  19487. var utils = require('./utils/common');
  19488. var strings = require('./utils/strings');
  19489. var msg = require('./zlib/messages');
  19490. var ZStream = require('./zlib/zstream');
  19491. var toString = Object.prototype.toString;
  19492. /* Public constants ==========================================================*/
  19493. /* ===========================================================================*/
  19494. var Z_NO_FLUSH = 0;
  19495. var Z_FINISH = 4;
  19496. var Z_OK = 0;
  19497. var Z_STREAM_END = 1;
  19498. var Z_SYNC_FLUSH = 2;
  19499. var Z_DEFAULT_COMPRESSION = -1;
  19500. var Z_DEFAULT_STRATEGY = 0;
  19501. var Z_DEFLATED = 8;
  19502. /* ===========================================================================*/
  19503. /**
  19504. * class Deflate
  19505. *
  19506. * Generic JS-style wrapper for zlib calls. If you don't need
  19507. * streaming behaviour - use more simple functions: [[deflate]],
  19508. * [[deflateRaw]] and [[gzip]].
  19509. **/
  19510. /* internal
  19511. * Deflate.chunks -> Array
  19512. *
  19513. * Chunks of output data, if [[Deflate#onData]] not overridden.
  19514. **/
  19515. /**
  19516. * Deflate.result -> Uint8Array|Array
  19517. *
  19518. * Compressed result, generated by default [[Deflate#onData]]
  19519. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19520. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19521. * push a chunk with explicit flush (call [[Deflate#push]] with
  19522. * `Z_SYNC_FLUSH` param).
  19523. **/
  19524. /**
  19525. * Deflate.err -> Number
  19526. *
  19527. * Error code after deflate finished. 0 (Z_OK) on success.
  19528. * You will not need it in real life, because deflate errors
  19529. * are possible only on wrong options or bad `onData` / `onEnd`
  19530. * custom handlers.
  19531. **/
  19532. /**
  19533. * Deflate.msg -> String
  19534. *
  19535. * Error message, if [[Deflate.err]] != 0
  19536. **/
  19537. /**
  19538. * new Deflate(options)
  19539. * - options (Object): zlib deflate options.
  19540. *
  19541. * Creates new deflator instance with specified params. Throws exception
  19542. * on bad params. Supported options:
  19543. *
  19544. * - `level`
  19545. * - `windowBits`
  19546. * - `memLevel`
  19547. * - `strategy`
  19548. * - `dictionary`
  19549. *
  19550. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19551. * for more information on these.
  19552. *
  19553. * Additional options, for internal needs:
  19554. *
  19555. * - `chunkSize` - size of generated data chunks (16K by default)
  19556. * - `raw` (Boolean) - do raw deflate
  19557. * - `gzip` (Boolean) - create gzip wrapper
  19558. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19559. * (each char code [0..255])
  19560. * - `header` (Object) - custom header for gzip
  19561. * - `text` (Boolean) - true if compressed data believed to be text
  19562. * - `time` (Number) - modification time, unix timestamp
  19563. * - `os` (Number) - operation system code
  19564. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19565. * - `name` (String) - file name (binary string)
  19566. * - `comment` (String) - comment (binary string)
  19567. * - `hcrc` (Boolean) - true if header crc should be added
  19568. *
  19569. * ##### Example:
  19570. *
  19571. * ```javascript
  19572. * var pako = require('pako')
  19573. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19574. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19575. *
  19576. * var deflate = new pako.Deflate({ level: 3});
  19577. *
  19578. * deflate.push(chunk1, false);
  19579. * deflate.push(chunk2, true); // true -> last chunk
  19580. *
  19581. * if (deflate.err) { throw new Error(deflate.err); }
  19582. *
  19583. * console.log(deflate.result);
  19584. * ```
  19585. **/
  19586. function Deflate(options) {
  19587. if (!(this instanceof Deflate)) return new Deflate(options);
  19588. this.options = utils.assign({
  19589. level: Z_DEFAULT_COMPRESSION,
  19590. method: Z_DEFLATED,
  19591. chunkSize: 16384,
  19592. windowBits: 15,
  19593. memLevel: 8,
  19594. strategy: Z_DEFAULT_STRATEGY,
  19595. to: ''
  19596. }, options || {});
  19597. var opt = this.options;
  19598. if (opt.raw && (opt.windowBits > 0)) {
  19599. opt.windowBits = -opt.windowBits;
  19600. }
  19601. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19602. opt.windowBits += 16;
  19603. }
  19604. this.err = 0; // error code, if happens (0 = Z_OK)
  19605. this.msg = ''; // error message
  19606. this.ended = false; // used to avoid multiple onEnd() calls
  19607. this.chunks = []; // chunks of compressed data
  19608. this.strm = new ZStream();
  19609. this.strm.avail_out = 0;
  19610. var status = zlib_deflate.deflateInit2(
  19611. this.strm,
  19612. opt.level,
  19613. opt.method,
  19614. opt.windowBits,
  19615. opt.memLevel,
  19616. opt.strategy
  19617. );
  19618. if (status !== Z_OK) {
  19619. throw new Error(msg[status]);
  19620. }
  19621. if (opt.header) {
  19622. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19623. }
  19624. if (opt.dictionary) {
  19625. var dict;
  19626. // Convert data if needed
  19627. if (typeof opt.dictionary === 'string') {
  19628. // If we need to compress text, change encoding to utf8.
  19629. dict = strings.string2buf(opt.dictionary);
  19630. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  19631. dict = new Uint8Array(opt.dictionary);
  19632. } else {
  19633. dict = opt.dictionary;
  19634. }
  19635. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  19636. if (status !== Z_OK) {
  19637. throw new Error(msg[status]);
  19638. }
  19639. this._dict_set = true;
  19640. }
  19641. }
  19642. /**
  19643. * Deflate#push(data[, mode]) -> Boolean
  19644. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19645. * converted to utf8 byte sequence.
  19646. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19647. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  19648. *
  19649. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19650. * new compressed chunks. Returns `true` on success. The last data block must have
  19651. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19652. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19653. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19654. *
  19655. * On fail call [[Deflate#onEnd]] with error code and return false.
  19656. *
  19657. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19658. * array format is detected automatically). Also, don't skip last param and always
  19659. * use the same type in your code (boolean or number). That will improve JS speed.
  19660. *
  19661. * For regular `Array`-s make sure all elements are [0..255].
  19662. *
  19663. * ##### Example
  19664. *
  19665. * ```javascript
  19666. * push(chunk, false); // push one of data chunks
  19667. * ...
  19668. * push(chunk, true); // push last chunk
  19669. * ```
  19670. **/
  19671. Deflate.prototype.push = function (data, mode) {
  19672. var strm = this.strm;
  19673. var chunkSize = this.options.chunkSize;
  19674. var status, _mode;
  19675. if (this.ended) { return false; }
  19676. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19677. // Convert data if needed
  19678. if (typeof data === 'string') {
  19679. // If we need to compress text, change encoding to utf8.
  19680. strm.input = strings.string2buf(data);
  19681. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19682. strm.input = new Uint8Array(data);
  19683. } else {
  19684. strm.input = data;
  19685. }
  19686. strm.next_in = 0;
  19687. strm.avail_in = strm.input.length;
  19688. do {
  19689. if (strm.avail_out === 0) {
  19690. strm.output = new utils.Buf8(chunkSize);
  19691. strm.next_out = 0;
  19692. strm.avail_out = chunkSize;
  19693. }
  19694. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19695. if (status !== Z_STREAM_END && status !== Z_OK) {
  19696. this.onEnd(status);
  19697. this.ended = true;
  19698. return false;
  19699. }
  19700. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19701. if (this.options.to === 'string') {
  19702. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19703. } else {
  19704. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19705. }
  19706. }
  19707. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19708. // Finalize on the last chunk.
  19709. if (_mode === Z_FINISH) {
  19710. status = zlib_deflate.deflateEnd(this.strm);
  19711. this.onEnd(status);
  19712. this.ended = true;
  19713. return status === Z_OK;
  19714. }
  19715. // callback interim results if Z_SYNC_FLUSH.
  19716. if (_mode === Z_SYNC_FLUSH) {
  19717. this.onEnd(Z_OK);
  19718. strm.avail_out = 0;
  19719. return true;
  19720. }
  19721. return true;
  19722. };
  19723. /**
  19724. * Deflate#onData(chunk) -> Void
  19725. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  19726. * on js engine support. When string output requested, each chunk
  19727. * will be string.
  19728. *
  19729. * By default, stores data blocks in `chunks[]` property and glue
  19730. * those in `onEnd`. Override this handler, if you need another behaviour.
  19731. **/
  19732. Deflate.prototype.onData = function (chunk) {
  19733. this.chunks.push(chunk);
  19734. };
  19735. /**
  19736. * Deflate#onEnd(status) -> Void
  19737. * - status (Number): deflate status. 0 (Z_OK) on success,
  19738. * other if not.
  19739. *
  19740. * Called once after you tell deflate that the input stream is
  19741. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19742. * or if an error happened. By default - join collected chunks,
  19743. * free memory and fill `results` / `err` properties.
  19744. **/
  19745. Deflate.prototype.onEnd = function (status) {
  19746. // On success - join
  19747. if (status === Z_OK) {
  19748. if (this.options.to === 'string') {
  19749. this.result = this.chunks.join('');
  19750. } else {
  19751. this.result = utils.flattenChunks(this.chunks);
  19752. }
  19753. }
  19754. this.chunks = [];
  19755. this.err = status;
  19756. this.msg = this.strm.msg;
  19757. };
  19758. /**
  19759. * deflate(data[, options]) -> Uint8Array|Array|String
  19760. * - data (Uint8Array|Array|String): input data to compress.
  19761. * - options (Object): zlib deflate options.
  19762. *
  19763. * Compress `data` with deflate algorithm and `options`.
  19764. *
  19765. * Supported options are:
  19766. *
  19767. * - level
  19768. * - windowBits
  19769. * - memLevel
  19770. * - strategy
  19771. * - dictionary
  19772. *
  19773. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19774. * for more information on these.
  19775. *
  19776. * Sugar (options):
  19777. *
  19778. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19779. * negative windowBits implicitly.
  19780. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19781. * (each char code [0..255])
  19782. *
  19783. * ##### Example:
  19784. *
  19785. * ```javascript
  19786. * var pako = require('pako')
  19787. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19788. *
  19789. * console.log(pako.deflate(data));
  19790. * ```
  19791. **/
  19792. function deflate(input, options) {
  19793. var deflator = new Deflate(options);
  19794. deflator.push(input, true);
  19795. // That will never happens, if you don't cheat with options :)
  19796. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  19797. return deflator.result;
  19798. }
  19799. /**
  19800. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19801. * - data (Uint8Array|Array|String): input data to compress.
  19802. * - options (Object): zlib deflate options.
  19803. *
  19804. * The same as [[deflate]], but creates raw data, without wrapper
  19805. * (header and adler32 crc).
  19806. **/
  19807. function deflateRaw(input, options) {
  19808. options = options || {};
  19809. options.raw = true;
  19810. return deflate(input, options);
  19811. }
  19812. /**
  19813. * gzip(data[, options]) -> Uint8Array|Array|String
  19814. * - data (Uint8Array|Array|String): input data to compress.
  19815. * - options (Object): zlib deflate options.
  19816. *
  19817. * The same as [[deflate]], but create gzip wrapper instead of
  19818. * deflate one.
  19819. **/
  19820. function gzip(input, options) {
  19821. options = options || {};
  19822. options.gzip = true;
  19823. return deflate(input, options);
  19824. }
  19825. exports.Deflate = Deflate;
  19826. exports.deflate = deflate;
  19827. exports.deflateRaw = deflateRaw;
  19828. exports.gzip = gzip;
  19829. },{"./utils/common":268,"./utils/strings":269,"./zlib/deflate":273,"./zlib/messages":278,"./zlib/zstream":280}],267:[function(require,module,exports){
  19830. 'use strict';
  19831. var zlib_inflate = require('./zlib/inflate');
  19832. var utils = require('./utils/common');
  19833. var strings = require('./utils/strings');
  19834. var c = require('./zlib/constants');
  19835. var msg = require('./zlib/messages');
  19836. var ZStream = require('./zlib/zstream');
  19837. var GZheader = require('./zlib/gzheader');
  19838. var toString = Object.prototype.toString;
  19839. /**
  19840. * class Inflate
  19841. *
  19842. * Generic JS-style wrapper for zlib calls. If you don't need
  19843. * streaming behaviour - use more simple functions: [[inflate]]
  19844. * and [[inflateRaw]].
  19845. **/
  19846. /* internal
  19847. * inflate.chunks -> Array
  19848. *
  19849. * Chunks of output data, if [[Inflate#onData]] not overridden.
  19850. **/
  19851. /**
  19852. * Inflate.result -> Uint8Array|Array|String
  19853. *
  19854. * Uncompressed result, generated by default [[Inflate#onData]]
  19855. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19856. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19857. * push a chunk with explicit flush (call [[Inflate#push]] with
  19858. * `Z_SYNC_FLUSH` param).
  19859. **/
  19860. /**
  19861. * Inflate.err -> Number
  19862. *
  19863. * Error code after inflate finished. 0 (Z_OK) on success.
  19864. * Should be checked if broken data possible.
  19865. **/
  19866. /**
  19867. * Inflate.msg -> String
  19868. *
  19869. * Error message, if [[Inflate.err]] != 0
  19870. **/
  19871. /**
  19872. * new Inflate(options)
  19873. * - options (Object): zlib inflate options.
  19874. *
  19875. * Creates new inflator instance with specified params. Throws exception
  19876. * on bad params. Supported options:
  19877. *
  19878. * - `windowBits`
  19879. * - `dictionary`
  19880. *
  19881. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19882. * for more information on these.
  19883. *
  19884. * Additional options, for internal needs:
  19885. *
  19886. * - `chunkSize` - size of generated data chunks (16K by default)
  19887. * - `raw` (Boolean) - do raw inflate
  19888. * - `to` (String) - if equal to 'string', then result will be converted
  19889. * from utf8 to utf16 (javascript) string. When string output requested,
  19890. * chunk length can differ from `chunkSize`, depending on content.
  19891. *
  19892. * By default, when no options set, autodetect deflate/gzip data format via
  19893. * wrapper header.
  19894. *
  19895. * ##### Example:
  19896. *
  19897. * ```javascript
  19898. * var pako = require('pako')
  19899. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19900. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19901. *
  19902. * var inflate = new pako.Inflate({ level: 3});
  19903. *
  19904. * inflate.push(chunk1, false);
  19905. * inflate.push(chunk2, true); // true -> last chunk
  19906. *
  19907. * if (inflate.err) { throw new Error(inflate.err); }
  19908. *
  19909. * console.log(inflate.result);
  19910. * ```
  19911. **/
  19912. function Inflate(options) {
  19913. if (!(this instanceof Inflate)) return new Inflate(options);
  19914. this.options = utils.assign({
  19915. chunkSize: 16384,
  19916. windowBits: 0,
  19917. to: ''
  19918. }, options || {});
  19919. var opt = this.options;
  19920. // Force window size for `raw` data, if not set directly,
  19921. // because we have no header for autodetect.
  19922. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19923. opt.windowBits = -opt.windowBits;
  19924. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19925. }
  19926. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19927. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19928. !(options && options.windowBits)) {
  19929. opt.windowBits += 32;
  19930. }
  19931. // Gzip header has no info about windows size, we can do autodetect only
  19932. // for deflate. So, if window size not set, force it to max when gzip possible
  19933. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19934. // bit 3 (16) -> gzipped data
  19935. // bit 4 (32) -> autodetect gzip/deflate
  19936. if ((opt.windowBits & 15) === 0) {
  19937. opt.windowBits |= 15;
  19938. }
  19939. }
  19940. this.err = 0; // error code, if happens (0 = Z_OK)
  19941. this.msg = ''; // error message
  19942. this.ended = false; // used to avoid multiple onEnd() calls
  19943. this.chunks = []; // chunks of compressed data
  19944. this.strm = new ZStream();
  19945. this.strm.avail_out = 0;
  19946. var status = zlib_inflate.inflateInit2(
  19947. this.strm,
  19948. opt.windowBits
  19949. );
  19950. if (status !== c.Z_OK) {
  19951. throw new Error(msg[status]);
  19952. }
  19953. this.header = new GZheader();
  19954. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19955. }
  19956. /**
  19957. * Inflate#push(data[, mode]) -> Boolean
  19958. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19959. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19960. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  19961. *
  19962. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19963. * new output chunks. Returns `true` on success. The last data block must have
  19964. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19965. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19966. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19967. *
  19968. * On fail call [[Inflate#onEnd]] with error code and return false.
  19969. *
  19970. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19971. * format is detected automatically). Also, don't skip last param and always
  19972. * use the same type in your code (boolean or number). That will improve JS speed.
  19973. *
  19974. * For regular `Array`-s make sure all elements are [0..255].
  19975. *
  19976. * ##### Example
  19977. *
  19978. * ```javascript
  19979. * push(chunk, false); // push one of data chunks
  19980. * ...
  19981. * push(chunk, true); // push last chunk
  19982. * ```
  19983. **/
  19984. Inflate.prototype.push = function (data, mode) {
  19985. var strm = this.strm;
  19986. var chunkSize = this.options.chunkSize;
  19987. var dictionary = this.options.dictionary;
  19988. var status, _mode;
  19989. var next_out_utf8, tail, utf8str;
  19990. var dict;
  19991. // Flag to properly process Z_BUF_ERROR on testing inflate call
  19992. // when we check that all output data was flushed.
  19993. var allowBufError = false;
  19994. if (this.ended) { return false; }
  19995. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19996. // Convert data if needed
  19997. if (typeof data === 'string') {
  19998. // Only binary strings can be decompressed on practice
  19999. strm.input = strings.binstring2buf(data);
  20000. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20001. strm.input = new Uint8Array(data);
  20002. } else {
  20003. strm.input = data;
  20004. }
  20005. strm.next_in = 0;
  20006. strm.avail_in = strm.input.length;
  20007. do {
  20008. if (strm.avail_out === 0) {
  20009. strm.output = new utils.Buf8(chunkSize);
  20010. strm.next_out = 0;
  20011. strm.avail_out = chunkSize;
  20012. }
  20013. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20014. if (status === c.Z_NEED_DICT && dictionary) {
  20015. // Convert data if needed
  20016. if (typeof dictionary === 'string') {
  20017. dict = strings.string2buf(dictionary);
  20018. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  20019. dict = new Uint8Array(dictionary);
  20020. } else {
  20021. dict = dictionary;
  20022. }
  20023. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  20024. }
  20025. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  20026. status = c.Z_OK;
  20027. allowBufError = false;
  20028. }
  20029. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20030. this.onEnd(status);
  20031. this.ended = true;
  20032. return false;
  20033. }
  20034. if (strm.next_out) {
  20035. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20036. if (this.options.to === 'string') {
  20037. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20038. tail = strm.next_out - next_out_utf8;
  20039. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20040. // move tail
  20041. strm.next_out = tail;
  20042. strm.avail_out = chunkSize - tail;
  20043. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20044. this.onData(utf8str);
  20045. } else {
  20046. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20047. }
  20048. }
  20049. }
  20050. // When no more input data, we should check that internal inflate buffers
  20051. // are flushed. The only way to do it when avail_out = 0 - run one more
  20052. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  20053. // Here we set flag to process this error properly.
  20054. //
  20055. // NOTE. Deflate does not return error in this case and does not needs such
  20056. // logic.
  20057. if (strm.avail_in === 0 && strm.avail_out === 0) {
  20058. allowBufError = true;
  20059. }
  20060. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  20061. if (status === c.Z_STREAM_END) {
  20062. _mode = c.Z_FINISH;
  20063. }
  20064. // Finalize on the last chunk.
  20065. if (_mode === c.Z_FINISH) {
  20066. status = zlib_inflate.inflateEnd(this.strm);
  20067. this.onEnd(status);
  20068. this.ended = true;
  20069. return status === c.Z_OK;
  20070. }
  20071. // callback interim results if Z_SYNC_FLUSH.
  20072. if (_mode === c.Z_SYNC_FLUSH) {
  20073. this.onEnd(c.Z_OK);
  20074. strm.avail_out = 0;
  20075. return true;
  20076. }
  20077. return true;
  20078. };
  20079. /**
  20080. * Inflate#onData(chunk) -> Void
  20081. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  20082. * on js engine support. When string output requested, each chunk
  20083. * will be string.
  20084. *
  20085. * By default, stores data blocks in `chunks[]` property and glue
  20086. * those in `onEnd`. Override this handler, if you need another behaviour.
  20087. **/
  20088. Inflate.prototype.onData = function (chunk) {
  20089. this.chunks.push(chunk);
  20090. };
  20091. /**
  20092. * Inflate#onEnd(status) -> Void
  20093. * - status (Number): inflate status. 0 (Z_OK) on success,
  20094. * other if not.
  20095. *
  20096. * Called either after you tell inflate that the input stream is
  20097. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20098. * or if an error happened. By default - join collected chunks,
  20099. * free memory and fill `results` / `err` properties.
  20100. **/
  20101. Inflate.prototype.onEnd = function (status) {
  20102. // On success - join
  20103. if (status === c.Z_OK) {
  20104. if (this.options.to === 'string') {
  20105. // Glue & convert here, until we teach pako to send
  20106. // utf8 aligned strings to onData
  20107. this.result = this.chunks.join('');
  20108. } else {
  20109. this.result = utils.flattenChunks(this.chunks);
  20110. }
  20111. }
  20112. this.chunks = [];
  20113. this.err = status;
  20114. this.msg = this.strm.msg;
  20115. };
  20116. /**
  20117. * inflate(data[, options]) -> Uint8Array|Array|String
  20118. * - data (Uint8Array|Array|String): input data to decompress.
  20119. * - options (Object): zlib inflate options.
  20120. *
  20121. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20122. * format via wrapper header by default. That's why we don't provide
  20123. * separate `ungzip` method.
  20124. *
  20125. * Supported options are:
  20126. *
  20127. * - windowBits
  20128. *
  20129. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20130. * for more information.
  20131. *
  20132. * Sugar (options):
  20133. *
  20134. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20135. * negative windowBits implicitly.
  20136. * - `to` (String) - if equal to 'string', then result will be converted
  20137. * from utf8 to utf16 (javascript) string. When string output requested,
  20138. * chunk length can differ from `chunkSize`, depending on content.
  20139. *
  20140. *
  20141. * ##### Example:
  20142. *
  20143. * ```javascript
  20144. * var pako = require('pako')
  20145. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20146. * , output;
  20147. *
  20148. * try {
  20149. * output = pako.inflate(input);
  20150. * } catch (err)
  20151. * console.log(err);
  20152. * }
  20153. * ```
  20154. **/
  20155. function inflate(input, options) {
  20156. var inflator = new Inflate(options);
  20157. inflator.push(input, true);
  20158. // That will never happens, if you don't cheat with options :)
  20159. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  20160. return inflator.result;
  20161. }
  20162. /**
  20163. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20164. * - data (Uint8Array|Array|String): input data to decompress.
  20165. * - options (Object): zlib inflate options.
  20166. *
  20167. * The same as [[inflate]], but creates raw data, without wrapper
  20168. * (header and adler32 crc).
  20169. **/
  20170. function inflateRaw(input, options) {
  20171. options = options || {};
  20172. options.raw = true;
  20173. return inflate(input, options);
  20174. }
  20175. /**
  20176. * ungzip(data[, options]) -> Uint8Array|Array|String
  20177. * - data (Uint8Array|Array|String): input data to decompress.
  20178. * - options (Object): zlib inflate options.
  20179. *
  20180. * Just shortcut to [[inflate]], because it autodetects format
  20181. * by header.content. Done for convenience.
  20182. **/
  20183. exports.Inflate = Inflate;
  20184. exports.inflate = inflate;
  20185. exports.inflateRaw = inflateRaw;
  20186. exports.ungzip = inflate;
  20187. },{"./utils/common":268,"./utils/strings":269,"./zlib/constants":271,"./zlib/gzheader":274,"./zlib/inflate":276,"./zlib/messages":278,"./zlib/zstream":280}],268:[function(require,module,exports){
  20188. arguments[4][35][0].apply(exports,arguments)
  20189. },{"dup":35}],269:[function(require,module,exports){
  20190. // String encode/decode helpers
  20191. 'use strict';
  20192. var utils = require('./common');
  20193. // Quick check if we can use fast array to bin string conversion
  20194. //
  20195. // - apply(Array) can fail on Android 2.2
  20196. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  20197. //
  20198. var STR_APPLY_OK = true;
  20199. var STR_APPLY_UIA_OK = true;
  20200. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  20201. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  20202. // Table with utf8 lengths (calculated by first byte of sequence)
  20203. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20204. // because max possible codepoint is 0x10ffff
  20205. var _utf8len = new utils.Buf8(256);
  20206. for (var q = 0; q < 256; q++) {
  20207. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20208. }
  20209. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  20210. // convert string to array (typed, when possible)
  20211. exports.string2buf = function (str) {
  20212. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20213. // count binary size
  20214. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20215. c = str.charCodeAt(m_pos);
  20216. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  20217. c2 = str.charCodeAt(m_pos + 1);
  20218. if ((c2 & 0xfc00) === 0xdc00) {
  20219. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20220. m_pos++;
  20221. }
  20222. }
  20223. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20224. }
  20225. // allocate buffer
  20226. buf = new utils.Buf8(buf_len);
  20227. // convert
  20228. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  20229. c = str.charCodeAt(m_pos);
  20230. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  20231. c2 = str.charCodeAt(m_pos + 1);
  20232. if ((c2 & 0xfc00) === 0xdc00) {
  20233. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20234. m_pos++;
  20235. }
  20236. }
  20237. if (c < 0x80) {
  20238. /* one byte */
  20239. buf[i++] = c;
  20240. } else if (c < 0x800) {
  20241. /* two bytes */
  20242. buf[i++] = 0xC0 | (c >>> 6);
  20243. buf[i++] = 0x80 | (c & 0x3f);
  20244. } else if (c < 0x10000) {
  20245. /* three bytes */
  20246. buf[i++] = 0xE0 | (c >>> 12);
  20247. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20248. buf[i++] = 0x80 | (c & 0x3f);
  20249. } else {
  20250. /* four bytes */
  20251. buf[i++] = 0xf0 | (c >>> 18);
  20252. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20253. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20254. buf[i++] = 0x80 | (c & 0x3f);
  20255. }
  20256. }
  20257. return buf;
  20258. };
  20259. // Helper (used in 2 places)
  20260. function buf2binstring(buf, len) {
  20261. // use fallback for big arrays to avoid stack overflow
  20262. if (len < 65537) {
  20263. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20264. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20265. }
  20266. }
  20267. var result = '';
  20268. for (var i = 0; i < len; i++) {
  20269. result += String.fromCharCode(buf[i]);
  20270. }
  20271. return result;
  20272. }
  20273. // Convert byte array to binary string
  20274. exports.buf2binstring = function (buf) {
  20275. return buf2binstring(buf, buf.length);
  20276. };
  20277. // Convert binary string (typed, when possible)
  20278. exports.binstring2buf = function (str) {
  20279. var buf = new utils.Buf8(str.length);
  20280. for (var i = 0, len = buf.length; i < len; i++) {
  20281. buf[i] = str.charCodeAt(i);
  20282. }
  20283. return buf;
  20284. };
  20285. // convert array to string
  20286. exports.buf2string = function (buf, max) {
  20287. var i, out, c, c_len;
  20288. var len = max || buf.length;
  20289. // Reserve max possible length (2 words per char)
  20290. // NB: by unknown reasons, Array is significantly faster for
  20291. // String.fromCharCode.apply than Uint16Array.
  20292. var utf16buf = new Array(len * 2);
  20293. for (out = 0, i = 0; i < len;) {
  20294. c = buf[i++];
  20295. // quick process ascii
  20296. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20297. c_len = _utf8len[c];
  20298. // skip 5 & 6 byte codes
  20299. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  20300. // apply mask on first byte
  20301. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20302. // join the rest
  20303. while (c_len > 1 && i < len) {
  20304. c = (c << 6) | (buf[i++] & 0x3f);
  20305. c_len--;
  20306. }
  20307. // terminated by end of string?
  20308. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20309. if (c < 0x10000) {
  20310. utf16buf[out++] = c;
  20311. } else {
  20312. c -= 0x10000;
  20313. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20314. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20315. }
  20316. }
  20317. return buf2binstring(utf16buf, out);
  20318. };
  20319. // Calculate max possible position in utf8 buffer,
  20320. // that will not break sequence. If that's not possible
  20321. // - (very small limits) return max size as is.
  20322. //
  20323. // buf[] - utf8 bytes array
  20324. // max - length limit (mandatory);
  20325. exports.utf8border = function (buf, max) {
  20326. var pos;
  20327. max = max || buf.length;
  20328. if (max > buf.length) { max = buf.length; }
  20329. // go back from last position, until start of sequence found
  20330. pos = max - 1;
  20331. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20332. // Very small and broken sequence,
  20333. // return max, because we should return something anyway.
  20334. if (pos < 0) { return max; }
  20335. // If we came to start of buffer - that means buffer is too small,
  20336. // return max too.
  20337. if (pos === 0) { return max; }
  20338. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20339. };
  20340. },{"./common":268}],270:[function(require,module,exports){
  20341. arguments[4][36][0].apply(exports,arguments)
  20342. },{"dup":36}],271:[function(require,module,exports){
  20343. arguments[4][37][0].apply(exports,arguments)
  20344. },{"dup":37}],272:[function(require,module,exports){
  20345. arguments[4][38][0].apply(exports,arguments)
  20346. },{"dup":38}],273:[function(require,module,exports){
  20347. 'use strict';
  20348. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  20349. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  20350. //
  20351. // This software is provided 'as-is', without any express or implied
  20352. // warranty. In no event will the authors be held liable for any damages
  20353. // arising from the use of this software.
  20354. //
  20355. // Permission is granted to anyone to use this software for any purpose,
  20356. // including commercial applications, and to alter it and redistribute it
  20357. // freely, subject to the following restrictions:
  20358. //
  20359. // 1. The origin of this software must not be misrepresented; you must not
  20360. // claim that you wrote the original software. If you use this software
  20361. // in a product, an acknowledgment in the product documentation would be
  20362. // appreciated but is not required.
  20363. // 2. Altered source versions must be plainly marked as such, and must not be
  20364. // misrepresented as being the original software.
  20365. // 3. This notice may not be removed or altered from any source distribution.
  20366. var utils = require('../utils/common');
  20367. var trees = require('./trees');
  20368. var adler32 = require('./adler32');
  20369. var crc32 = require('./crc32');
  20370. var msg = require('./messages');
  20371. /* Public constants ==========================================================*/
  20372. /* ===========================================================================*/
  20373. /* Allowed flush values; see deflate() and inflate() below for details */
  20374. var Z_NO_FLUSH = 0;
  20375. var Z_PARTIAL_FLUSH = 1;
  20376. //var Z_SYNC_FLUSH = 2;
  20377. var Z_FULL_FLUSH = 3;
  20378. var Z_FINISH = 4;
  20379. var Z_BLOCK = 5;
  20380. //var Z_TREES = 6;
  20381. /* Return codes for the compression/decompression functions. Negative values
  20382. * are errors, positive values are used for special but normal events.
  20383. */
  20384. var Z_OK = 0;
  20385. var Z_STREAM_END = 1;
  20386. //var Z_NEED_DICT = 2;
  20387. //var Z_ERRNO = -1;
  20388. var Z_STREAM_ERROR = -2;
  20389. var Z_DATA_ERROR = -3;
  20390. //var Z_MEM_ERROR = -4;
  20391. var Z_BUF_ERROR = -5;
  20392. //var Z_VERSION_ERROR = -6;
  20393. /* compression levels */
  20394. //var Z_NO_COMPRESSION = 0;
  20395. //var Z_BEST_SPEED = 1;
  20396. //var Z_BEST_COMPRESSION = 9;
  20397. var Z_DEFAULT_COMPRESSION = -1;
  20398. var Z_FILTERED = 1;
  20399. var Z_HUFFMAN_ONLY = 2;
  20400. var Z_RLE = 3;
  20401. var Z_FIXED = 4;
  20402. var Z_DEFAULT_STRATEGY = 0;
  20403. /* Possible values of the data_type field (though see inflate()) */
  20404. //var Z_BINARY = 0;
  20405. //var Z_TEXT = 1;
  20406. //var Z_ASCII = 1; // = Z_TEXT
  20407. var Z_UNKNOWN = 2;
  20408. /* The deflate compression method */
  20409. var Z_DEFLATED = 8;
  20410. /*============================================================================*/
  20411. var MAX_MEM_LEVEL = 9;
  20412. /* Maximum value for memLevel in deflateInit2 */
  20413. var MAX_WBITS = 15;
  20414. /* 32K LZ77 window */
  20415. var DEF_MEM_LEVEL = 8;
  20416. var LENGTH_CODES = 29;
  20417. /* number of length codes, not counting the special END_BLOCK code */
  20418. var LITERALS = 256;
  20419. /* number of literal bytes 0..255 */
  20420. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20421. /* number of Literal or Length codes, including the END_BLOCK code */
  20422. var D_CODES = 30;
  20423. /* number of distance codes */
  20424. var BL_CODES = 19;
  20425. /* number of codes used to transfer the bit lengths */
  20426. var HEAP_SIZE = 2 * L_CODES + 1;
  20427. /* maximum heap size */
  20428. var MAX_BITS = 15;
  20429. /* All codes must not exceed MAX_BITS bits */
  20430. var MIN_MATCH = 3;
  20431. var MAX_MATCH = 258;
  20432. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20433. var PRESET_DICT = 0x20;
  20434. var INIT_STATE = 42;
  20435. var EXTRA_STATE = 69;
  20436. var NAME_STATE = 73;
  20437. var COMMENT_STATE = 91;
  20438. var HCRC_STATE = 103;
  20439. var BUSY_STATE = 113;
  20440. var FINISH_STATE = 666;
  20441. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20442. var BS_BLOCK_DONE = 2; /* block flush performed */
  20443. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20444. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20445. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20446. function err(strm, errorCode) {
  20447. strm.msg = msg[errorCode];
  20448. return errorCode;
  20449. }
  20450. function rank(f) {
  20451. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20452. }
  20453. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20454. /* =========================================================================
  20455. * Flush as much pending output as possible. All deflate() output goes
  20456. * through this function so some applications may wish to modify it
  20457. * to avoid allocating a large strm->output buffer and copying into it.
  20458. * (See also read_buf()).
  20459. */
  20460. function flush_pending(strm) {
  20461. var s = strm.state;
  20462. //_tr_flush_bits(s);
  20463. var len = s.pending;
  20464. if (len > strm.avail_out) {
  20465. len = strm.avail_out;
  20466. }
  20467. if (len === 0) { return; }
  20468. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20469. strm.next_out += len;
  20470. s.pending_out += len;
  20471. strm.total_out += len;
  20472. strm.avail_out -= len;
  20473. s.pending -= len;
  20474. if (s.pending === 0) {
  20475. s.pending_out = 0;
  20476. }
  20477. }
  20478. function flush_block_only(s, last) {
  20479. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20480. s.block_start = s.strstart;
  20481. flush_pending(s.strm);
  20482. }
  20483. function put_byte(s, b) {
  20484. s.pending_buf[s.pending++] = b;
  20485. }
  20486. /* =========================================================================
  20487. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20488. * IN assertion: the stream state is correct and there is enough room in
  20489. * pending_buf.
  20490. */
  20491. function putShortMSB(s, b) {
  20492. // put_byte(s, (Byte)(b >> 8));
  20493. // put_byte(s, (Byte)(b & 0xff));
  20494. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20495. s.pending_buf[s.pending++] = b & 0xff;
  20496. }
  20497. /* ===========================================================================
  20498. * Read a new buffer from the current input stream, update the adler32
  20499. * and total number of bytes read. All deflate() input goes through
  20500. * this function so some applications may wish to modify it to avoid
  20501. * allocating a large strm->input buffer and copying from it.
  20502. * (See also flush_pending()).
  20503. */
  20504. function read_buf(strm, buf, start, size) {
  20505. var len = strm.avail_in;
  20506. if (len > size) { len = size; }
  20507. if (len === 0) { return 0; }
  20508. strm.avail_in -= len;
  20509. // zmemcpy(buf, strm->next_in, len);
  20510. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20511. if (strm.state.wrap === 1) {
  20512. strm.adler = adler32(strm.adler, buf, len, start);
  20513. }
  20514. else if (strm.state.wrap === 2) {
  20515. strm.adler = crc32(strm.adler, buf, len, start);
  20516. }
  20517. strm.next_in += len;
  20518. strm.total_in += len;
  20519. return len;
  20520. }
  20521. /* ===========================================================================
  20522. * Set match_start to the longest match starting at the given string and
  20523. * return its length. Matches shorter or equal to prev_length are discarded,
  20524. * in which case the result is equal to prev_length and match_start is
  20525. * garbage.
  20526. * IN assertions: cur_match is the head of the hash chain for the current
  20527. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20528. * OUT assertion: the match length is not greater than s->lookahead.
  20529. */
  20530. function longest_match(s, cur_match) {
  20531. var chain_length = s.max_chain_length; /* max hash chain length */
  20532. var scan = s.strstart; /* current string */
  20533. var match; /* matched string */
  20534. var len; /* length of current match */
  20535. var best_len = s.prev_length; /* best match length so far */
  20536. var nice_match = s.nice_match; /* stop if match long enough */
  20537. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20538. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20539. var _win = s.window; // shortcut
  20540. var wmask = s.w_mask;
  20541. var prev = s.prev;
  20542. /* Stop when cur_match becomes <= limit. To simplify the code,
  20543. * we prevent matches with the string of window index 0.
  20544. */
  20545. var strend = s.strstart + MAX_MATCH;
  20546. var scan_end1 = _win[scan + best_len - 1];
  20547. var scan_end = _win[scan + best_len];
  20548. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20549. * It is easy to get rid of this optimization if necessary.
  20550. */
  20551. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20552. /* Do not waste too much time if we already have a good match: */
  20553. if (s.prev_length >= s.good_match) {
  20554. chain_length >>= 2;
  20555. }
  20556. /* Do not look for matches beyond the end of the input. This is necessary
  20557. * to make deflate deterministic.
  20558. */
  20559. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20560. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20561. do {
  20562. // Assert(cur_match < s->strstart, "no future");
  20563. match = cur_match;
  20564. /* Skip to next match if the match length cannot increase
  20565. * or if the match length is less than 2. Note that the checks below
  20566. * for insufficient lookahead only occur occasionally for performance
  20567. * reasons. Therefore uninitialized memory will be accessed, and
  20568. * conditional jumps will be made that depend on those values.
  20569. * However the length of the match is limited to the lookahead, so
  20570. * the output of deflate is not affected by the uninitialized values.
  20571. */
  20572. if (_win[match + best_len] !== scan_end ||
  20573. _win[match + best_len - 1] !== scan_end1 ||
  20574. _win[match] !== _win[scan] ||
  20575. _win[++match] !== _win[scan + 1]) {
  20576. continue;
  20577. }
  20578. /* The check at best_len-1 can be removed because it will be made
  20579. * again later. (This heuristic is not always a win.)
  20580. * It is not necessary to compare scan[2] and match[2] since they
  20581. * are always equal when the other bytes match, given that
  20582. * the hash keys are equal and that HASH_BITS >= 8.
  20583. */
  20584. scan += 2;
  20585. match++;
  20586. // Assert(*scan == *match, "match[2]?");
  20587. /* We check for insufficient lookahead only every 8th comparison;
  20588. * the 256th check will be made at strstart+258.
  20589. */
  20590. do {
  20591. /*jshint noempty:false*/
  20592. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20593. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20594. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20595. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20596. scan < strend);
  20597. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20598. len = MAX_MATCH - (strend - scan);
  20599. scan = strend - MAX_MATCH;
  20600. if (len > best_len) {
  20601. s.match_start = cur_match;
  20602. best_len = len;
  20603. if (len >= nice_match) {
  20604. break;
  20605. }
  20606. scan_end1 = _win[scan + best_len - 1];
  20607. scan_end = _win[scan + best_len];
  20608. }
  20609. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20610. if (best_len <= s.lookahead) {
  20611. return best_len;
  20612. }
  20613. return s.lookahead;
  20614. }
  20615. /* ===========================================================================
  20616. * Fill the window when the lookahead becomes insufficient.
  20617. * Updates strstart and lookahead.
  20618. *
  20619. * IN assertion: lookahead < MIN_LOOKAHEAD
  20620. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20621. * At least one byte has been read, or avail_in == 0; reads are
  20622. * performed for at least two bytes (required for the zip translate_eol
  20623. * option -- not supported here).
  20624. */
  20625. function fill_window(s) {
  20626. var _w_size = s.w_size;
  20627. var p, n, m, more, str;
  20628. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20629. do {
  20630. more = s.window_size - s.lookahead - s.strstart;
  20631. // JS ints have 32 bit, block below not needed
  20632. /* Deal with !@#$% 64K limit: */
  20633. //if (sizeof(int) <= 2) {
  20634. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20635. // more = wsize;
  20636. //
  20637. // } else if (more == (unsigned)(-1)) {
  20638. // /* Very unlikely, but possible on 16 bit machine if
  20639. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20640. // */
  20641. // more--;
  20642. // }
  20643. //}
  20644. /* If the window is almost full and there is insufficient lookahead,
  20645. * move the upper half to the lower one to make room in the upper half.
  20646. */
  20647. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20648. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20649. s.match_start -= _w_size;
  20650. s.strstart -= _w_size;
  20651. /* we now have strstart >= MAX_DIST */
  20652. s.block_start -= _w_size;
  20653. /* Slide the hash table (could be avoided with 32 bit values
  20654. at the expense of memory usage). We slide even when level == 0
  20655. to keep the hash table consistent if we switch back to level > 0
  20656. later. (Using level 0 permanently is not an optimal usage of
  20657. zlib, so we don't care about this pathological case.)
  20658. */
  20659. n = s.hash_size;
  20660. p = n;
  20661. do {
  20662. m = s.head[--p];
  20663. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20664. } while (--n);
  20665. n = _w_size;
  20666. p = n;
  20667. do {
  20668. m = s.prev[--p];
  20669. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20670. /* If n is not on any hash chain, prev[n] is garbage but
  20671. * its value will never be used.
  20672. */
  20673. } while (--n);
  20674. more += _w_size;
  20675. }
  20676. if (s.strm.avail_in === 0) {
  20677. break;
  20678. }
  20679. /* If there was no sliding:
  20680. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20681. * more == window_size - lookahead - strstart
  20682. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20683. * => more >= window_size - 2*WSIZE + 2
  20684. * In the BIG_MEM or MMAP case (not yet supported),
  20685. * window_size == input_size + MIN_LOOKAHEAD &&
  20686. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20687. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20688. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20689. */
  20690. //Assert(more >= 2, "more < 2");
  20691. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20692. s.lookahead += n;
  20693. /* Initialize the hash value now that we have some input: */
  20694. if (s.lookahead + s.insert >= MIN_MATCH) {
  20695. str = s.strstart - s.insert;
  20696. s.ins_h = s.window[str];
  20697. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20698. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20699. //#if MIN_MATCH != 3
  20700. // Call update_hash() MIN_MATCH-3 more times
  20701. //#endif
  20702. while (s.insert) {
  20703. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20704. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  20705. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20706. s.head[s.ins_h] = str;
  20707. str++;
  20708. s.insert--;
  20709. if (s.lookahead + s.insert < MIN_MATCH) {
  20710. break;
  20711. }
  20712. }
  20713. }
  20714. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20715. * but this is not important since only literal bytes will be emitted.
  20716. */
  20717. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20718. /* If the WIN_INIT bytes after the end of the current data have never been
  20719. * written, then zero those bytes in order to avoid memory check reports of
  20720. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20721. * the longest match routines. Update the high water mark for the next
  20722. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20723. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20724. */
  20725. // if (s.high_water < s.window_size) {
  20726. // var curr = s.strstart + s.lookahead;
  20727. // var init = 0;
  20728. //
  20729. // if (s.high_water < curr) {
  20730. // /* Previous high water mark below current data -- zero WIN_INIT
  20731. // * bytes or up to end of window, whichever is less.
  20732. // */
  20733. // init = s.window_size - curr;
  20734. // if (init > WIN_INIT)
  20735. // init = WIN_INIT;
  20736. // zmemzero(s->window + curr, (unsigned)init);
  20737. // s->high_water = curr + init;
  20738. // }
  20739. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20740. // /* High water mark at or above current data, but below current data
  20741. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20742. // * to end of window, whichever is less.
  20743. // */
  20744. // init = (ulg)curr + WIN_INIT - s->high_water;
  20745. // if (init > s->window_size - s->high_water)
  20746. // init = s->window_size - s->high_water;
  20747. // zmemzero(s->window + s->high_water, (unsigned)init);
  20748. // s->high_water += init;
  20749. // }
  20750. // }
  20751. //
  20752. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20753. // "not enough room for search");
  20754. }
  20755. /* ===========================================================================
  20756. * Copy without compression as much as possible from the input stream, return
  20757. * the current block state.
  20758. * This function does not insert new strings in the dictionary since
  20759. * uncompressible data is probably not useful. This function is used
  20760. * only for the level=0 compression option.
  20761. * NOTE: this function should be optimized to avoid extra copying from
  20762. * window to pending_buf.
  20763. */
  20764. function deflate_stored(s, flush) {
  20765. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20766. * to pending_buf_size, and each stored block has a 5 byte header:
  20767. */
  20768. var max_block_size = 0xffff;
  20769. if (max_block_size > s.pending_buf_size - 5) {
  20770. max_block_size = s.pending_buf_size - 5;
  20771. }
  20772. /* Copy as much as possible from input to output: */
  20773. for (;;) {
  20774. /* Fill the window as much as possible: */
  20775. if (s.lookahead <= 1) {
  20776. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20777. // s->block_start >= (long)s->w_size, "slide too late");
  20778. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20779. // s.block_start >= s.w_size)) {
  20780. // throw new Error("slide too late");
  20781. // }
  20782. fill_window(s);
  20783. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20784. return BS_NEED_MORE;
  20785. }
  20786. if (s.lookahead === 0) {
  20787. break;
  20788. }
  20789. /* flush the current block */
  20790. }
  20791. //Assert(s->block_start >= 0L, "block gone");
  20792. // if (s.block_start < 0) throw new Error("block gone");
  20793. s.strstart += s.lookahead;
  20794. s.lookahead = 0;
  20795. /* Emit a stored block if pending_buf will be full: */
  20796. var max_start = s.block_start + max_block_size;
  20797. if (s.strstart === 0 || s.strstart >= max_start) {
  20798. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20799. s.lookahead = s.strstart - max_start;
  20800. s.strstart = max_start;
  20801. /*** FLUSH_BLOCK(s, 0); ***/
  20802. flush_block_only(s, false);
  20803. if (s.strm.avail_out === 0) {
  20804. return BS_NEED_MORE;
  20805. }
  20806. /***/
  20807. }
  20808. /* Flush if we may have to slide, otherwise block_start may become
  20809. * negative and the data will be gone:
  20810. */
  20811. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20812. /*** FLUSH_BLOCK(s, 0); ***/
  20813. flush_block_only(s, false);
  20814. if (s.strm.avail_out === 0) {
  20815. return BS_NEED_MORE;
  20816. }
  20817. /***/
  20818. }
  20819. }
  20820. s.insert = 0;
  20821. if (flush === Z_FINISH) {
  20822. /*** FLUSH_BLOCK(s, 1); ***/
  20823. flush_block_only(s, true);
  20824. if (s.strm.avail_out === 0) {
  20825. return BS_FINISH_STARTED;
  20826. }
  20827. /***/
  20828. return BS_FINISH_DONE;
  20829. }
  20830. if (s.strstart > s.block_start) {
  20831. /*** FLUSH_BLOCK(s, 0); ***/
  20832. flush_block_only(s, false);
  20833. if (s.strm.avail_out === 0) {
  20834. return BS_NEED_MORE;
  20835. }
  20836. /***/
  20837. }
  20838. return BS_NEED_MORE;
  20839. }
  20840. /* ===========================================================================
  20841. * Compress as much as possible from the input stream, return the current
  20842. * block state.
  20843. * This function does not perform lazy evaluation of matches and inserts
  20844. * new strings in the dictionary only for unmatched strings or for short
  20845. * matches. It is used only for the fast compression options.
  20846. */
  20847. function deflate_fast(s, flush) {
  20848. var hash_head; /* head of the hash chain */
  20849. var bflush; /* set if current block must be flushed */
  20850. for (;;) {
  20851. /* Make sure that we always have enough lookahead, except
  20852. * at the end of the input file. We need MAX_MATCH bytes
  20853. * for the next match, plus MIN_MATCH bytes to insert the
  20854. * string following the next match.
  20855. */
  20856. if (s.lookahead < MIN_LOOKAHEAD) {
  20857. fill_window(s);
  20858. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20859. return BS_NEED_MORE;
  20860. }
  20861. if (s.lookahead === 0) {
  20862. break; /* flush the current block */
  20863. }
  20864. }
  20865. /* Insert the string window[strstart .. strstart+2] in the
  20866. * dictionary, and set hash_head to the head of the hash chain:
  20867. */
  20868. hash_head = 0/*NIL*/;
  20869. if (s.lookahead >= MIN_MATCH) {
  20870. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20871. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20872. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20873. s.head[s.ins_h] = s.strstart;
  20874. /***/
  20875. }
  20876. /* Find the longest match, discarding those <= prev_length.
  20877. * At this point we have always match_length < MIN_MATCH
  20878. */
  20879. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20880. /* To simplify the code, we prevent matches with the string
  20881. * of window index 0 (in particular we have to avoid a match
  20882. * of the string with itself at the start of the input file).
  20883. */
  20884. s.match_length = longest_match(s, hash_head);
  20885. /* longest_match() sets match_start */
  20886. }
  20887. if (s.match_length >= MIN_MATCH) {
  20888. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20889. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20890. s.match_length - MIN_MATCH, bflush); ***/
  20891. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20892. s.lookahead -= s.match_length;
  20893. /* Insert new strings in the hash table only if the match length
  20894. * is not too large. This saves time but degrades compression.
  20895. */
  20896. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20897. s.match_length--; /* string at strstart already in table */
  20898. do {
  20899. s.strstart++;
  20900. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20901. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20902. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20903. s.head[s.ins_h] = s.strstart;
  20904. /***/
  20905. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20906. * always MIN_MATCH bytes ahead.
  20907. */
  20908. } while (--s.match_length !== 0);
  20909. s.strstart++;
  20910. } else
  20911. {
  20912. s.strstart += s.match_length;
  20913. s.match_length = 0;
  20914. s.ins_h = s.window[s.strstart];
  20915. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20916. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20917. //#if MIN_MATCH != 3
  20918. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20919. //#endif
  20920. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20921. * matter since it will be recomputed at next deflate call.
  20922. */
  20923. }
  20924. } else {
  20925. /* No match, output a literal byte */
  20926. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20927. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20928. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20929. s.lookahead--;
  20930. s.strstart++;
  20931. }
  20932. if (bflush) {
  20933. /*** FLUSH_BLOCK(s, 0); ***/
  20934. flush_block_only(s, false);
  20935. if (s.strm.avail_out === 0) {
  20936. return BS_NEED_MORE;
  20937. }
  20938. /***/
  20939. }
  20940. }
  20941. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  20942. if (flush === Z_FINISH) {
  20943. /*** FLUSH_BLOCK(s, 1); ***/
  20944. flush_block_only(s, true);
  20945. if (s.strm.avail_out === 0) {
  20946. return BS_FINISH_STARTED;
  20947. }
  20948. /***/
  20949. return BS_FINISH_DONE;
  20950. }
  20951. if (s.last_lit) {
  20952. /*** FLUSH_BLOCK(s, 0); ***/
  20953. flush_block_only(s, false);
  20954. if (s.strm.avail_out === 0) {
  20955. return BS_NEED_MORE;
  20956. }
  20957. /***/
  20958. }
  20959. return BS_BLOCK_DONE;
  20960. }
  20961. /* ===========================================================================
  20962. * Same as above, but achieves better compression. We use a lazy
  20963. * evaluation for matches: a match is finally adopted only if there is
  20964. * no better match at the next window position.
  20965. */
  20966. function deflate_slow(s, flush) {
  20967. var hash_head; /* head of hash chain */
  20968. var bflush; /* set if current block must be flushed */
  20969. var max_insert;
  20970. /* Process the input block. */
  20971. for (;;) {
  20972. /* Make sure that we always have enough lookahead, except
  20973. * at the end of the input file. We need MAX_MATCH bytes
  20974. * for the next match, plus MIN_MATCH bytes to insert the
  20975. * string following the next match.
  20976. */
  20977. if (s.lookahead < MIN_LOOKAHEAD) {
  20978. fill_window(s);
  20979. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20980. return BS_NEED_MORE;
  20981. }
  20982. if (s.lookahead === 0) { break; } /* flush the current block */
  20983. }
  20984. /* Insert the string window[strstart .. strstart+2] in the
  20985. * dictionary, and set hash_head to the head of the hash chain:
  20986. */
  20987. hash_head = 0/*NIL*/;
  20988. if (s.lookahead >= MIN_MATCH) {
  20989. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20990. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20991. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20992. s.head[s.ins_h] = s.strstart;
  20993. /***/
  20994. }
  20995. /* Find the longest match, discarding those <= prev_length.
  20996. */
  20997. s.prev_length = s.match_length;
  20998. s.prev_match = s.match_start;
  20999. s.match_length = MIN_MATCH - 1;
  21000. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21001. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21002. /* To simplify the code, we prevent matches with the string
  21003. * of window index 0 (in particular we have to avoid a match
  21004. * of the string with itself at the start of the input file).
  21005. */
  21006. s.match_length = longest_match(s, hash_head);
  21007. /* longest_match() sets match_start */
  21008. if (s.match_length <= 5 &&
  21009. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21010. /* If prev_match is also MIN_MATCH, match_start is garbage
  21011. * but we will ignore the current match anyway.
  21012. */
  21013. s.match_length = MIN_MATCH - 1;
  21014. }
  21015. }
  21016. /* If there was a match at the previous step and the current
  21017. * match is not better, output the previous match:
  21018. */
  21019. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21020. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21021. /* Do not insert strings in hash table beyond this. */
  21022. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21023. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21024. s.prev_length - MIN_MATCH, bflush);***/
  21025. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  21026. /* Insert in hash table all strings up to the end of the match.
  21027. * strstart-1 and strstart are already inserted. If there is not
  21028. * enough lookahead, the last two strings are not inserted in
  21029. * the hash table.
  21030. */
  21031. s.lookahead -= s.prev_length - 1;
  21032. s.prev_length -= 2;
  21033. do {
  21034. if (++s.strstart <= max_insert) {
  21035. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21036. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21037. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21038. s.head[s.ins_h] = s.strstart;
  21039. /***/
  21040. }
  21041. } while (--s.prev_length !== 0);
  21042. s.match_available = 0;
  21043. s.match_length = MIN_MATCH - 1;
  21044. s.strstart++;
  21045. if (bflush) {
  21046. /*** FLUSH_BLOCK(s, 0); ***/
  21047. flush_block_only(s, false);
  21048. if (s.strm.avail_out === 0) {
  21049. return BS_NEED_MORE;
  21050. }
  21051. /***/
  21052. }
  21053. } else if (s.match_available) {
  21054. /* If there was no match at the previous position, output a
  21055. * single literal. If there was a match but the current match
  21056. * is longer, truncate the previous match to a single literal.
  21057. */
  21058. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21059. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21060. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  21061. if (bflush) {
  21062. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21063. flush_block_only(s, false);
  21064. /***/
  21065. }
  21066. s.strstart++;
  21067. s.lookahead--;
  21068. if (s.strm.avail_out === 0) {
  21069. return BS_NEED_MORE;
  21070. }
  21071. } else {
  21072. /* There is no previous match to compare with, wait for
  21073. * the next step to decide.
  21074. */
  21075. s.match_available = 1;
  21076. s.strstart++;
  21077. s.lookahead--;
  21078. }
  21079. }
  21080. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21081. if (s.match_available) {
  21082. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21083. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21084. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  21085. s.match_available = 0;
  21086. }
  21087. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  21088. if (flush === Z_FINISH) {
  21089. /*** FLUSH_BLOCK(s, 1); ***/
  21090. flush_block_only(s, true);
  21091. if (s.strm.avail_out === 0) {
  21092. return BS_FINISH_STARTED;
  21093. }
  21094. /***/
  21095. return BS_FINISH_DONE;
  21096. }
  21097. if (s.last_lit) {
  21098. /*** FLUSH_BLOCK(s, 0); ***/
  21099. flush_block_only(s, false);
  21100. if (s.strm.avail_out === 0) {
  21101. return BS_NEED_MORE;
  21102. }
  21103. /***/
  21104. }
  21105. return BS_BLOCK_DONE;
  21106. }
  21107. /* ===========================================================================
  21108. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21109. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21110. * deflate switches away from Z_RLE.)
  21111. */
  21112. function deflate_rle(s, flush) {
  21113. var bflush; /* set if current block must be flushed */
  21114. var prev; /* byte at distance one to match */
  21115. var scan, strend; /* scan goes up to strend for length of run */
  21116. var _win = s.window;
  21117. for (;;) {
  21118. /* Make sure that we always have enough lookahead, except
  21119. * at the end of the input file. We need MAX_MATCH bytes
  21120. * for the longest run, plus one for the unrolled loop.
  21121. */
  21122. if (s.lookahead <= MAX_MATCH) {
  21123. fill_window(s);
  21124. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21125. return BS_NEED_MORE;
  21126. }
  21127. if (s.lookahead === 0) { break; } /* flush the current block */
  21128. }
  21129. /* See how many times the previous byte repeats */
  21130. s.match_length = 0;
  21131. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21132. scan = s.strstart - 1;
  21133. prev = _win[scan];
  21134. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21135. strend = s.strstart + MAX_MATCH;
  21136. do {
  21137. /*jshint noempty:false*/
  21138. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21139. prev === _win[++scan] && prev === _win[++scan] &&
  21140. prev === _win[++scan] && prev === _win[++scan] &&
  21141. prev === _win[++scan] && prev === _win[++scan] &&
  21142. scan < strend);
  21143. s.match_length = MAX_MATCH - (strend - scan);
  21144. if (s.match_length > s.lookahead) {
  21145. s.match_length = s.lookahead;
  21146. }
  21147. }
  21148. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21149. }
  21150. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21151. if (s.match_length >= MIN_MATCH) {
  21152. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21153. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21154. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21155. s.lookahead -= s.match_length;
  21156. s.strstart += s.match_length;
  21157. s.match_length = 0;
  21158. } else {
  21159. /* No match, output a literal byte */
  21160. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21161. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21162. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21163. s.lookahead--;
  21164. s.strstart++;
  21165. }
  21166. if (bflush) {
  21167. /*** FLUSH_BLOCK(s, 0); ***/
  21168. flush_block_only(s, false);
  21169. if (s.strm.avail_out === 0) {
  21170. return BS_NEED_MORE;
  21171. }
  21172. /***/
  21173. }
  21174. }
  21175. s.insert = 0;
  21176. if (flush === Z_FINISH) {
  21177. /*** FLUSH_BLOCK(s, 1); ***/
  21178. flush_block_only(s, true);
  21179. if (s.strm.avail_out === 0) {
  21180. return BS_FINISH_STARTED;
  21181. }
  21182. /***/
  21183. return BS_FINISH_DONE;
  21184. }
  21185. if (s.last_lit) {
  21186. /*** FLUSH_BLOCK(s, 0); ***/
  21187. flush_block_only(s, false);
  21188. if (s.strm.avail_out === 0) {
  21189. return BS_NEED_MORE;
  21190. }
  21191. /***/
  21192. }
  21193. return BS_BLOCK_DONE;
  21194. }
  21195. /* ===========================================================================
  21196. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21197. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21198. */
  21199. function deflate_huff(s, flush) {
  21200. var bflush; /* set if current block must be flushed */
  21201. for (;;) {
  21202. /* Make sure that we have a literal to write. */
  21203. if (s.lookahead === 0) {
  21204. fill_window(s);
  21205. if (s.lookahead === 0) {
  21206. if (flush === Z_NO_FLUSH) {
  21207. return BS_NEED_MORE;
  21208. }
  21209. break; /* flush the current block */
  21210. }
  21211. }
  21212. /* Output a literal byte */
  21213. s.match_length = 0;
  21214. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21215. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21216. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21217. s.lookahead--;
  21218. s.strstart++;
  21219. if (bflush) {
  21220. /*** FLUSH_BLOCK(s, 0); ***/
  21221. flush_block_only(s, false);
  21222. if (s.strm.avail_out === 0) {
  21223. return BS_NEED_MORE;
  21224. }
  21225. /***/
  21226. }
  21227. }
  21228. s.insert = 0;
  21229. if (flush === Z_FINISH) {
  21230. /*** FLUSH_BLOCK(s, 1); ***/
  21231. flush_block_only(s, true);
  21232. if (s.strm.avail_out === 0) {
  21233. return BS_FINISH_STARTED;
  21234. }
  21235. /***/
  21236. return BS_FINISH_DONE;
  21237. }
  21238. if (s.last_lit) {
  21239. /*** FLUSH_BLOCK(s, 0); ***/
  21240. flush_block_only(s, false);
  21241. if (s.strm.avail_out === 0) {
  21242. return BS_NEED_MORE;
  21243. }
  21244. /***/
  21245. }
  21246. return BS_BLOCK_DONE;
  21247. }
  21248. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21249. * the desired pack level (0..9). The values given below have been tuned to
  21250. * exclude worst case performance for pathological files. Better values may be
  21251. * found for specific files.
  21252. */
  21253. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  21254. this.good_length = good_length;
  21255. this.max_lazy = max_lazy;
  21256. this.nice_length = nice_length;
  21257. this.max_chain = max_chain;
  21258. this.func = func;
  21259. }
  21260. var configuration_table;
  21261. configuration_table = [
  21262. /* good lazy nice chain */
  21263. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21264. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21265. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21266. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21267. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21268. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21269. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21270. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21271. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21272. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21273. ];
  21274. /* ===========================================================================
  21275. * Initialize the "longest match" routines for a new zlib stream
  21276. */
  21277. function lm_init(s) {
  21278. s.window_size = 2 * s.w_size;
  21279. /*** CLEAR_HASH(s); ***/
  21280. zero(s.head); // Fill with NIL (= 0);
  21281. /* Set the default configuration parameters:
  21282. */
  21283. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21284. s.good_match = configuration_table[s.level].good_length;
  21285. s.nice_match = configuration_table[s.level].nice_length;
  21286. s.max_chain_length = configuration_table[s.level].max_chain;
  21287. s.strstart = 0;
  21288. s.block_start = 0;
  21289. s.lookahead = 0;
  21290. s.insert = 0;
  21291. s.match_length = s.prev_length = MIN_MATCH - 1;
  21292. s.match_available = 0;
  21293. s.ins_h = 0;
  21294. }
  21295. function DeflateState() {
  21296. this.strm = null; /* pointer back to this zlib stream */
  21297. this.status = 0; /* as the name implies */
  21298. this.pending_buf = null; /* output still pending */
  21299. this.pending_buf_size = 0; /* size of pending_buf */
  21300. this.pending_out = 0; /* next pending byte to output to the stream */
  21301. this.pending = 0; /* nb of bytes in the pending buffer */
  21302. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21303. this.gzhead = null; /* gzip header information to write */
  21304. this.gzindex = 0; /* where in extra, name, or comment */
  21305. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21306. this.last_flush = -1; /* value of flush param for previous deflate call */
  21307. this.w_size = 0; /* LZ77 window size (32K by default) */
  21308. this.w_bits = 0; /* log2(w_size) (8..16) */
  21309. this.w_mask = 0; /* w_size - 1 */
  21310. this.window = null;
  21311. /* Sliding window. Input bytes are read into the second half of the window,
  21312. * and move to the first half later to keep a dictionary of at least wSize
  21313. * bytes. With this organization, matches are limited to a distance of
  21314. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21315. * performed with a length multiple of the block size.
  21316. */
  21317. this.window_size = 0;
  21318. /* Actual size of window: 2*wSize, except when the user input buffer
  21319. * is directly used as sliding window.
  21320. */
  21321. this.prev = null;
  21322. /* Link to older string with same hash index. To limit the size of this
  21323. * array to 64K, this link is maintained only for the last 32K strings.
  21324. * An index in this array is thus a window index modulo 32K.
  21325. */
  21326. this.head = null; /* Heads of the hash chains or NIL. */
  21327. this.ins_h = 0; /* hash index of string to be inserted */
  21328. this.hash_size = 0; /* number of elements in hash table */
  21329. this.hash_bits = 0; /* log2(hash_size) */
  21330. this.hash_mask = 0; /* hash_size-1 */
  21331. this.hash_shift = 0;
  21332. /* Number of bits by which ins_h must be shifted at each input
  21333. * step. It must be such that after MIN_MATCH steps, the oldest
  21334. * byte no longer takes part in the hash key, that is:
  21335. * hash_shift * MIN_MATCH >= hash_bits
  21336. */
  21337. this.block_start = 0;
  21338. /* Window position at the beginning of the current output block. Gets
  21339. * negative when the window is moved backwards.
  21340. */
  21341. this.match_length = 0; /* length of best match */
  21342. this.prev_match = 0; /* previous match */
  21343. this.match_available = 0; /* set if previous match exists */
  21344. this.strstart = 0; /* start of string to insert */
  21345. this.match_start = 0; /* start of matching string */
  21346. this.lookahead = 0; /* number of valid bytes ahead in window */
  21347. this.prev_length = 0;
  21348. /* Length of the best match at previous step. Matches not greater than this
  21349. * are discarded. This is used in the lazy match evaluation.
  21350. */
  21351. this.max_chain_length = 0;
  21352. /* To speed up deflation, hash chains are never searched beyond this
  21353. * length. A higher limit improves compression ratio but degrades the
  21354. * speed.
  21355. */
  21356. this.max_lazy_match = 0;
  21357. /* Attempt to find a better match only when the current match is strictly
  21358. * smaller than this value. This mechanism is used only for compression
  21359. * levels >= 4.
  21360. */
  21361. // That's alias to max_lazy_match, don't use directly
  21362. //this.max_insert_length = 0;
  21363. /* Insert new strings in the hash table only if the match length is not
  21364. * greater than this length. This saves time but degrades compression.
  21365. * max_insert_length is used only for compression levels <= 3.
  21366. */
  21367. this.level = 0; /* compression level (1..9) */
  21368. this.strategy = 0; /* favor or force Huffman coding*/
  21369. this.good_match = 0;
  21370. /* Use a faster search when the previous match is longer than this */
  21371. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21372. /* used by trees.c: */
  21373. /* Didn't use ct_data typedef below to suppress compiler warning */
  21374. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21375. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21376. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21377. // Use flat array of DOUBLE size, with interleaved fata,
  21378. // because JS does not support effective
  21379. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21380. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  21381. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  21382. zero(this.dyn_ltree);
  21383. zero(this.dyn_dtree);
  21384. zero(this.bl_tree);
  21385. this.l_desc = null; /* desc. for literal tree */
  21386. this.d_desc = null; /* desc. for distance tree */
  21387. this.bl_desc = null; /* desc. for bit length tree */
  21388. //ush bl_count[MAX_BITS+1];
  21389. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  21390. /* number of codes at each bit length for an optimal tree */
  21391. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21392. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  21393. zero(this.heap);
  21394. this.heap_len = 0; /* number of elements in the heap */
  21395. this.heap_max = 0; /* element of largest frequency */
  21396. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21397. * The same heap array is used to build all trees.
  21398. */
  21399. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  21400. zero(this.depth);
  21401. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21402. */
  21403. this.l_buf = 0; /* buffer index for literals or lengths */
  21404. this.lit_bufsize = 0;
  21405. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21406. * limiting lit_bufsize to 64K:
  21407. * - frequencies can be kept in 16 bit counters
  21408. * - if compression is not successful for the first block, all input
  21409. * data is still in the window so we can still emit a stored block even
  21410. * when input comes from standard input. (This can also be done for
  21411. * all blocks if lit_bufsize is not greater than 32K.)
  21412. * - if compression is not successful for a file smaller than 64K, we can
  21413. * even emit a stored file instead of a stored block (saving 5 bytes).
  21414. * This is applicable only for zip (not gzip or zlib).
  21415. * - creating new Huffman trees less frequently may not provide fast
  21416. * adaptation to changes in the input data statistics. (Take for
  21417. * example a binary file with poorly compressible code followed by
  21418. * a highly compressible string table.) Smaller buffer sizes give
  21419. * fast adaptation but have of course the overhead of transmitting
  21420. * trees more frequently.
  21421. * - I can't count above 4
  21422. */
  21423. this.last_lit = 0; /* running index in l_buf */
  21424. this.d_buf = 0;
  21425. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21426. * the same number of elements. To use different lengths, an extra flag
  21427. * array would be necessary.
  21428. */
  21429. this.opt_len = 0; /* bit length of current block with optimal trees */
  21430. this.static_len = 0; /* bit length of current block with static trees */
  21431. this.matches = 0; /* number of string matches in current block */
  21432. this.insert = 0; /* bytes at end of window left to insert */
  21433. this.bi_buf = 0;
  21434. /* Output buffer. bits are inserted starting at the bottom (least
  21435. * significant bits).
  21436. */
  21437. this.bi_valid = 0;
  21438. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21439. * are always zero.
  21440. */
  21441. // Used for window memory init. We safely ignore it for JS. That makes
  21442. // sense only for pointers and memory check tools.
  21443. //this.high_water = 0;
  21444. /* High water mark offset in window for initialized bytes -- bytes above
  21445. * this are set to zero in order to avoid memory check warnings when
  21446. * longest match routines access bytes past the input. This is then
  21447. * updated to the new high water mark.
  21448. */
  21449. }
  21450. function deflateResetKeep(strm) {
  21451. var s;
  21452. if (!strm || !strm.state) {
  21453. return err(strm, Z_STREAM_ERROR);
  21454. }
  21455. strm.total_in = strm.total_out = 0;
  21456. strm.data_type = Z_UNKNOWN;
  21457. s = strm.state;
  21458. s.pending = 0;
  21459. s.pending_out = 0;
  21460. if (s.wrap < 0) {
  21461. s.wrap = -s.wrap;
  21462. /* was made negative by deflate(..., Z_FINISH); */
  21463. }
  21464. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21465. strm.adler = (s.wrap === 2) ?
  21466. 0 // crc32(0, Z_NULL, 0)
  21467. :
  21468. 1; // adler32(0, Z_NULL, 0)
  21469. s.last_flush = Z_NO_FLUSH;
  21470. trees._tr_init(s);
  21471. return Z_OK;
  21472. }
  21473. function deflateReset(strm) {
  21474. var ret = deflateResetKeep(strm);
  21475. if (ret === Z_OK) {
  21476. lm_init(strm.state);
  21477. }
  21478. return ret;
  21479. }
  21480. function deflateSetHeader(strm, head) {
  21481. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21482. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21483. strm.state.gzhead = head;
  21484. return Z_OK;
  21485. }
  21486. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21487. if (!strm) { // === Z_NULL
  21488. return Z_STREAM_ERROR;
  21489. }
  21490. var wrap = 1;
  21491. if (level === Z_DEFAULT_COMPRESSION) {
  21492. level = 6;
  21493. }
  21494. if (windowBits < 0) { /* suppress zlib wrapper */
  21495. wrap = 0;
  21496. windowBits = -windowBits;
  21497. }
  21498. else if (windowBits > 15) {
  21499. wrap = 2; /* write gzip wrapper instead */
  21500. windowBits -= 16;
  21501. }
  21502. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21503. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21504. strategy < 0 || strategy > Z_FIXED) {
  21505. return err(strm, Z_STREAM_ERROR);
  21506. }
  21507. if (windowBits === 8) {
  21508. windowBits = 9;
  21509. }
  21510. /* until 256-byte window bug fixed */
  21511. var s = new DeflateState();
  21512. strm.state = s;
  21513. s.strm = strm;
  21514. s.wrap = wrap;
  21515. s.gzhead = null;
  21516. s.w_bits = windowBits;
  21517. s.w_size = 1 << s.w_bits;
  21518. s.w_mask = s.w_size - 1;
  21519. s.hash_bits = memLevel + 7;
  21520. s.hash_size = 1 << s.hash_bits;
  21521. s.hash_mask = s.hash_size - 1;
  21522. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21523. s.window = new utils.Buf8(s.w_size * 2);
  21524. s.head = new utils.Buf16(s.hash_size);
  21525. s.prev = new utils.Buf16(s.w_size);
  21526. // Don't need mem init magic for JS.
  21527. //s.high_water = 0; /* nothing written to s->window yet */
  21528. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21529. s.pending_buf_size = s.lit_bufsize * 4;
  21530. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  21531. //s->pending_buf = (uchf *) overlay;
  21532. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21533. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  21534. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  21535. s.d_buf = 1 * s.lit_bufsize;
  21536. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  21537. s.l_buf = (1 + 2) * s.lit_bufsize;
  21538. s.level = level;
  21539. s.strategy = strategy;
  21540. s.method = method;
  21541. return deflateReset(strm);
  21542. }
  21543. function deflateInit(strm, level) {
  21544. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21545. }
  21546. function deflate(strm, flush) {
  21547. var old_flush, s;
  21548. var beg, val; // for gzip header write only
  21549. if (!strm || !strm.state ||
  21550. flush > Z_BLOCK || flush < 0) {
  21551. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21552. }
  21553. s = strm.state;
  21554. if (!strm.output ||
  21555. (!strm.input && strm.avail_in !== 0) ||
  21556. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21557. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21558. }
  21559. s.strm = strm; /* just in case */
  21560. old_flush = s.last_flush;
  21561. s.last_flush = flush;
  21562. /* Write the header */
  21563. if (s.status === INIT_STATE) {
  21564. if (s.wrap === 2) { // GZIP header
  21565. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21566. put_byte(s, 31);
  21567. put_byte(s, 139);
  21568. put_byte(s, 8);
  21569. if (!s.gzhead) { // s->gzhead == Z_NULL
  21570. put_byte(s, 0);
  21571. put_byte(s, 0);
  21572. put_byte(s, 0);
  21573. put_byte(s, 0);
  21574. put_byte(s, 0);
  21575. put_byte(s, s.level === 9 ? 2 :
  21576. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21577. 4 : 0));
  21578. put_byte(s, OS_CODE);
  21579. s.status = BUSY_STATE;
  21580. }
  21581. else {
  21582. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21583. (s.gzhead.hcrc ? 2 : 0) +
  21584. (!s.gzhead.extra ? 0 : 4) +
  21585. (!s.gzhead.name ? 0 : 8) +
  21586. (!s.gzhead.comment ? 0 : 16)
  21587. );
  21588. put_byte(s, s.gzhead.time & 0xff);
  21589. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21590. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21591. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21592. put_byte(s, s.level === 9 ? 2 :
  21593. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21594. 4 : 0));
  21595. put_byte(s, s.gzhead.os & 0xff);
  21596. if (s.gzhead.extra && s.gzhead.extra.length) {
  21597. put_byte(s, s.gzhead.extra.length & 0xff);
  21598. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21599. }
  21600. if (s.gzhead.hcrc) {
  21601. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21602. }
  21603. s.gzindex = 0;
  21604. s.status = EXTRA_STATE;
  21605. }
  21606. }
  21607. else // DEFLATE header
  21608. {
  21609. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21610. var level_flags = -1;
  21611. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21612. level_flags = 0;
  21613. } else if (s.level < 6) {
  21614. level_flags = 1;
  21615. } else if (s.level === 6) {
  21616. level_flags = 2;
  21617. } else {
  21618. level_flags = 3;
  21619. }
  21620. header |= (level_flags << 6);
  21621. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21622. header += 31 - (header % 31);
  21623. s.status = BUSY_STATE;
  21624. putShortMSB(s, header);
  21625. /* Save the adler32 of the preset dictionary: */
  21626. if (s.strstart !== 0) {
  21627. putShortMSB(s, strm.adler >>> 16);
  21628. putShortMSB(s, strm.adler & 0xffff);
  21629. }
  21630. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21631. }
  21632. }
  21633. //#ifdef GZIP
  21634. if (s.status === EXTRA_STATE) {
  21635. if (s.gzhead.extra/* != Z_NULL*/) {
  21636. beg = s.pending; /* start of bytes to update crc */
  21637. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21638. if (s.pending === s.pending_buf_size) {
  21639. if (s.gzhead.hcrc && s.pending > beg) {
  21640. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21641. }
  21642. flush_pending(strm);
  21643. beg = s.pending;
  21644. if (s.pending === s.pending_buf_size) {
  21645. break;
  21646. }
  21647. }
  21648. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21649. s.gzindex++;
  21650. }
  21651. if (s.gzhead.hcrc && s.pending > beg) {
  21652. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21653. }
  21654. if (s.gzindex === s.gzhead.extra.length) {
  21655. s.gzindex = 0;
  21656. s.status = NAME_STATE;
  21657. }
  21658. }
  21659. else {
  21660. s.status = NAME_STATE;
  21661. }
  21662. }
  21663. if (s.status === NAME_STATE) {
  21664. if (s.gzhead.name/* != Z_NULL*/) {
  21665. beg = s.pending; /* start of bytes to update crc */
  21666. //int val;
  21667. do {
  21668. if (s.pending === s.pending_buf_size) {
  21669. if (s.gzhead.hcrc && s.pending > beg) {
  21670. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21671. }
  21672. flush_pending(strm);
  21673. beg = s.pending;
  21674. if (s.pending === s.pending_buf_size) {
  21675. val = 1;
  21676. break;
  21677. }
  21678. }
  21679. // JS specific: little magic to add zero terminator to end of string
  21680. if (s.gzindex < s.gzhead.name.length) {
  21681. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21682. } else {
  21683. val = 0;
  21684. }
  21685. put_byte(s, val);
  21686. } while (val !== 0);
  21687. if (s.gzhead.hcrc && s.pending > beg) {
  21688. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21689. }
  21690. if (val === 0) {
  21691. s.gzindex = 0;
  21692. s.status = COMMENT_STATE;
  21693. }
  21694. }
  21695. else {
  21696. s.status = COMMENT_STATE;
  21697. }
  21698. }
  21699. if (s.status === COMMENT_STATE) {
  21700. if (s.gzhead.comment/* != Z_NULL*/) {
  21701. beg = s.pending; /* start of bytes to update crc */
  21702. //int val;
  21703. do {
  21704. if (s.pending === s.pending_buf_size) {
  21705. if (s.gzhead.hcrc && s.pending > beg) {
  21706. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21707. }
  21708. flush_pending(strm);
  21709. beg = s.pending;
  21710. if (s.pending === s.pending_buf_size) {
  21711. val = 1;
  21712. break;
  21713. }
  21714. }
  21715. // JS specific: little magic to add zero terminator to end of string
  21716. if (s.gzindex < s.gzhead.comment.length) {
  21717. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21718. } else {
  21719. val = 0;
  21720. }
  21721. put_byte(s, val);
  21722. } while (val !== 0);
  21723. if (s.gzhead.hcrc && s.pending > beg) {
  21724. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21725. }
  21726. if (val === 0) {
  21727. s.status = HCRC_STATE;
  21728. }
  21729. }
  21730. else {
  21731. s.status = HCRC_STATE;
  21732. }
  21733. }
  21734. if (s.status === HCRC_STATE) {
  21735. if (s.gzhead.hcrc) {
  21736. if (s.pending + 2 > s.pending_buf_size) {
  21737. flush_pending(strm);
  21738. }
  21739. if (s.pending + 2 <= s.pending_buf_size) {
  21740. put_byte(s, strm.adler & 0xff);
  21741. put_byte(s, (strm.adler >> 8) & 0xff);
  21742. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21743. s.status = BUSY_STATE;
  21744. }
  21745. }
  21746. else {
  21747. s.status = BUSY_STATE;
  21748. }
  21749. }
  21750. //#endif
  21751. /* Flush as much pending output as possible */
  21752. if (s.pending !== 0) {
  21753. flush_pending(strm);
  21754. if (strm.avail_out === 0) {
  21755. /* Since avail_out is 0, deflate will be called again with
  21756. * more output space, but possibly with both pending and
  21757. * avail_in equal to zero. There won't be anything to do,
  21758. * but this is not an error situation so make sure we
  21759. * return OK instead of BUF_ERROR at next call of deflate:
  21760. */
  21761. s.last_flush = -1;
  21762. return Z_OK;
  21763. }
  21764. /* Make sure there is something to do and avoid duplicate consecutive
  21765. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21766. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21767. */
  21768. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21769. flush !== Z_FINISH) {
  21770. return err(strm, Z_BUF_ERROR);
  21771. }
  21772. /* User must not provide more input after the first FINISH: */
  21773. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21774. return err(strm, Z_BUF_ERROR);
  21775. }
  21776. /* Start a new block or continue the current one.
  21777. */
  21778. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21779. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21780. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21781. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21782. configuration_table[s.level].func(s, flush));
  21783. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21784. s.status = FINISH_STATE;
  21785. }
  21786. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21787. if (strm.avail_out === 0) {
  21788. s.last_flush = -1;
  21789. /* avoid BUF_ERROR next call, see above */
  21790. }
  21791. return Z_OK;
  21792. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21793. * of deflate should use the same flush parameter to make sure
  21794. * that the flush is complete. So we don't have to output an
  21795. * empty block here, this will be done at next call. This also
  21796. * ensures that for a very small output buffer, we emit at most
  21797. * one empty block.
  21798. */
  21799. }
  21800. if (bstate === BS_BLOCK_DONE) {
  21801. if (flush === Z_PARTIAL_FLUSH) {
  21802. trees._tr_align(s);
  21803. }
  21804. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21805. trees._tr_stored_block(s, 0, 0, false);
  21806. /* For a full flush, this empty block will be recognized
  21807. * as a special marker by inflate_sync().
  21808. */
  21809. if (flush === Z_FULL_FLUSH) {
  21810. /*** CLEAR_HASH(s); ***/ /* forget history */
  21811. zero(s.head); // Fill with NIL (= 0);
  21812. if (s.lookahead === 0) {
  21813. s.strstart = 0;
  21814. s.block_start = 0;
  21815. s.insert = 0;
  21816. }
  21817. }
  21818. }
  21819. flush_pending(strm);
  21820. if (strm.avail_out === 0) {
  21821. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21822. return Z_OK;
  21823. }
  21824. }
  21825. }
  21826. //Assert(strm->avail_out > 0, "bug2");
  21827. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21828. if (flush !== Z_FINISH) { return Z_OK; }
  21829. if (s.wrap <= 0) { return Z_STREAM_END; }
  21830. /* Write the trailer */
  21831. if (s.wrap === 2) {
  21832. put_byte(s, strm.adler & 0xff);
  21833. put_byte(s, (strm.adler >> 8) & 0xff);
  21834. put_byte(s, (strm.adler >> 16) & 0xff);
  21835. put_byte(s, (strm.adler >> 24) & 0xff);
  21836. put_byte(s, strm.total_in & 0xff);
  21837. put_byte(s, (strm.total_in >> 8) & 0xff);
  21838. put_byte(s, (strm.total_in >> 16) & 0xff);
  21839. put_byte(s, (strm.total_in >> 24) & 0xff);
  21840. }
  21841. else
  21842. {
  21843. putShortMSB(s, strm.adler >>> 16);
  21844. putShortMSB(s, strm.adler & 0xffff);
  21845. }
  21846. flush_pending(strm);
  21847. /* If avail_out is zero, the application will call deflate again
  21848. * to flush the rest.
  21849. */
  21850. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21851. /* write the trailer only once! */
  21852. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21853. }
  21854. function deflateEnd(strm) {
  21855. var status;
  21856. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21857. return Z_STREAM_ERROR;
  21858. }
  21859. status = strm.state.status;
  21860. if (status !== INIT_STATE &&
  21861. status !== EXTRA_STATE &&
  21862. status !== NAME_STATE &&
  21863. status !== COMMENT_STATE &&
  21864. status !== HCRC_STATE &&
  21865. status !== BUSY_STATE &&
  21866. status !== FINISH_STATE
  21867. ) {
  21868. return err(strm, Z_STREAM_ERROR);
  21869. }
  21870. strm.state = null;
  21871. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21872. }
  21873. /* =========================================================================
  21874. * Initializes the compression dictionary from the given byte
  21875. * sequence without producing any compressed output.
  21876. */
  21877. function deflateSetDictionary(strm, dictionary) {
  21878. var dictLength = dictionary.length;
  21879. var s;
  21880. var str, n;
  21881. var wrap;
  21882. var avail;
  21883. var next;
  21884. var input;
  21885. var tmpDict;
  21886. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21887. return Z_STREAM_ERROR;
  21888. }
  21889. s = strm.state;
  21890. wrap = s.wrap;
  21891. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  21892. return Z_STREAM_ERROR;
  21893. }
  21894. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  21895. if (wrap === 1) {
  21896. /* adler32(strm->adler, dictionary, dictLength); */
  21897. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  21898. }
  21899. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  21900. /* if dictionary would fill window, just replace the history */
  21901. if (dictLength >= s.w_size) {
  21902. if (wrap === 0) { /* already empty otherwise */
  21903. /*** CLEAR_HASH(s); ***/
  21904. zero(s.head); // Fill with NIL (= 0);
  21905. s.strstart = 0;
  21906. s.block_start = 0;
  21907. s.insert = 0;
  21908. }
  21909. /* use the tail */
  21910. // dictionary = dictionary.slice(dictLength - s.w_size);
  21911. tmpDict = new utils.Buf8(s.w_size);
  21912. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  21913. dictionary = tmpDict;
  21914. dictLength = s.w_size;
  21915. }
  21916. /* insert dictionary into window and hash */
  21917. avail = strm.avail_in;
  21918. next = strm.next_in;
  21919. input = strm.input;
  21920. strm.avail_in = dictLength;
  21921. strm.next_in = 0;
  21922. strm.input = dictionary;
  21923. fill_window(s);
  21924. while (s.lookahead >= MIN_MATCH) {
  21925. str = s.strstart;
  21926. n = s.lookahead - (MIN_MATCH - 1);
  21927. do {
  21928. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21929. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  21930. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21931. s.head[s.ins_h] = str;
  21932. str++;
  21933. } while (--n);
  21934. s.strstart = str;
  21935. s.lookahead = MIN_MATCH - 1;
  21936. fill_window(s);
  21937. }
  21938. s.strstart += s.lookahead;
  21939. s.block_start = s.strstart;
  21940. s.insert = s.lookahead;
  21941. s.lookahead = 0;
  21942. s.match_length = s.prev_length = MIN_MATCH - 1;
  21943. s.match_available = 0;
  21944. strm.next_in = next;
  21945. strm.input = input;
  21946. strm.avail_in = avail;
  21947. s.wrap = wrap;
  21948. return Z_OK;
  21949. }
  21950. exports.deflateInit = deflateInit;
  21951. exports.deflateInit2 = deflateInit2;
  21952. exports.deflateReset = deflateReset;
  21953. exports.deflateResetKeep = deflateResetKeep;
  21954. exports.deflateSetHeader = deflateSetHeader;
  21955. exports.deflate = deflate;
  21956. exports.deflateEnd = deflateEnd;
  21957. exports.deflateSetDictionary = deflateSetDictionary;
  21958. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21959. /* Not implemented
  21960. exports.deflateBound = deflateBound;
  21961. exports.deflateCopy = deflateCopy;
  21962. exports.deflateParams = deflateParams;
  21963. exports.deflatePending = deflatePending;
  21964. exports.deflatePrime = deflatePrime;
  21965. exports.deflateTune = deflateTune;
  21966. */
  21967. },{"../utils/common":268,"./adler32":270,"./crc32":272,"./messages":278,"./trees":279}],274:[function(require,module,exports){
  21968. 'use strict';
  21969. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  21970. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  21971. //
  21972. // This software is provided 'as-is', without any express or implied
  21973. // warranty. In no event will the authors be held liable for any damages
  21974. // arising from the use of this software.
  21975. //
  21976. // Permission is granted to anyone to use this software for any purpose,
  21977. // including commercial applications, and to alter it and redistribute it
  21978. // freely, subject to the following restrictions:
  21979. //
  21980. // 1. The origin of this software must not be misrepresented; you must not
  21981. // claim that you wrote the original software. If you use this software
  21982. // in a product, an acknowledgment in the product documentation would be
  21983. // appreciated but is not required.
  21984. // 2. Altered source versions must be plainly marked as such, and must not be
  21985. // misrepresented as being the original software.
  21986. // 3. This notice may not be removed or altered from any source distribution.
  21987. function GZheader() {
  21988. /* true if compressed data believed to be text */
  21989. this.text = 0;
  21990. /* modification time */
  21991. this.time = 0;
  21992. /* extra flags (not used when writing a gzip file) */
  21993. this.xflags = 0;
  21994. /* operating system */
  21995. this.os = 0;
  21996. /* pointer to extra field or Z_NULL if none */
  21997. this.extra = null;
  21998. /* extra field length (valid if extra != Z_NULL) */
  21999. this.extra_len = 0; // Actually, we don't need it in JS,
  22000. // but leave for few code modifications
  22001. //
  22002. // Setup limits is not necessary because in js we should not preallocate memory
  22003. // for inflate use constant limit in 65536 bytes
  22004. //
  22005. /* space at extra (only when reading header) */
  22006. // this.extra_max = 0;
  22007. /* pointer to zero-terminated file name or Z_NULL */
  22008. this.name = '';
  22009. /* space at name (only when reading header) */
  22010. // this.name_max = 0;
  22011. /* pointer to zero-terminated comment or Z_NULL */
  22012. this.comment = '';
  22013. /* space at comment (only when reading header) */
  22014. // this.comm_max = 0;
  22015. /* true if there was or will be a header crc */
  22016. this.hcrc = 0;
  22017. /* true when done reading gzip header (not used when writing a gzip file) */
  22018. this.done = false;
  22019. }
  22020. module.exports = GZheader;
  22021. },{}],275:[function(require,module,exports){
  22022. arguments[4][40][0].apply(exports,arguments)
  22023. },{"dup":40}],276:[function(require,module,exports){
  22024. arguments[4][41][0].apply(exports,arguments)
  22025. },{"../utils/common":268,"./adler32":270,"./crc32":272,"./inffast":275,"./inftrees":277,"dup":41}],277:[function(require,module,exports){
  22026. arguments[4][42][0].apply(exports,arguments)
  22027. },{"../utils/common":268,"dup":42}],278:[function(require,module,exports){
  22028. arguments[4][43][0].apply(exports,arguments)
  22029. },{"dup":43}],279:[function(require,module,exports){
  22030. 'use strict';
  22031. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  22032. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  22033. //
  22034. // This software is provided 'as-is', without any express or implied
  22035. // warranty. In no event will the authors be held liable for any damages
  22036. // arising from the use of this software.
  22037. //
  22038. // Permission is granted to anyone to use this software for any purpose,
  22039. // including commercial applications, and to alter it and redistribute it
  22040. // freely, subject to the following restrictions:
  22041. //
  22042. // 1. The origin of this software must not be misrepresented; you must not
  22043. // claim that you wrote the original software. If you use this software
  22044. // in a product, an acknowledgment in the product documentation would be
  22045. // appreciated but is not required.
  22046. // 2. Altered source versions must be plainly marked as such, and must not be
  22047. // misrepresented as being the original software.
  22048. // 3. This notice may not be removed or altered from any source distribution.
  22049. var utils = require('../utils/common');
  22050. /* Public constants ==========================================================*/
  22051. /* ===========================================================================*/
  22052. //var Z_FILTERED = 1;
  22053. //var Z_HUFFMAN_ONLY = 2;
  22054. //var Z_RLE = 3;
  22055. var Z_FIXED = 4;
  22056. //var Z_DEFAULT_STRATEGY = 0;
  22057. /* Possible values of the data_type field (though see inflate()) */
  22058. var Z_BINARY = 0;
  22059. var Z_TEXT = 1;
  22060. //var Z_ASCII = 1; // = Z_TEXT
  22061. var Z_UNKNOWN = 2;
  22062. /*============================================================================*/
  22063. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  22064. // From zutil.h
  22065. var STORED_BLOCK = 0;
  22066. var STATIC_TREES = 1;
  22067. var DYN_TREES = 2;
  22068. /* The three kinds of block type */
  22069. var MIN_MATCH = 3;
  22070. var MAX_MATCH = 258;
  22071. /* The minimum and maximum match lengths */
  22072. // From deflate.h
  22073. /* ===========================================================================
  22074. * Internal compression state.
  22075. */
  22076. var LENGTH_CODES = 29;
  22077. /* number of length codes, not counting the special END_BLOCK code */
  22078. var LITERALS = 256;
  22079. /* number of literal bytes 0..255 */
  22080. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  22081. /* number of Literal or Length codes, including the END_BLOCK code */
  22082. var D_CODES = 30;
  22083. /* number of distance codes */
  22084. var BL_CODES = 19;
  22085. /* number of codes used to transfer the bit lengths */
  22086. var HEAP_SIZE = 2 * L_CODES + 1;
  22087. /* maximum heap size */
  22088. var MAX_BITS = 15;
  22089. /* All codes must not exceed MAX_BITS bits */
  22090. var Buf_size = 16;
  22091. /* size of bit buffer in bi_buf */
  22092. /* ===========================================================================
  22093. * Constants
  22094. */
  22095. var MAX_BL_BITS = 7;
  22096. /* Bit length codes must not exceed MAX_BL_BITS bits */
  22097. var END_BLOCK = 256;
  22098. /* end of block literal code */
  22099. var REP_3_6 = 16;
  22100. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  22101. var REPZ_3_10 = 17;
  22102. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  22103. var REPZ_11_138 = 18;
  22104. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  22105. /* eslint-disable comma-spacing,array-bracket-spacing */
  22106. var extra_lbits = /* extra bits for each length code */
  22107. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  22108. var extra_dbits = /* extra bits for each distance code */
  22109. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  22110. var extra_blbits = /* extra bits for each bit length code */
  22111. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  22112. var bl_order =
  22113. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  22114. /* eslint-enable comma-spacing,array-bracket-spacing */
  22115. /* The lengths of the bit length codes are sent in order of decreasing
  22116. * probability, to avoid transmitting the lengths for unused bit length codes.
  22117. */
  22118. /* ===========================================================================
  22119. * Local data. These are initialized only once.
  22120. */
  22121. // We pre-fill arrays with 0 to avoid uninitialized gaps
  22122. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  22123. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  22124. var static_ltree = new Array((L_CODES + 2) * 2);
  22125. zero(static_ltree);
  22126. /* The static literal tree. Since the bit lengths are imposed, there is no
  22127. * need for the L_CODES extra codes used during heap construction. However
  22128. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  22129. * below).
  22130. */
  22131. var static_dtree = new Array(D_CODES * 2);
  22132. zero(static_dtree);
  22133. /* The static distance tree. (Actually a trivial tree since all codes use
  22134. * 5 bits.)
  22135. */
  22136. var _dist_code = new Array(DIST_CODE_LEN);
  22137. zero(_dist_code);
  22138. /* Distance codes. The first 256 values correspond to the distances
  22139. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  22140. * the 15 bit distances.
  22141. */
  22142. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  22143. zero(_length_code);
  22144. /* length code for each normalized match length (0 == MIN_MATCH) */
  22145. var base_length = new Array(LENGTH_CODES);
  22146. zero(base_length);
  22147. /* First normalized length for each code (0 = MIN_MATCH) */
  22148. var base_dist = new Array(D_CODES);
  22149. zero(base_dist);
  22150. /* First normalized distance for each code (0 = distance of 1) */
  22151. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  22152. this.static_tree = static_tree; /* static tree or NULL */
  22153. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  22154. this.extra_base = extra_base; /* base index for extra_bits */
  22155. this.elems = elems; /* max number of elements in the tree */
  22156. this.max_length = max_length; /* max bit length for the codes */
  22157. // show if `static_tree` has data or dummy - needed for monomorphic objects
  22158. this.has_stree = static_tree && static_tree.length;
  22159. }
  22160. var static_l_desc;
  22161. var static_d_desc;
  22162. var static_bl_desc;
  22163. function TreeDesc(dyn_tree, stat_desc) {
  22164. this.dyn_tree = dyn_tree; /* the dynamic tree */
  22165. this.max_code = 0; /* largest code with non zero frequency */
  22166. this.stat_desc = stat_desc; /* the corresponding static tree */
  22167. }
  22168. function d_code(dist) {
  22169. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  22170. }
  22171. /* ===========================================================================
  22172. * Output a short LSB first on the stream.
  22173. * IN assertion: there is enough room in pendingBuf.
  22174. */
  22175. function put_short(s, w) {
  22176. // put_byte(s, (uch)((w) & 0xff));
  22177. // put_byte(s, (uch)((ush)(w) >> 8));
  22178. s.pending_buf[s.pending++] = (w) & 0xff;
  22179. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  22180. }
  22181. /* ===========================================================================
  22182. * Send a value on a given number of bits.
  22183. * IN assertion: length <= 16 and value fits in length bits.
  22184. */
  22185. function send_bits(s, value, length) {
  22186. if (s.bi_valid > (Buf_size - length)) {
  22187. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22188. put_short(s, s.bi_buf);
  22189. s.bi_buf = value >> (Buf_size - s.bi_valid);
  22190. s.bi_valid += length - Buf_size;
  22191. } else {
  22192. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22193. s.bi_valid += length;
  22194. }
  22195. }
  22196. function send_code(s, c, tree) {
  22197. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  22198. }
  22199. /* ===========================================================================
  22200. * Reverse the first len bits of a code, using straightforward code (a faster
  22201. * method would use a table)
  22202. * IN assertion: 1 <= len <= 15
  22203. */
  22204. function bi_reverse(code, len) {
  22205. var res = 0;
  22206. do {
  22207. res |= code & 1;
  22208. code >>>= 1;
  22209. res <<= 1;
  22210. } while (--len > 0);
  22211. return res >>> 1;
  22212. }
  22213. /* ===========================================================================
  22214. * Flush the bit buffer, keeping at most 7 bits in it.
  22215. */
  22216. function bi_flush(s) {
  22217. if (s.bi_valid === 16) {
  22218. put_short(s, s.bi_buf);
  22219. s.bi_buf = 0;
  22220. s.bi_valid = 0;
  22221. } else if (s.bi_valid >= 8) {
  22222. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  22223. s.bi_buf >>= 8;
  22224. s.bi_valid -= 8;
  22225. }
  22226. }
  22227. /* ===========================================================================
  22228. * Compute the optimal bit lengths for a tree and update the total bit length
  22229. * for the current block.
  22230. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  22231. * above are the tree nodes sorted by increasing frequency.
  22232. * OUT assertions: the field len is set to the optimal bit length, the
  22233. * array bl_count contains the frequencies for each bit length.
  22234. * The length opt_len is updated; static_len is also updated if stree is
  22235. * not null.
  22236. */
  22237. function gen_bitlen(s, desc)
  22238. // deflate_state *s;
  22239. // tree_desc *desc; /* the tree descriptor */
  22240. {
  22241. var tree = desc.dyn_tree;
  22242. var max_code = desc.max_code;
  22243. var stree = desc.stat_desc.static_tree;
  22244. var has_stree = desc.stat_desc.has_stree;
  22245. var extra = desc.stat_desc.extra_bits;
  22246. var base = desc.stat_desc.extra_base;
  22247. var max_length = desc.stat_desc.max_length;
  22248. var h; /* heap index */
  22249. var n, m; /* iterate over the tree elements */
  22250. var bits; /* bit length */
  22251. var xbits; /* extra bits */
  22252. var f; /* frequency */
  22253. var overflow = 0; /* number of elements with bit length too large */
  22254. for (bits = 0; bits <= MAX_BITS; bits++) {
  22255. s.bl_count[bits] = 0;
  22256. }
  22257. /* In a first pass, compute the optimal bit lengths (which may
  22258. * overflow in the case of the bit length tree).
  22259. */
  22260. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  22261. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  22262. n = s.heap[h];
  22263. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  22264. if (bits > max_length) {
  22265. bits = max_length;
  22266. overflow++;
  22267. }
  22268. tree[n * 2 + 1]/*.Len*/ = bits;
  22269. /* We overwrite tree[n].Dad which is no longer needed */
  22270. if (n > max_code) { continue; } /* not a leaf node */
  22271. s.bl_count[bits]++;
  22272. xbits = 0;
  22273. if (n >= base) {
  22274. xbits = extra[n - base];
  22275. }
  22276. f = tree[n * 2]/*.Freq*/;
  22277. s.opt_len += f * (bits + xbits);
  22278. if (has_stree) {
  22279. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  22280. }
  22281. }
  22282. if (overflow === 0) { return; }
  22283. // Trace((stderr,"\nbit length overflow\n"));
  22284. /* This happens for example on obj2 and pic of the Calgary corpus */
  22285. /* Find the first bit length which could increase: */
  22286. do {
  22287. bits = max_length - 1;
  22288. while (s.bl_count[bits] === 0) { bits--; }
  22289. s.bl_count[bits]--; /* move one leaf down the tree */
  22290. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  22291. s.bl_count[max_length]--;
  22292. /* The brother of the overflow item also moves one step up,
  22293. * but this does not affect bl_count[max_length]
  22294. */
  22295. overflow -= 2;
  22296. } while (overflow > 0);
  22297. /* Now recompute all bit lengths, scanning in increasing frequency.
  22298. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  22299. * lengths instead of fixing only the wrong ones. This idea is taken
  22300. * from 'ar' written by Haruhiko Okumura.)
  22301. */
  22302. for (bits = max_length; bits !== 0; bits--) {
  22303. n = s.bl_count[bits];
  22304. while (n !== 0) {
  22305. m = s.heap[--h];
  22306. if (m > max_code) { continue; }
  22307. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  22308. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  22309. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  22310. tree[m * 2 + 1]/*.Len*/ = bits;
  22311. }
  22312. n--;
  22313. }
  22314. }
  22315. }
  22316. /* ===========================================================================
  22317. * Generate the codes for a given tree and bit counts (which need not be
  22318. * optimal).
  22319. * IN assertion: the array bl_count contains the bit length statistics for
  22320. * the given tree and the field len is set for all tree elements.
  22321. * OUT assertion: the field code is set for all tree elements of non
  22322. * zero code length.
  22323. */
  22324. function gen_codes(tree, max_code, bl_count)
  22325. // ct_data *tree; /* the tree to decorate */
  22326. // int max_code; /* largest code with non zero frequency */
  22327. // ushf *bl_count; /* number of codes at each bit length */
  22328. {
  22329. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  22330. var code = 0; /* running code value */
  22331. var bits; /* bit index */
  22332. var n; /* code index */
  22333. /* The distribution counts are first used to generate the code values
  22334. * without bit reversal.
  22335. */
  22336. for (bits = 1; bits <= MAX_BITS; bits++) {
  22337. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  22338. }
  22339. /* Check that the bit counts in bl_count are consistent. The last code
  22340. * must be all ones.
  22341. */
  22342. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  22343. // "inconsistent bit counts");
  22344. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  22345. for (n = 0; n <= max_code; n++) {
  22346. var len = tree[n * 2 + 1]/*.Len*/;
  22347. if (len === 0) { continue; }
  22348. /* Now reverse the bits */
  22349. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  22350. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  22351. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  22352. }
  22353. }
  22354. /* ===========================================================================
  22355. * Initialize the various 'constant' tables.
  22356. */
  22357. function tr_static_init() {
  22358. var n; /* iterates over tree elements */
  22359. var bits; /* bit counter */
  22360. var length; /* length value */
  22361. var code; /* code value */
  22362. var dist; /* distance index */
  22363. var bl_count = new Array(MAX_BITS + 1);
  22364. /* number of codes at each bit length for an optimal tree */
  22365. // do check in _tr_init()
  22366. //if (static_init_done) return;
  22367. /* For some embedded targets, global variables are not initialized: */
  22368. /*#ifdef NO_INIT_GLOBAL_POINTERS
  22369. static_l_desc.static_tree = static_ltree;
  22370. static_l_desc.extra_bits = extra_lbits;
  22371. static_d_desc.static_tree = static_dtree;
  22372. static_d_desc.extra_bits = extra_dbits;
  22373. static_bl_desc.extra_bits = extra_blbits;
  22374. #endif*/
  22375. /* Initialize the mapping length (0..255) -> length code (0..28) */
  22376. length = 0;
  22377. for (code = 0; code < LENGTH_CODES - 1; code++) {
  22378. base_length[code] = length;
  22379. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  22380. _length_code[length++] = code;
  22381. }
  22382. }
  22383. //Assert (length == 256, "tr_static_init: length != 256");
  22384. /* Note that the length 255 (match length 258) can be represented
  22385. * in two different ways: code 284 + 5 bits or code 285, so we
  22386. * overwrite length_code[255] to use the best encoding:
  22387. */
  22388. _length_code[length - 1] = code;
  22389. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  22390. dist = 0;
  22391. for (code = 0; code < 16; code++) {
  22392. base_dist[code] = dist;
  22393. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  22394. _dist_code[dist++] = code;
  22395. }
  22396. }
  22397. //Assert (dist == 256, "tr_static_init: dist != 256");
  22398. dist >>= 7; /* from now on, all distances are divided by 128 */
  22399. for (; code < D_CODES; code++) {
  22400. base_dist[code] = dist << 7;
  22401. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  22402. _dist_code[256 + dist++] = code;
  22403. }
  22404. }
  22405. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  22406. /* Construct the codes of the static literal tree */
  22407. for (bits = 0; bits <= MAX_BITS; bits++) {
  22408. bl_count[bits] = 0;
  22409. }
  22410. n = 0;
  22411. while (n <= 143) {
  22412. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  22413. n++;
  22414. bl_count[8]++;
  22415. }
  22416. while (n <= 255) {
  22417. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  22418. n++;
  22419. bl_count[9]++;
  22420. }
  22421. while (n <= 279) {
  22422. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  22423. n++;
  22424. bl_count[7]++;
  22425. }
  22426. while (n <= 287) {
  22427. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  22428. n++;
  22429. bl_count[8]++;
  22430. }
  22431. /* Codes 286 and 287 do not exist, but we must include them in the
  22432. * tree construction to get a canonical Huffman tree (longest code
  22433. * all ones)
  22434. */
  22435. gen_codes(static_ltree, L_CODES + 1, bl_count);
  22436. /* The static distance tree is trivial: */
  22437. for (n = 0; n < D_CODES; n++) {
  22438. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  22439. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  22440. }
  22441. // Now data ready and we can init static trees
  22442. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  22443. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22444. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22445. //static_init_done = true;
  22446. }
  22447. /* ===========================================================================
  22448. * Initialize a new block.
  22449. */
  22450. function init_block(s) {
  22451. var n; /* iterates over tree elements */
  22452. /* Initialize the trees. */
  22453. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  22454. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  22455. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  22456. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  22457. s.opt_len = s.static_len = 0;
  22458. s.last_lit = s.matches = 0;
  22459. }
  22460. /* ===========================================================================
  22461. * Flush the bit buffer and align the output on a byte boundary
  22462. */
  22463. function bi_windup(s)
  22464. {
  22465. if (s.bi_valid > 8) {
  22466. put_short(s, s.bi_buf);
  22467. } else if (s.bi_valid > 0) {
  22468. //put_byte(s, (Byte)s->bi_buf);
  22469. s.pending_buf[s.pending++] = s.bi_buf;
  22470. }
  22471. s.bi_buf = 0;
  22472. s.bi_valid = 0;
  22473. }
  22474. /* ===========================================================================
  22475. * Copy a stored block, storing first the length and its
  22476. * one's complement if requested.
  22477. */
  22478. function copy_block(s, buf, len, header)
  22479. //DeflateState *s;
  22480. //charf *buf; /* the input data */
  22481. //unsigned len; /* its length */
  22482. //int header; /* true if block header must be written */
  22483. {
  22484. bi_windup(s); /* align on byte boundary */
  22485. if (header) {
  22486. put_short(s, len);
  22487. put_short(s, ~len);
  22488. }
  22489. // while (len--) {
  22490. // put_byte(s, *buf++);
  22491. // }
  22492. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22493. s.pending += len;
  22494. }
  22495. /* ===========================================================================
  22496. * Compares to subtrees, using the tree depth as tie breaker when
  22497. * the subtrees have equal frequency. This minimizes the worst case length.
  22498. */
  22499. function smaller(tree, n, m, depth) {
  22500. var _n2 = n * 2;
  22501. var _m2 = m * 2;
  22502. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22503. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22504. }
  22505. /* ===========================================================================
  22506. * Restore the heap property by moving down the tree starting at node k,
  22507. * exchanging a node with the smallest of its two sons if necessary, stopping
  22508. * when the heap property is re-established (each father smaller than its
  22509. * two sons).
  22510. */
  22511. function pqdownheap(s, tree, k)
  22512. // deflate_state *s;
  22513. // ct_data *tree; /* the tree to restore */
  22514. // int k; /* node to move down */
  22515. {
  22516. var v = s.heap[k];
  22517. var j = k << 1; /* left son of k */
  22518. while (j <= s.heap_len) {
  22519. /* Set j to the smallest of the two sons: */
  22520. if (j < s.heap_len &&
  22521. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  22522. j++;
  22523. }
  22524. /* Exit if v is smaller than both sons */
  22525. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22526. /* Exchange v with the smallest son */
  22527. s.heap[k] = s.heap[j];
  22528. k = j;
  22529. /* And continue down the tree, setting j to the left son of k */
  22530. j <<= 1;
  22531. }
  22532. s.heap[k] = v;
  22533. }
  22534. // inlined manually
  22535. // var SMALLEST = 1;
  22536. /* ===========================================================================
  22537. * Send the block data compressed using the given Huffman trees
  22538. */
  22539. function compress_block(s, ltree, dtree)
  22540. // deflate_state *s;
  22541. // const ct_data *ltree; /* literal tree */
  22542. // const ct_data *dtree; /* distance tree */
  22543. {
  22544. var dist; /* distance of matched string */
  22545. var lc; /* match length or unmatched char (if dist == 0) */
  22546. var lx = 0; /* running index in l_buf */
  22547. var code; /* the code to send */
  22548. var extra; /* number of extra bits to send */
  22549. if (s.last_lit !== 0) {
  22550. do {
  22551. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  22552. lc = s.pending_buf[s.l_buf + lx];
  22553. lx++;
  22554. if (dist === 0) {
  22555. send_code(s, lc, ltree); /* send a literal byte */
  22556. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22557. } else {
  22558. /* Here, lc is the match length - MIN_MATCH */
  22559. code = _length_code[lc];
  22560. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  22561. extra = extra_lbits[code];
  22562. if (extra !== 0) {
  22563. lc -= base_length[code];
  22564. send_bits(s, lc, extra); /* send the extra length bits */
  22565. }
  22566. dist--; /* dist is now the match distance - 1 */
  22567. code = d_code(dist);
  22568. //Assert (code < D_CODES, "bad d_code");
  22569. send_code(s, code, dtree); /* send the distance code */
  22570. extra = extra_dbits[code];
  22571. if (extra !== 0) {
  22572. dist -= base_dist[code];
  22573. send_bits(s, dist, extra); /* send the extra distance bits */
  22574. }
  22575. } /* literal or match pair ? */
  22576. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22577. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22578. // "pendingBuf overflow");
  22579. } while (lx < s.last_lit);
  22580. }
  22581. send_code(s, END_BLOCK, ltree);
  22582. }
  22583. /* ===========================================================================
  22584. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22585. * Update the total bit length for the current block.
  22586. * IN assertion: the field freq is set for all tree elements.
  22587. * OUT assertions: the fields len and code are set to the optimal bit length
  22588. * and corresponding code. The length opt_len is updated; static_len is
  22589. * also updated if stree is not null. The field max_code is set.
  22590. */
  22591. function build_tree(s, desc)
  22592. // deflate_state *s;
  22593. // tree_desc *desc; /* the tree descriptor */
  22594. {
  22595. var tree = desc.dyn_tree;
  22596. var stree = desc.stat_desc.static_tree;
  22597. var has_stree = desc.stat_desc.has_stree;
  22598. var elems = desc.stat_desc.elems;
  22599. var n, m; /* iterate over heap elements */
  22600. var max_code = -1; /* largest code with non zero frequency */
  22601. var node; /* new node being created */
  22602. /* Construct the initial heap, with least frequent element in
  22603. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22604. * heap[0] is not used.
  22605. */
  22606. s.heap_len = 0;
  22607. s.heap_max = HEAP_SIZE;
  22608. for (n = 0; n < elems; n++) {
  22609. if (tree[n * 2]/*.Freq*/ !== 0) {
  22610. s.heap[++s.heap_len] = max_code = n;
  22611. s.depth[n] = 0;
  22612. } else {
  22613. tree[n * 2 + 1]/*.Len*/ = 0;
  22614. }
  22615. }
  22616. /* The pkzip format requires that at least one distance code exists,
  22617. * and that at least one bit should be sent even if there is only one
  22618. * possible code. So to avoid special checks later on we force at least
  22619. * two codes of non zero frequency.
  22620. */
  22621. while (s.heap_len < 2) {
  22622. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22623. tree[node * 2]/*.Freq*/ = 1;
  22624. s.depth[node] = 0;
  22625. s.opt_len--;
  22626. if (has_stree) {
  22627. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  22628. }
  22629. /* node is 0 or 1 so it does not have extra bits */
  22630. }
  22631. desc.max_code = max_code;
  22632. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22633. * establish sub-heaps of increasing lengths:
  22634. */
  22635. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22636. /* Construct the Huffman tree by repeatedly combining the least two
  22637. * frequent nodes.
  22638. */
  22639. node = elems; /* next internal node of the tree */
  22640. do {
  22641. //pqremove(s, tree, n); /* n = node of least frequency */
  22642. /*** pqremove ***/
  22643. n = s.heap[1/*SMALLEST*/];
  22644. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22645. pqdownheap(s, tree, 1/*SMALLEST*/);
  22646. /***/
  22647. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22648. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22649. s.heap[--s.heap_max] = m;
  22650. /* Create a new node father of n and m */
  22651. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22652. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22653. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  22654. /* and insert the new node in the heap */
  22655. s.heap[1/*SMALLEST*/] = node++;
  22656. pqdownheap(s, tree, 1/*SMALLEST*/);
  22657. } while (s.heap_len >= 2);
  22658. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22659. /* At this point, the fields freq and dad are set. We can now
  22660. * generate the bit lengths.
  22661. */
  22662. gen_bitlen(s, desc);
  22663. /* The field len is now set, we can generate the bit codes */
  22664. gen_codes(tree, max_code, s.bl_count);
  22665. }
  22666. /* ===========================================================================
  22667. * Scan a literal or distance tree to determine the frequencies of the codes
  22668. * in the bit length tree.
  22669. */
  22670. function scan_tree(s, tree, max_code)
  22671. // deflate_state *s;
  22672. // ct_data *tree; /* the tree to be scanned */
  22673. // int max_code; /* and its largest code of non zero frequency */
  22674. {
  22675. var n; /* iterates over all tree elements */
  22676. var prevlen = -1; /* last emitted length */
  22677. var curlen; /* length of current code */
  22678. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  22679. var count = 0; /* repeat count of the current code */
  22680. var max_count = 7; /* max repeat count */
  22681. var min_count = 4; /* min repeat count */
  22682. if (nextlen === 0) {
  22683. max_count = 138;
  22684. min_count = 3;
  22685. }
  22686. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  22687. for (n = 0; n <= max_code; n++) {
  22688. curlen = nextlen;
  22689. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  22690. if (++count < max_count && curlen === nextlen) {
  22691. continue;
  22692. } else if (count < min_count) {
  22693. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22694. } else if (curlen !== 0) {
  22695. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22696. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  22697. } else if (count <= 10) {
  22698. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  22699. } else {
  22700. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  22701. }
  22702. count = 0;
  22703. prevlen = curlen;
  22704. if (nextlen === 0) {
  22705. max_count = 138;
  22706. min_count = 3;
  22707. } else if (curlen === nextlen) {
  22708. max_count = 6;
  22709. min_count = 3;
  22710. } else {
  22711. max_count = 7;
  22712. min_count = 4;
  22713. }
  22714. }
  22715. }
  22716. /* ===========================================================================
  22717. * Send a literal or distance tree in compressed form, using the codes in
  22718. * bl_tree.
  22719. */
  22720. function send_tree(s, tree, max_code)
  22721. // deflate_state *s;
  22722. // ct_data *tree; /* the tree to be scanned */
  22723. // int max_code; /* and its largest code of non zero frequency */
  22724. {
  22725. var n; /* iterates over all tree elements */
  22726. var prevlen = -1; /* last emitted length */
  22727. var curlen; /* length of current code */
  22728. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  22729. var count = 0; /* repeat count of the current code */
  22730. var max_count = 7; /* max repeat count */
  22731. var min_count = 4; /* min repeat count */
  22732. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22733. if (nextlen === 0) {
  22734. max_count = 138;
  22735. min_count = 3;
  22736. }
  22737. for (n = 0; n <= max_code; n++) {
  22738. curlen = nextlen;
  22739. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  22740. if (++count < max_count && curlen === nextlen) {
  22741. continue;
  22742. } else if (count < min_count) {
  22743. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22744. } else if (curlen !== 0) {
  22745. if (curlen !== prevlen) {
  22746. send_code(s, curlen, s.bl_tree);
  22747. count--;
  22748. }
  22749. //Assert(count >= 3 && count <= 6, " 3_6?");
  22750. send_code(s, REP_3_6, s.bl_tree);
  22751. send_bits(s, count - 3, 2);
  22752. } else if (count <= 10) {
  22753. send_code(s, REPZ_3_10, s.bl_tree);
  22754. send_bits(s, count - 3, 3);
  22755. } else {
  22756. send_code(s, REPZ_11_138, s.bl_tree);
  22757. send_bits(s, count - 11, 7);
  22758. }
  22759. count = 0;
  22760. prevlen = curlen;
  22761. if (nextlen === 0) {
  22762. max_count = 138;
  22763. min_count = 3;
  22764. } else if (curlen === nextlen) {
  22765. max_count = 6;
  22766. min_count = 3;
  22767. } else {
  22768. max_count = 7;
  22769. min_count = 4;
  22770. }
  22771. }
  22772. }
  22773. /* ===========================================================================
  22774. * Construct the Huffman tree for the bit lengths and return the index in
  22775. * bl_order of the last bit length code to send.
  22776. */
  22777. function build_bl_tree(s) {
  22778. var max_blindex; /* index of last bit length code of non zero freq */
  22779. /* Determine the bit length frequencies for literal and distance trees */
  22780. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22781. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22782. /* Build the bit length tree: */
  22783. build_tree(s, s.bl_desc);
  22784. /* opt_len now includes the length of the tree representations, except
  22785. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22786. */
  22787. /* Determine the number of bit length codes to send. The pkzip format
  22788. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22789. * 3 but the actual value used is 4.)
  22790. */
  22791. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  22792. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  22793. break;
  22794. }
  22795. }
  22796. /* Update opt_len to include the bit length tree and counts */
  22797. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  22798. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22799. // s->opt_len, s->static_len));
  22800. return max_blindex;
  22801. }
  22802. /* ===========================================================================
  22803. * Send the header for a block using dynamic Huffman trees: the counts, the
  22804. * lengths of the bit length codes, the literal tree and the distance tree.
  22805. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22806. */
  22807. function send_all_trees(s, lcodes, dcodes, blcodes)
  22808. // deflate_state *s;
  22809. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22810. {
  22811. var rank; /* index in bl_order */
  22812. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22813. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22814. // "too many codes");
  22815. //Tracev((stderr, "\nbl counts: "));
  22816. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  22817. send_bits(s, dcodes - 1, 5);
  22818. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  22819. for (rank = 0; rank < blcodes; rank++) {
  22820. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22821. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  22822. }
  22823. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22824. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  22825. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22826. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  22827. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22828. }
  22829. /* ===========================================================================
  22830. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22831. * - TEXT if the two conditions below are satisfied:
  22832. * a) There are no non-portable control characters belonging to the
  22833. * "black list" (0..6, 14..25, 28..31).
  22834. * b) There is at least one printable character belonging to the
  22835. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22836. * - BINARY otherwise.
  22837. * - The following partially-portable control characters form a
  22838. * "gray list" that is ignored in this detection algorithm:
  22839. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22840. * IN assertion: the fields Freq of dyn_ltree are set.
  22841. */
  22842. function detect_data_type(s) {
  22843. /* black_mask is the bit mask of black-listed bytes
  22844. * set bits 0..6, 14..25, and 28..31
  22845. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22846. */
  22847. var black_mask = 0xf3ffc07f;
  22848. var n;
  22849. /* Check for non-textual ("black-listed") bytes. */
  22850. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22851. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  22852. return Z_BINARY;
  22853. }
  22854. }
  22855. /* Check for textual ("white-listed") bytes. */
  22856. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22857. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22858. return Z_TEXT;
  22859. }
  22860. for (n = 32; n < LITERALS; n++) {
  22861. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22862. return Z_TEXT;
  22863. }
  22864. }
  22865. /* There are no "black-listed" or "white-listed" bytes:
  22866. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22867. */
  22868. return Z_BINARY;
  22869. }
  22870. var static_init_done = false;
  22871. /* ===========================================================================
  22872. * Initialize the tree data structures for a new zlib stream.
  22873. */
  22874. function _tr_init(s)
  22875. {
  22876. if (!static_init_done) {
  22877. tr_static_init();
  22878. static_init_done = true;
  22879. }
  22880. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22881. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22882. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22883. s.bi_buf = 0;
  22884. s.bi_valid = 0;
  22885. /* Initialize the first block of the first file: */
  22886. init_block(s);
  22887. }
  22888. /* ===========================================================================
  22889. * Send a stored block
  22890. */
  22891. function _tr_stored_block(s, buf, stored_len, last)
  22892. //DeflateState *s;
  22893. //charf *buf; /* input block */
  22894. //ulg stored_len; /* length of input block */
  22895. //int last; /* one if this is the last block for a file */
  22896. {
  22897. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  22898. copy_block(s, buf, stored_len, true); /* with header */
  22899. }
  22900. /* ===========================================================================
  22901. * Send one empty static block to give enough lookahead for inflate.
  22902. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22903. */
  22904. function _tr_align(s) {
  22905. send_bits(s, STATIC_TREES << 1, 3);
  22906. send_code(s, END_BLOCK, static_ltree);
  22907. bi_flush(s);
  22908. }
  22909. /* ===========================================================================
  22910. * Determine the best encoding for the current block: dynamic trees, static
  22911. * trees or store, and output the encoded block to the zip file.
  22912. */
  22913. function _tr_flush_block(s, buf, stored_len, last)
  22914. //DeflateState *s;
  22915. //charf *buf; /* input block, or NULL if too old */
  22916. //ulg stored_len; /* length of input block */
  22917. //int last; /* one if this is the last block for a file */
  22918. {
  22919. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22920. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22921. /* Build the Huffman trees unless a stored block is forced */
  22922. if (s.level > 0) {
  22923. /* Check if the file is binary or text */
  22924. if (s.strm.data_type === Z_UNKNOWN) {
  22925. s.strm.data_type = detect_data_type(s);
  22926. }
  22927. /* Construct the literal and distance trees */
  22928. build_tree(s, s.l_desc);
  22929. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22930. // s->static_len));
  22931. build_tree(s, s.d_desc);
  22932. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22933. // s->static_len));
  22934. /* At this point, opt_len and static_len are the total bit lengths of
  22935. * the compressed block data, excluding the tree representations.
  22936. */
  22937. /* Build the bit length tree for the above two trees, and get the index
  22938. * in bl_order of the last bit length code to send.
  22939. */
  22940. max_blindex = build_bl_tree(s);
  22941. /* Determine the best encoding. Compute the block lengths in bytes. */
  22942. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  22943. static_lenb = (s.static_len + 3 + 7) >>> 3;
  22944. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22945. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22946. // s->last_lit));
  22947. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22948. } else {
  22949. // Assert(buf != (char*)0, "lost buf");
  22950. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22951. }
  22952. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  22953. /* 4: two words for the lengths */
  22954. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22955. * Otherwise we can't have processed more than WSIZE input bytes since
  22956. * the last block flush, because compression would have been
  22957. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22958. * transform a block into a stored block.
  22959. */
  22960. _tr_stored_block(s, buf, stored_len, last);
  22961. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22962. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  22963. compress_block(s, static_ltree, static_dtree);
  22964. } else {
  22965. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  22966. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  22967. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22968. }
  22969. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22970. /* The above check is made mod 2^32, for files larger than 512 MB
  22971. * and uLong implemented on 32 bits.
  22972. */
  22973. init_block(s);
  22974. if (last) {
  22975. bi_windup(s);
  22976. }
  22977. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22978. // s->compressed_len-7*last));
  22979. }
  22980. /* ===========================================================================
  22981. * Save the match info and tally the frequency counts. Return true if
  22982. * the current block must be flushed.
  22983. */
  22984. function _tr_tally(s, dist, lc)
  22985. // deflate_state *s;
  22986. // unsigned dist; /* distance of matched string */
  22987. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22988. {
  22989. //var out_length, in_length, dcode;
  22990. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22991. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22992. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22993. s.last_lit++;
  22994. if (dist === 0) {
  22995. /* lc is the unmatched char */
  22996. s.dyn_ltree[lc * 2]/*.Freq*/++;
  22997. } else {
  22998. s.matches++;
  22999. /* Here, lc is the match length - MIN_MATCH */
  23000. dist--; /* dist = match distance - 1 */
  23001. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  23002. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  23003. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  23004. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  23005. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  23006. }
  23007. // (!) This block is disabled in zlib defaults,
  23008. // don't enable it for binary compatibility
  23009. //#ifdef TRUNCATE_BLOCK
  23010. // /* Try to guess if it is profitable to stop the current block here */
  23011. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  23012. // /* Compute an upper bound for the compressed length */
  23013. // out_length = s.last_lit*8;
  23014. // in_length = s.strstart - s.block_start;
  23015. //
  23016. // for (dcode = 0; dcode < D_CODES; dcode++) {
  23017. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  23018. // }
  23019. // out_length >>>= 3;
  23020. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  23021. // // s->last_lit, in_length, out_length,
  23022. // // 100L - out_length*100L/in_length));
  23023. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  23024. // return true;
  23025. // }
  23026. // }
  23027. //#endif
  23028. return (s.last_lit === s.lit_bufsize - 1);
  23029. /* We avoid equality with lit_bufsize because of wraparound at 64K
  23030. * on 16 bit machines and because stored blocks are restricted to
  23031. * 64K-1 bytes.
  23032. */
  23033. }
  23034. exports._tr_init = _tr_init;
  23035. exports._tr_stored_block = _tr_stored_block;
  23036. exports._tr_flush_block = _tr_flush_block;
  23037. exports._tr_tally = _tr_tally;
  23038. exports._tr_align = _tr_align;
  23039. },{"../utils/common":268}],280:[function(require,module,exports){
  23040. arguments[4][45][0].apply(exports,arguments)
  23041. },{"dup":45}],281:[function(require,module,exports){
  23042. module.exports = function parseBMFontAscii(data) {
  23043. if (!data)
  23044. throw new Error('no data provided')
  23045. data = data.toString().trim()
  23046. var output = {
  23047. pages: [],
  23048. chars: [],
  23049. kernings: []
  23050. }
  23051. var lines = data.split(/\r\n?|\n/g)
  23052. if (lines.length === 0)
  23053. throw new Error('no data in BMFont file')
  23054. for (var i = 0; i < lines.length; i++) {
  23055. var lineData = splitLine(lines[i], i)
  23056. if (!lineData) //skip empty lines
  23057. continue
  23058. if (lineData.key === 'page') {
  23059. if (typeof lineData.data.id !== 'number')
  23060. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  23061. if (typeof lineData.data.file !== 'string')
  23062. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  23063. output.pages[lineData.data.id] = lineData.data.file
  23064. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  23065. //... do nothing for these two ...
  23066. } else if (lineData.key === 'char') {
  23067. output.chars.push(lineData.data)
  23068. } else if (lineData.key === 'kerning') {
  23069. output.kernings.push(lineData.data)
  23070. } else {
  23071. output[lineData.key] = lineData.data
  23072. }
  23073. }
  23074. return output
  23075. }
  23076. function splitLine(line, idx) {
  23077. line = line.replace(/\t+/g, ' ').trim()
  23078. if (!line)
  23079. return null
  23080. var space = line.indexOf(' ')
  23081. if (space === -1)
  23082. throw new Error("no named row at line " + idx)
  23083. var key = line.substring(0, space)
  23084. line = line.substring(space + 1)
  23085. //clear "letter" field as it is non-standard and
  23086. //requires additional complexity to parse " / = symbols
  23087. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  23088. line = line.split("=")
  23089. line = line.map(function(str) {
  23090. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  23091. })
  23092. var data = []
  23093. for (var i = 0; i < line.length; i++) {
  23094. var dt = line[i]
  23095. if (i === 0) {
  23096. data.push({
  23097. key: dt[0],
  23098. data: ""
  23099. })
  23100. } else if (i === line.length - 1) {
  23101. data[data.length - 1].data = parseData(dt[0])
  23102. } else {
  23103. data[data.length - 1].data = parseData(dt[0])
  23104. data.push({
  23105. key: dt[1],
  23106. data: ""
  23107. })
  23108. }
  23109. }
  23110. var out = {
  23111. key: key,
  23112. data: {}
  23113. }
  23114. data.forEach(function(v) {
  23115. out.data[v.key] = v.data;
  23116. })
  23117. return out
  23118. }
  23119. function parseData(data) {
  23120. if (!data || data.length === 0)
  23121. return ""
  23122. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  23123. return data.substring(1, data.length - 1)
  23124. if (data.indexOf(',') !== -1)
  23125. return parseIntList(data)
  23126. return parseInt(data, 10)
  23127. }
  23128. function parseIntList(data) {
  23129. return data.split(',').map(function(val) {
  23130. return parseInt(val, 10)
  23131. })
  23132. }
  23133. },{}],282:[function(require,module,exports){
  23134. var HEADER = [66, 77, 70]
  23135. module.exports = function readBMFontBinary(buf) {
  23136. if (buf.length < 6)
  23137. throw new Error('invalid buffer length for BMFont')
  23138. var header = HEADER.every(function(byte, i) {
  23139. return buf.readUInt8(i) === byte
  23140. })
  23141. if (!header)
  23142. throw new Error('BMFont missing BMF byte header')
  23143. var i = 3
  23144. var vers = buf.readUInt8(i++)
  23145. if (vers > 3)
  23146. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  23147. var target = { kernings: [], chars: [] }
  23148. for (var b=0; b<5; b++)
  23149. i += readBlock(target, buf, i)
  23150. return target
  23151. }
  23152. function readBlock(target, buf, i) {
  23153. if (i > buf.length-1)
  23154. return 0
  23155. var blockID = buf.readUInt8(i++)
  23156. var blockSize = buf.readInt32LE(i)
  23157. i += 4
  23158. switch(blockID) {
  23159. case 1:
  23160. target.info = readInfo(buf, i)
  23161. break
  23162. case 2:
  23163. target.common = readCommon(buf, i)
  23164. break
  23165. case 3:
  23166. target.pages = readPages(buf, i, blockSize)
  23167. break
  23168. case 4:
  23169. target.chars = readChars(buf, i, blockSize)
  23170. break
  23171. case 5:
  23172. target.kernings = readKernings(buf, i, blockSize)
  23173. break
  23174. }
  23175. return 5 + blockSize
  23176. }
  23177. function readInfo(buf, i) {
  23178. var info = {}
  23179. info.size = buf.readInt16LE(i)
  23180. var bitField = buf.readUInt8(i+2)
  23181. info.smooth = (bitField >> 7) & 1
  23182. info.unicode = (bitField >> 6) & 1
  23183. info.italic = (bitField >> 5) & 1
  23184. info.bold = (bitField >> 4) & 1
  23185. //fixedHeight is only mentioned in binary spec
  23186. if ((bitField >> 3) & 1)
  23187. info.fixedHeight = 1
  23188. info.charset = buf.readUInt8(i+3) || ''
  23189. info.stretchH = buf.readUInt16LE(i+4)
  23190. info.aa = buf.readUInt8(i+6)
  23191. info.padding = [
  23192. buf.readInt8(i+7),
  23193. buf.readInt8(i+8),
  23194. buf.readInt8(i+9),
  23195. buf.readInt8(i+10)
  23196. ]
  23197. info.spacing = [
  23198. buf.readInt8(i+11),
  23199. buf.readInt8(i+12)
  23200. ]
  23201. info.outline = buf.readUInt8(i+13)
  23202. info.face = readStringNT(buf, i+14)
  23203. return info
  23204. }
  23205. function readCommon(buf, i) {
  23206. var common = {}
  23207. common.lineHeight = buf.readUInt16LE(i)
  23208. common.base = buf.readUInt16LE(i+2)
  23209. common.scaleW = buf.readUInt16LE(i+4)
  23210. common.scaleH = buf.readUInt16LE(i+6)
  23211. common.pages = buf.readUInt16LE(i+8)
  23212. var bitField = buf.readUInt8(i+10)
  23213. common.packed = 0
  23214. common.alphaChnl = buf.readUInt8(i+11)
  23215. common.redChnl = buf.readUInt8(i+12)
  23216. common.greenChnl = buf.readUInt8(i+13)
  23217. common.blueChnl = buf.readUInt8(i+14)
  23218. return common
  23219. }
  23220. function readPages(buf, i, size) {
  23221. var pages = []
  23222. var text = readNameNT(buf, i)
  23223. var len = text.length+1
  23224. var count = size / len
  23225. for (var c=0; c<count; c++) {
  23226. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  23227. i += len
  23228. }
  23229. return pages
  23230. }
  23231. function readChars(buf, i, blockSize) {
  23232. var chars = []
  23233. var count = blockSize / 20
  23234. for (var c=0; c<count; c++) {
  23235. var char = {}
  23236. var off = c*20
  23237. char.id = buf.readUInt32LE(i + 0 + off)
  23238. char.x = buf.readUInt16LE(i + 4 + off)
  23239. char.y = buf.readUInt16LE(i + 6 + off)
  23240. char.width = buf.readUInt16LE(i + 8 + off)
  23241. char.height = buf.readUInt16LE(i + 10 + off)
  23242. char.xoffset = buf.readInt16LE(i + 12 + off)
  23243. char.yoffset = buf.readInt16LE(i + 14 + off)
  23244. char.xadvance = buf.readInt16LE(i + 16 + off)
  23245. char.page = buf.readUInt8(i + 18 + off)
  23246. char.chnl = buf.readUInt8(i + 19 + off)
  23247. chars[c] = char
  23248. }
  23249. return chars
  23250. }
  23251. function readKernings(buf, i, blockSize) {
  23252. var kernings = []
  23253. var count = blockSize / 10
  23254. for (var c=0; c<count; c++) {
  23255. var kern = {}
  23256. var off = c*10
  23257. kern.first = buf.readUInt32LE(i + 0 + off)
  23258. kern.second = buf.readUInt32LE(i + 4 + off)
  23259. kern.amount = buf.readInt16LE(i + 8 + off)
  23260. kernings[c] = kern
  23261. }
  23262. return kernings
  23263. }
  23264. function readNameNT(buf, offset) {
  23265. var pos=offset
  23266. for (; pos<buf.length; pos++) {
  23267. if (buf[pos] === 0x00)
  23268. break
  23269. }
  23270. return buf.slice(offset, pos)
  23271. }
  23272. function readStringNT(buf, offset) {
  23273. return readNameNT(buf, offset).toString('utf8')
  23274. }
  23275. },{}],283:[function(require,module,exports){
  23276. var parseAttributes = require('./parse-attribs')
  23277. var parseFromString = require('xml-parse-from-string')
  23278. //In some cases element.attribute.nodeName can return
  23279. //all lowercase values.. so we need to map them to the correct
  23280. //case
  23281. var NAME_MAP = {
  23282. scaleh: 'scaleH',
  23283. scalew: 'scaleW',
  23284. stretchh: 'stretchH',
  23285. lineheight: 'lineHeight',
  23286. alphachnl: 'alphaChnl',
  23287. redchnl: 'redChnl',
  23288. greenchnl: 'greenChnl',
  23289. bluechnl: 'blueChnl'
  23290. }
  23291. module.exports = function parse(data) {
  23292. data = data.toString()
  23293. var xmlRoot = parseFromString(data)
  23294. var output = {
  23295. pages: [],
  23296. chars: [],
  23297. kernings: []
  23298. }
  23299. //get config settings
  23300. ;['info', 'common'].forEach(function(key) {
  23301. var element = xmlRoot.getElementsByTagName(key)[0]
  23302. if (element)
  23303. output[key] = parseAttributes(getAttribs(element))
  23304. })
  23305. //get page info
  23306. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  23307. if (!pageRoot)
  23308. throw new Error('malformed file -- no <pages> element')
  23309. var pages = pageRoot.getElementsByTagName('page')
  23310. for (var i=0; i<pages.length; i++) {
  23311. var p = pages[i]
  23312. var id = parseInt(p.getAttribute('id'), 10)
  23313. var file = p.getAttribute('file')
  23314. if (isNaN(id))
  23315. throw new Error('malformed file -- page "id" attribute is NaN')
  23316. if (!file)
  23317. throw new Error('malformed file -- needs page "file" attribute')
  23318. output.pages[parseInt(id, 10)] = file
  23319. }
  23320. //get kernings / chars
  23321. ;['chars', 'kernings'].forEach(function(key) {
  23322. var element = xmlRoot.getElementsByTagName(key)[0]
  23323. if (!element)
  23324. return
  23325. var childTag = key.substring(0, key.length-1)
  23326. var children = element.getElementsByTagName(childTag)
  23327. for (var i=0; i<children.length; i++) {
  23328. var child = children[i]
  23329. output[key].push(parseAttributes(getAttribs(child)))
  23330. }
  23331. })
  23332. return output
  23333. }
  23334. function getAttribs(element) {
  23335. var attribs = getAttribList(element)
  23336. return attribs.reduce(function(dict, attrib) {
  23337. var key = mapName(attrib.nodeName)
  23338. dict[key] = attrib.nodeValue
  23339. return dict
  23340. }, {})
  23341. }
  23342. function getAttribList(element) {
  23343. //IE8+ and modern browsers
  23344. var attribs = []
  23345. for (var i=0; i<element.attributes.length; i++)
  23346. attribs.push(element.attributes[i])
  23347. return attribs
  23348. }
  23349. function mapName(nodeName) {
  23350. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  23351. }
  23352. },{"./parse-attribs":284,"xml-parse-from-string":367}],284:[function(require,module,exports){
  23353. //Some versions of GlyphDesigner have a typo
  23354. //that causes some bugs with parsing.
  23355. //Need to confirm with recent version of the software
  23356. //to see whether this is still an issue or not.
  23357. var GLYPH_DESIGNER_ERROR = 'chasrset'
  23358. module.exports = function parseAttributes(obj) {
  23359. if (GLYPH_DESIGNER_ERROR in obj) {
  23360. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  23361. delete obj[GLYPH_DESIGNER_ERROR]
  23362. }
  23363. for (var k in obj) {
  23364. if (k === 'face' || k === 'charset')
  23365. continue
  23366. else if (k === 'padding' || k === 'spacing')
  23367. obj[k] = parseIntList(obj[k])
  23368. else
  23369. obj[k] = parseInt(obj[k], 10)
  23370. }
  23371. return obj
  23372. }
  23373. function parseIntList(data) {
  23374. return data.split(',').map(function(val) {
  23375. return parseInt(val, 10)
  23376. })
  23377. }
  23378. },{}],285:[function(require,module,exports){
  23379. var trim = require('trim')
  23380. , forEach = require('for-each')
  23381. , isArray = function(arg) {
  23382. return Object.prototype.toString.call(arg) === '[object Array]';
  23383. }
  23384. module.exports = function (headers) {
  23385. if (!headers)
  23386. return {}
  23387. var result = {}
  23388. forEach(
  23389. trim(headers).split('\n')
  23390. , function (row) {
  23391. var index = row.indexOf(':')
  23392. , key = trim(row.slice(0, index)).toLowerCase()
  23393. , value = trim(row.slice(index + 1))
  23394. if (typeof(result[key]) === 'undefined') {
  23395. result[key] = value
  23396. } else if (isArray(result[key])) {
  23397. result[key].push(value)
  23398. } else {
  23399. result[key] = [ result[key], value ]
  23400. }
  23401. }
  23402. )
  23403. return result
  23404. }
  23405. },{"for-each":250,"trim":358}],286:[function(require,module,exports){
  23406. (function (process){
  23407. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  23408. // backported and transplited with Babel, with backwards-compat fixes
  23409. // Copyright Joyent, Inc. and other Node contributors.
  23410. //
  23411. // Permission is hereby granted, free of charge, to any person obtaining a
  23412. // copy of this software and associated documentation files (the
  23413. // "Software"), to deal in the Software without restriction, including
  23414. // without limitation the rights to use, copy, modify, merge, publish,
  23415. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23416. // persons to whom the Software is furnished to do so, subject to the
  23417. // following conditions:
  23418. //
  23419. // The above copyright notice and this permission notice shall be included
  23420. // in all copies or substantial portions of the Software.
  23421. //
  23422. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23423. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23424. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23425. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23426. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23427. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23428. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23429. // resolves . and .. elements in a path array with directory names there
  23430. // must be no slashes, empty elements, or device names (c:\) in the array
  23431. // (so also no leading and trailing slashes - it does not distinguish
  23432. // relative and absolute paths)
  23433. function normalizeArray(parts, allowAboveRoot) {
  23434. // if the path tries to go above the root, `up` ends up > 0
  23435. var up = 0;
  23436. for (var i = parts.length - 1; i >= 0; i--) {
  23437. var last = parts[i];
  23438. if (last === '.') {
  23439. parts.splice(i, 1);
  23440. } else if (last === '..') {
  23441. parts.splice(i, 1);
  23442. up++;
  23443. } else if (up) {
  23444. parts.splice(i, 1);
  23445. up--;
  23446. }
  23447. }
  23448. // if the path is allowed to go above the root, restore leading ..s
  23449. if (allowAboveRoot) {
  23450. for (; up--; up) {
  23451. parts.unshift('..');
  23452. }
  23453. }
  23454. return parts;
  23455. }
  23456. // path.resolve([from ...], to)
  23457. // posix version
  23458. exports.resolve = function() {
  23459. var resolvedPath = '',
  23460. resolvedAbsolute = false;
  23461. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  23462. var path = (i >= 0) ? arguments[i] : process.cwd();
  23463. // Skip empty and invalid entries
  23464. if (typeof path !== 'string') {
  23465. throw new TypeError('Arguments to path.resolve must be strings');
  23466. } else if (!path) {
  23467. continue;
  23468. }
  23469. resolvedPath = path + '/' + resolvedPath;
  23470. resolvedAbsolute = path.charAt(0) === '/';
  23471. }
  23472. // At this point the path should be resolved to a full absolute path, but
  23473. // handle relative paths to be safe (might happen when process.cwd() fails)
  23474. // Normalize the path
  23475. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  23476. return !!p;
  23477. }), !resolvedAbsolute).join('/');
  23478. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  23479. };
  23480. // path.normalize(path)
  23481. // posix version
  23482. exports.normalize = function(path) {
  23483. var isAbsolute = exports.isAbsolute(path),
  23484. trailingSlash = substr(path, -1) === '/';
  23485. // Normalize the path
  23486. path = normalizeArray(filter(path.split('/'), function(p) {
  23487. return !!p;
  23488. }), !isAbsolute).join('/');
  23489. if (!path && !isAbsolute) {
  23490. path = '.';
  23491. }
  23492. if (path && trailingSlash) {
  23493. path += '/';
  23494. }
  23495. return (isAbsolute ? '/' : '') + path;
  23496. };
  23497. // posix version
  23498. exports.isAbsolute = function(path) {
  23499. return path.charAt(0) === '/';
  23500. };
  23501. // posix version
  23502. exports.join = function() {
  23503. var paths = Array.prototype.slice.call(arguments, 0);
  23504. return exports.normalize(filter(paths, function(p, index) {
  23505. if (typeof p !== 'string') {
  23506. throw new TypeError('Arguments to path.join must be strings');
  23507. }
  23508. return p;
  23509. }).join('/'));
  23510. };
  23511. // path.relative(from, to)
  23512. // posix version
  23513. exports.relative = function(from, to) {
  23514. from = exports.resolve(from).substr(1);
  23515. to = exports.resolve(to).substr(1);
  23516. function trim(arr) {
  23517. var start = 0;
  23518. for (; start < arr.length; start++) {
  23519. if (arr[start] !== '') break;
  23520. }
  23521. var end = arr.length - 1;
  23522. for (; end >= 0; end--) {
  23523. if (arr[end] !== '') break;
  23524. }
  23525. if (start > end) return [];
  23526. return arr.slice(start, end - start + 1);
  23527. }
  23528. var fromParts = trim(from.split('/'));
  23529. var toParts = trim(to.split('/'));
  23530. var length = Math.min(fromParts.length, toParts.length);
  23531. var samePartsLength = length;
  23532. for (var i = 0; i < length; i++) {
  23533. if (fromParts[i] !== toParts[i]) {
  23534. samePartsLength = i;
  23535. break;
  23536. }
  23537. }
  23538. var outputParts = [];
  23539. for (var i = samePartsLength; i < fromParts.length; i++) {
  23540. outputParts.push('..');
  23541. }
  23542. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  23543. return outputParts.join('/');
  23544. };
  23545. exports.sep = '/';
  23546. exports.delimiter = ':';
  23547. exports.dirname = function (path) {
  23548. if (typeof path !== 'string') path = path + '';
  23549. if (path.length === 0) return '.';
  23550. var code = path.charCodeAt(0);
  23551. var hasRoot = code === 47 /*/*/;
  23552. var end = -1;
  23553. var matchedSlash = true;
  23554. for (var i = path.length - 1; i >= 1; --i) {
  23555. code = path.charCodeAt(i);
  23556. if (code === 47 /*/*/) {
  23557. if (!matchedSlash) {
  23558. end = i;
  23559. break;
  23560. }
  23561. } else {
  23562. // We saw the first non-path separator
  23563. matchedSlash = false;
  23564. }
  23565. }
  23566. if (end === -1) return hasRoot ? '/' : '.';
  23567. if (hasRoot && end === 1) {
  23568. // return '//';
  23569. // Backwards-compat fix:
  23570. return '/';
  23571. }
  23572. return path.slice(0, end);
  23573. };
  23574. function basename(path) {
  23575. if (typeof path !== 'string') path = path + '';
  23576. var start = 0;
  23577. var end = -1;
  23578. var matchedSlash = true;
  23579. var i;
  23580. for (i = path.length - 1; i >= 0; --i) {
  23581. if (path.charCodeAt(i) === 47 /*/*/) {
  23582. // If we reached a path separator that was not part of a set of path
  23583. // separators at the end of the string, stop now
  23584. if (!matchedSlash) {
  23585. start = i + 1;
  23586. break;
  23587. }
  23588. } else if (end === -1) {
  23589. // We saw the first non-path separator, mark this as the end of our
  23590. // path component
  23591. matchedSlash = false;
  23592. end = i + 1;
  23593. }
  23594. }
  23595. if (end === -1) return '';
  23596. return path.slice(start, end);
  23597. }
  23598. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  23599. // in new Node.js versions, so only basename() above is backported here
  23600. exports.basename = function (path, ext) {
  23601. var f = basename(path);
  23602. if (ext && f.substr(-1 * ext.length) === ext) {
  23603. f = f.substr(0, f.length - ext.length);
  23604. }
  23605. return f;
  23606. };
  23607. exports.extname = function (path) {
  23608. if (typeof path !== 'string') path = path + '';
  23609. var startDot = -1;
  23610. var startPart = 0;
  23611. var end = -1;
  23612. var matchedSlash = true;
  23613. // Track the state of characters (if any) we see before our first dot and
  23614. // after any path separator we find
  23615. var preDotState = 0;
  23616. for (var i = path.length - 1; i >= 0; --i) {
  23617. var code = path.charCodeAt(i);
  23618. if (code === 47 /*/*/) {
  23619. // If we reached a path separator that was not part of a set of path
  23620. // separators at the end of the string, stop now
  23621. if (!matchedSlash) {
  23622. startPart = i + 1;
  23623. break;
  23624. }
  23625. continue;
  23626. }
  23627. if (end === -1) {
  23628. // We saw the first non-path separator, mark this as the end of our
  23629. // extension
  23630. matchedSlash = false;
  23631. end = i + 1;
  23632. }
  23633. if (code === 46 /*.*/) {
  23634. // If this is our first dot, mark it as the start of our extension
  23635. if (startDot === -1)
  23636. startDot = i;
  23637. else if (preDotState !== 1)
  23638. preDotState = 1;
  23639. } else if (startDot !== -1) {
  23640. // We saw a non-dot and non-path separator before our dot, so we should
  23641. // have a good chance at having a non-empty extension
  23642. preDotState = -1;
  23643. }
  23644. }
  23645. if (startDot === -1 || end === -1 ||
  23646. // We saw a non-dot character immediately before the dot
  23647. preDotState === 0 ||
  23648. // The (right-most) trimmed path component is exactly '..'
  23649. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  23650. return '';
  23651. }
  23652. return path.slice(startDot, end);
  23653. };
  23654. function filter (xs, f) {
  23655. if (xs.filter) return xs.filter(f);
  23656. var res = [];
  23657. for (var i = 0; i < xs.length; i++) {
  23658. if (f(xs[i], i, xs)) res.push(xs[i]);
  23659. }
  23660. return res;
  23661. }
  23662. // String.prototype.substr - negative index don't work in IE8
  23663. var substr = 'ab'.substr(-1) === 'b'
  23664. ? function (str, start, len) { return str.substr(start, len) }
  23665. : function (str, start, len) {
  23666. if (start < 0) start = str.length + start;
  23667. return str.substr(start, len);
  23668. }
  23669. ;
  23670. }).call(this,require('_process'))
  23671. },{"_process":312}],287:[function(require,module,exports){
  23672. (function (Buffer){
  23673. 'use strict';var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};var http=require('http');var https=require('https');var url=require('url');var qs=require('querystring');var zlib=require('zlib');var util=require('util');var phin=function phin(opts,cb){if(typeof opts!=='string'){if(!opts.hasOwnProperty('url')){throw new Error('Missing url option from options for request method.')}}var addr=(typeof opts==='undefined'?'undefined':_typeof(opts))==='object'?url.parse(opts.url):url.parse(opts);var options={'hostname':addr.hostname,'port':addr.port||(addr.protocol.toLowerCase()==='http:'?80:443),'path':addr.path,'method':'GET','headers':{},'auth':addr.auth||null,'parse':'none','stream':false};if((typeof opts==='undefined'?'undefined':_typeof(opts))==='object'){options=Object.assign(options,opts)}options.port=Number(options.port);if(options.hasOwnProperty('timeout'))delete options.timeout;if(options.compressed===true){options.headers['accept-encoding']='gzip, deflate'}if(opts.hasOwnProperty('form')){if(_typeof(opts.form)!=='object'){throw new Error('phin \'form\' option must be of type Object if present.')}var formDataString=qs.stringify(opts.form);options.headers['Content-Type']='application/x-www-form-urlencoded';options.headers['Content-Length']=Buffer.byteLength(formDataString);opts.data=formDataString}var req=void 0;var resHandler=function resHandler(res){var stream=res;if(options.compressed===true){if(res.headers['content-encoding']==='gzip'){stream=res.pipe(zlib.createGunzip())}else if(res.headers['content-encoding']==='deflate'){stream=res.pipe(zlib.createInflate())}}if(options.stream===true){res.stream=stream;cb(null,res)}else{res.body=new Buffer([]);stream.on('data',function(chunk){res.body=Buffer.concat([res.body,chunk])});stream.on('end',function(){if(cb){if(options.parse==='json'){try{res.body=JSON.parse(res.body.toString())}catch(err){cb('Invalid JSON received.',res);return}}cb(null,res)}})}};switch(addr.protocol.toLowerCase()){case'http:':req=http.request(options,resHandler);break;case'https:':req=https.request(options,resHandler);break;default:if(cb){cb(new Error('Invalid / unknown URL protocol. Expected HTTP or HTTPS.'),null)}return;}if(typeof opts.timeout==='number'){req.setTimeout(opts.timeout,function(){req.abort();cb(new Error('Timeout has been reached.'),null);cb=null})}req.on('error',function(err){if(cb){cb(err,null)}});if(opts.hasOwnProperty('data')){var postData=opts.data;if(!(opts.data instanceof Buffer)&&_typeof(opts.data)==='object'){var contentType=options.headers['content-type']||options.headers['Content-Type'];if(contentType==='application/x-www-form-urlencoded'){postData=qs.stringify(opts.data)}else{try{postData=JSON.stringify(opts.data)}catch(err){cb(new Error('Couldn\'t stringify object. (Likely due to a circular reference.)'),null)}}}req.write(postData)}req.end()};phin.promisified=function(opts,http){return new Promise(function(resolve,reject){phin(opts,function(err,res){if(err){reject(err)}else{resolve(res)}},http)})};if(util.promisify){phin[util.promisify.custom]=phin.promisified}module.exports=phin;
  23674. }).call(this,require("buffer").Buffer)
  23675. },{"buffer":47,"http":335,"https":252,"querystring":316,"url":359,"util":365,"zlib":34}],288:[function(require,module,exports){
  23676. 'use strict';
  23677. module.exports = pixelmatch;
  23678. function pixelmatch(img1, img2, output, width, height, options) {
  23679. if (!options) options = {};
  23680. var threshold = options.threshold === undefined ? 0.1 : options.threshold;
  23681. // maximum acceptable square distance between two colors;
  23682. // 35215 is the maximum possible value for the YIQ difference metric
  23683. var maxDelta = 35215 * threshold * threshold,
  23684. diff = 0;
  23685. // compare each pixel of one image against the other one
  23686. for (var y = 0; y < height; y++) {
  23687. for (var x = 0; x < width; x++) {
  23688. var pos = (y * width + x) * 4;
  23689. // squared YUV distance between colors at this pixel position
  23690. var delta = colorDelta(img1, img2, pos, pos);
  23691. // the color difference is above the threshold
  23692. if (delta > maxDelta) {
  23693. // check it's a real rendering difference or just anti-aliasing
  23694. if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) ||
  23695. antialiased(img2, x, y, width, height, img1))) {
  23696. // one of the pixels is anti-aliasing; draw as yellow and do not count as difference
  23697. if (output) drawPixel(output, pos, 255, 255, 0);
  23698. } else {
  23699. // found substantial difference not caused by anti-aliasing; draw it as red
  23700. if (output) drawPixel(output, pos, 255, 0, 0);
  23701. diff++;
  23702. }
  23703. } else if (output) {
  23704. // pixels are similar; draw background as grayscale image blended with white
  23705. var val = blend(grayPixel(img1, pos), 0.1);
  23706. drawPixel(output, pos, val, val, val);
  23707. }
  23708. }
  23709. }
  23710. // return the number of different pixels
  23711. return diff;
  23712. }
  23713. // check if a pixel is likely a part of anti-aliasing;
  23714. // based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009
  23715. function antialiased(img, x1, y1, width, height, img2) {
  23716. var x0 = Math.max(x1 - 1, 0),
  23717. y0 = Math.max(y1 - 1, 0),
  23718. x2 = Math.min(x1 + 1, width - 1),
  23719. y2 = Math.min(y1 + 1, height - 1),
  23720. pos = (y1 * width + x1) * 4,
  23721. zeroes = 0,
  23722. positives = 0,
  23723. negatives = 0,
  23724. min = 0,
  23725. max = 0,
  23726. minX, minY, maxX, maxY;
  23727. // go through 8 adjacent pixels
  23728. for (var x = x0; x <= x2; x++) {
  23729. for (var y = y0; y <= y2; y++) {
  23730. if (x === x1 && y === y1) continue;
  23731. // brightness delta between the center pixel and adjacent one
  23732. var delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
  23733. // count the number of equal, darker and brighter adjacent pixels
  23734. if (delta === 0) zeroes++;
  23735. else if (delta < 0) negatives++;
  23736. else if (delta > 0) positives++;
  23737. // if found more than 2 equal siblings, it's definitely not anti-aliasing
  23738. if (zeroes > 2) return false;
  23739. if (!img2) continue;
  23740. // remember the darkest pixel
  23741. if (delta < min) {
  23742. min = delta;
  23743. minX = x;
  23744. minY = y;
  23745. }
  23746. // remember the brightest pixel
  23747. if (delta > max) {
  23748. max = delta;
  23749. maxX = x;
  23750. maxY = y;
  23751. }
  23752. }
  23753. }
  23754. if (!img2) return true;
  23755. // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing
  23756. if (negatives === 0 || positives === 0) return false;
  23757. // if either the darkest or the brightest pixel has more than 2 equal siblings in both images
  23758. // (definitely not anti-aliased), this pixel is anti-aliased
  23759. return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) ||
  23760. (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height));
  23761. }
  23762. // calculate color difference according to the paper "Measuring perceived color difference
  23763. // using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos
  23764. function colorDelta(img1, img2, k, m, yOnly) {
  23765. var a1 = img1[k + 3] / 255,
  23766. a2 = img2[m + 3] / 255,
  23767. r1 = blend(img1[k + 0], a1),
  23768. g1 = blend(img1[k + 1], a1),
  23769. b1 = blend(img1[k + 2], a1),
  23770. r2 = blend(img2[m + 0], a2),
  23771. g2 = blend(img2[m + 1], a2),
  23772. b2 = blend(img2[m + 2], a2),
  23773. y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2);
  23774. if (yOnly) return y; // brightness difference only
  23775. var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2),
  23776. q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
  23777. return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
  23778. }
  23779. function rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; }
  23780. function rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; }
  23781. function rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; }
  23782. // blend semi-transparent color with white
  23783. function blend(c, a) {
  23784. return 255 + (c - 255) * a;
  23785. }
  23786. function drawPixel(output, pos, r, g, b) {
  23787. output[pos + 0] = r;
  23788. output[pos + 1] = g;
  23789. output[pos + 2] = b;
  23790. output[pos + 3] = 255;
  23791. }
  23792. function grayPixel(img, i) {
  23793. var a = img[i + 3] / 255,
  23794. r = blend(img[i + 0], a),
  23795. g = blend(img[i + 1], a),
  23796. b = blend(img[i + 2], a);
  23797. return rgb2y(r, g, b);
  23798. }
  23799. },{}],289:[function(require,module,exports){
  23800. (function (Buffer){
  23801. 'use strict';
  23802. var interlaceUtils = require('./interlace');
  23803. var pixelBppMap = {
  23804. 1: { // L
  23805. 0: 0,
  23806. 1: 0,
  23807. 2: 0,
  23808. 3: 0xff
  23809. },
  23810. 2: { // LA
  23811. 0: 0,
  23812. 1: 0,
  23813. 2: 0,
  23814. 3: 1
  23815. },
  23816. 3: { // RGB
  23817. 0: 0,
  23818. 1: 1,
  23819. 2: 2,
  23820. 3: 0xff
  23821. },
  23822. 4: { // RGBA
  23823. 0: 0,
  23824. 1: 1,
  23825. 2: 2,
  23826. 3: 3
  23827. }
  23828. };
  23829. function bitRetriever(data, depth) {
  23830. var leftOver = [];
  23831. var i = 0;
  23832. function split() {
  23833. if (i === data.length) {
  23834. throw new Error('Ran out of data');
  23835. }
  23836. var byte = data[i];
  23837. i++;
  23838. var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
  23839. switch (depth) {
  23840. default:
  23841. throw new Error('unrecognised depth');
  23842. case 16:
  23843. byte2 = data[i];
  23844. i++;
  23845. leftOver.push(((byte << 8) + byte2));
  23846. break;
  23847. case 4:
  23848. byte2 = byte & 0x0f;
  23849. byte1 = byte >> 4;
  23850. leftOver.push(byte1, byte2);
  23851. break;
  23852. case 2:
  23853. byte4 = byte & 3;
  23854. byte3 = byte >> 2 & 3;
  23855. byte2 = byte >> 4 & 3;
  23856. byte1 = byte >> 6 & 3;
  23857. leftOver.push(byte1, byte2, byte3, byte4);
  23858. break;
  23859. case 1:
  23860. byte8 = byte & 1;
  23861. byte7 = byte >> 1 & 1;
  23862. byte6 = byte >> 2 & 1;
  23863. byte5 = byte >> 3 & 1;
  23864. byte4 = byte >> 4 & 1;
  23865. byte3 = byte >> 5 & 1;
  23866. byte2 = byte >> 6 & 1;
  23867. byte1 = byte >> 7 & 1;
  23868. leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
  23869. break;
  23870. }
  23871. }
  23872. return {
  23873. get: function(count) {
  23874. while (leftOver.length < count) {
  23875. split();
  23876. }
  23877. var returner = leftOver.slice(0, count);
  23878. leftOver = leftOver.slice(count);
  23879. return returner;
  23880. },
  23881. resetAfterLine: function() {
  23882. leftOver.length = 0;
  23883. },
  23884. end: function() {
  23885. if (i !== data.length) {
  23886. throw new Error('extra data found');
  23887. }
  23888. }
  23889. };
  23890. }
  23891. function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
  23892. var imageWidth = image.width;
  23893. var imageHeight = image.height;
  23894. var imagePass = image.index;
  23895. for (var y = 0; y < imageHeight; y++) {
  23896. for (var x = 0; x < imageWidth; x++) {
  23897. var pxPos = getPxPos(x, y, imagePass);
  23898. for (var i = 0; i < 4; i++) {
  23899. var idx = pixelBppMap[bpp][i];
  23900. if (idx === 0xff) {
  23901. pxData[pxPos + i] = 0xff;
  23902. } else {
  23903. var dataPos = idx + rawPos;
  23904. if (dataPos === data.length) {
  23905. throw new Error('Ran out of data');
  23906. }
  23907. pxData[pxPos + i] = data[dataPos];
  23908. }
  23909. }
  23910. rawPos += bpp; //eslint-disable-line no-param-reassign
  23911. }
  23912. }
  23913. return rawPos;
  23914. }
  23915. function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
  23916. var imageWidth = image.width;
  23917. var imageHeight = image.height;
  23918. var imagePass = image.index;
  23919. for (var y = 0; y < imageHeight; y++) {
  23920. for (var x = 0; x < imageWidth; x++) {
  23921. var pixelData = bits.get(bpp);
  23922. var pxPos = getPxPos(x, y, imagePass);
  23923. for (var i = 0; i < 4; i++) {
  23924. var idx = pixelBppMap[bpp][i];
  23925. pxData[pxPos + i] = idx !== 0xff ? pixelData[idx] : maxBit;
  23926. }
  23927. }
  23928. bits.resetAfterLine();
  23929. }
  23930. }
  23931. exports.dataToBitMap = function(data, bitmapInfo) {
  23932. var width = bitmapInfo.width;
  23933. var height = bitmapInfo.height;
  23934. var depth = bitmapInfo.depth;
  23935. var bpp = bitmapInfo.bpp;
  23936. var interlace = bitmapInfo.interlace;
  23937. if (depth !== 8) {
  23938. var bits = bitRetriever(data, depth);
  23939. }
  23940. var pxData;
  23941. if (depth <= 8) {
  23942. pxData = new Buffer(width * height * 4);
  23943. }
  23944. else {
  23945. pxData = new Uint16Array(width * height * 4);
  23946. }
  23947. var maxBit = Math.pow(2, depth) - 1;
  23948. var rawPos = 0;
  23949. var images;
  23950. var getPxPos;
  23951. if (interlace) {
  23952. images = interlaceUtils.getImagePasses(width, height);
  23953. getPxPos = interlaceUtils.getInterlaceIterator(width, height);
  23954. }
  23955. else {
  23956. var nonInterlacedPxPos = 0;
  23957. getPxPos = function() {
  23958. var returner = nonInterlacedPxPos;
  23959. nonInterlacedPxPos += 4;
  23960. return returner;
  23961. };
  23962. images = [{ width: width, height: height }];
  23963. }
  23964. for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
  23965. if (depth === 8) {
  23966. rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
  23967. }
  23968. else {
  23969. mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
  23970. }
  23971. }
  23972. if (depth === 8) {
  23973. if (rawPos !== data.length) {
  23974. throw new Error('extra data found');
  23975. }
  23976. }
  23977. else {
  23978. bits.end();
  23979. }
  23980. return pxData;
  23981. };
  23982. }).call(this,require("buffer").Buffer)
  23983. },{"./interlace":299,"buffer":47}],290:[function(require,module,exports){
  23984. (function (Buffer){
  23985. 'use strict';
  23986. var constants = require('./constants');
  23987. module.exports = function(dataIn, width, height, options) {
  23988. var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
  23989. if (options.colorType === options.inputColorType) {
  23990. var bigEndian = (function() {
  23991. var buffer = new ArrayBuffer(2);
  23992. new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
  23993. // Int16Array uses the platform's endianness.
  23994. return new Int16Array(buffer)[0] !== 256;
  23995. })();
  23996. // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
  23997. if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)){
  23998. return dataIn;
  23999. }
  24000. }
  24001. // map to a UInt16 array if data is 16bit, fix endianness below
  24002. var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
  24003. var maxValue = 255;
  24004. var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
  24005. if (inBpp == 4 && !options.inputHasAlpha) inBpp = 3;
  24006. var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
  24007. if (options.bitDepth === 16) {
  24008. maxValue = 65535;
  24009. outBpp *= 2;
  24010. }
  24011. var outData = new Buffer(width * height * outBpp);
  24012. var inIndex = 0;
  24013. var outIndex = 0;
  24014. var bgColor = options.bgColor || {};
  24015. if (bgColor.red === undefined) {
  24016. bgColor.red = maxValue;
  24017. }
  24018. if (bgColor.green === undefined) {
  24019. bgColor.green = maxValue;
  24020. }
  24021. if (bgColor.blue === undefined) {
  24022. bgColor.blue = maxValue;
  24023. }
  24024. function getRGBA(data, inIndex) {
  24025. var red, green, blue, alpha = maxValue;
  24026. switch (options.inputColorType) {
  24027. case constants.COLORTYPE_COLOR_ALPHA:
  24028. alpha = data[inIndex + 3];
  24029. red = data[inIndex];
  24030. green = data[inIndex+1];
  24031. blue = data[inIndex+2];
  24032. break;
  24033. case constants.COLORTYPE_COLOR:
  24034. red = data[inIndex];
  24035. green = data[inIndex+1];
  24036. blue = data[inIndex+2];
  24037. break;
  24038. case constants.COLORTYPE_ALPHA:
  24039. alpha = data[inIndex + 1];
  24040. red = data[inIndex];
  24041. green = red;
  24042. blue = red;
  24043. break;
  24044. case constants.COLORTYPE_GRAYSCALE:
  24045. red = data[inIndex];
  24046. green = red;
  24047. blue = red;
  24048. break;
  24049. default:
  24050. throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
  24051. }
  24052. if (options.inputHasAlpha) {
  24053. if (!outHasAlpha) {
  24054. alpha /= maxValue;
  24055. red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
  24056. green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
  24057. blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
  24058. }
  24059. }
  24060. return {red: red, green: green, blue: blue, alpha: alpha};
  24061. }
  24062. for (var y = 0; y < height; y++) {
  24063. for (var x = 0; x < width; x++) {
  24064. var rgba = getRGBA(data, inIndex);
  24065. switch (options.colorType) {
  24066. case constants.COLORTYPE_COLOR_ALPHA:
  24067. case constants.COLORTYPE_COLOR:
  24068. if (options.bitDepth === 8) {
  24069. outData[outIndex] = rgba.red;
  24070. outData[outIndex + 1] = rgba.green;
  24071. outData[outIndex + 2] = rgba.blue;
  24072. if (outHasAlpha) {
  24073. outData[outIndex + 3] = rgba.alpha;
  24074. }
  24075. } else {
  24076. outData.writeUInt16BE(rgba.red, outIndex);
  24077. outData.writeUInt16BE(rgba.green, outIndex + 2);
  24078. outData.writeUInt16BE(rgba.blue, outIndex + 4);
  24079. if (outHasAlpha) {
  24080. outData.writeUInt16BE(rgba.alpha, outIndex + 6);
  24081. }
  24082. }
  24083. break;
  24084. case constants.COLORTYPE_ALPHA:
  24085. case constants.COLORTYPE_GRAYSCALE:
  24086. // Convert to grayscale and alpha
  24087. var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
  24088. if (options.bitDepth === 8) {
  24089. outData[outIndex] = grayscale;
  24090. if (outHasAlpha) {
  24091. outData[outIndex + 1] = rgba.alpha;
  24092. }
  24093. } else {
  24094. outData.writeUInt16BE(grayscale, outIndex);
  24095. if (outHasAlpha) {
  24096. outData.writeUInt16BE(rgba.alpha, outIndex + 2);
  24097. }
  24098. }
  24099. break;
  24100. }
  24101. inIndex += inBpp;
  24102. outIndex += outBpp;
  24103. }
  24104. }
  24105. return outData;
  24106. };
  24107. }).call(this,require("buffer").Buffer)
  24108. },{"./constants":292,"buffer":47}],291:[function(require,module,exports){
  24109. (function (process,Buffer){
  24110. 'use strict';
  24111. var util = require('util');
  24112. var Stream = require('stream');
  24113. var ChunkStream = module.exports = function() {
  24114. Stream.call(this);
  24115. this._buffers = [];
  24116. this._buffered = 0;
  24117. this._reads = [];
  24118. this._paused = false;
  24119. this._encoding = 'utf8';
  24120. this.writable = true;
  24121. };
  24122. util.inherits(ChunkStream, Stream);
  24123. ChunkStream.prototype.read = function(length, callback) {
  24124. this._reads.push({
  24125. length: Math.abs(length), // if length < 0 then at most this length
  24126. allowLess: length < 0,
  24127. func: callback
  24128. });
  24129. process.nextTick(function() {
  24130. this._process();
  24131. // its paused and there is not enought data then ask for more
  24132. if (this._paused && this._reads.length > 0) {
  24133. this._paused = false;
  24134. this.emit('drain');
  24135. }
  24136. }.bind(this));
  24137. };
  24138. ChunkStream.prototype.write = function(data, encoding) {
  24139. if (!this.writable) {
  24140. this.emit('error', new Error('Stream not writable'));
  24141. return false;
  24142. }
  24143. var dataBuffer;
  24144. if (Buffer.isBuffer(data)) {
  24145. dataBuffer = data;
  24146. }
  24147. else {
  24148. dataBuffer = new Buffer(data, encoding || this._encoding);
  24149. }
  24150. this._buffers.push(dataBuffer);
  24151. this._buffered += dataBuffer.length;
  24152. this._process();
  24153. // ok if there are no more read requests
  24154. if (this._reads && this._reads.length === 0) {
  24155. this._paused = true;
  24156. }
  24157. return this.writable && !this._paused;
  24158. };
  24159. ChunkStream.prototype.end = function(data, encoding) {
  24160. if (data) {
  24161. this.write(data, encoding);
  24162. }
  24163. this.writable = false;
  24164. // already destroyed
  24165. if (!this._buffers) {
  24166. return;
  24167. }
  24168. // enqueue or handle end
  24169. if (this._buffers.length === 0) {
  24170. this._end();
  24171. }
  24172. else {
  24173. this._buffers.push(null);
  24174. this._process();
  24175. }
  24176. };
  24177. ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
  24178. ChunkStream.prototype._end = function() {
  24179. if (this._reads.length > 0) {
  24180. this.emit('error',
  24181. new Error('There are some read requests waiting on finished stream')
  24182. );
  24183. }
  24184. this.destroy();
  24185. };
  24186. ChunkStream.prototype.destroy = function() {
  24187. if (!this._buffers) {
  24188. return;
  24189. }
  24190. this.writable = false;
  24191. this._reads = null;
  24192. this._buffers = null;
  24193. this.emit('close');
  24194. };
  24195. ChunkStream.prototype._processReadAllowingLess = function(read) {
  24196. // ok there is any data so that we can satisfy this request
  24197. this._reads.shift(); // == read
  24198. // first we need to peek into first buffer
  24199. var smallerBuf = this._buffers[0];
  24200. // ok there is more data than we need
  24201. if (smallerBuf.length > read.length) {
  24202. this._buffered -= read.length;
  24203. this._buffers[0] = smallerBuf.slice(read.length);
  24204. read.func.call(this, smallerBuf.slice(0, read.length));
  24205. }
  24206. else {
  24207. // ok this is less than maximum length so use it all
  24208. this._buffered -= smallerBuf.length;
  24209. this._buffers.shift(); // == smallerBuf
  24210. read.func.call(this, smallerBuf);
  24211. }
  24212. };
  24213. ChunkStream.prototype._processRead = function(read) {
  24214. this._reads.shift(); // == read
  24215. var pos = 0;
  24216. var count = 0;
  24217. var data = new Buffer(read.length);
  24218. // create buffer for all data
  24219. while (pos < read.length) {
  24220. var buf = this._buffers[count++];
  24221. var len = Math.min(buf.length, read.length - pos);
  24222. buf.copy(data, pos, 0, len);
  24223. pos += len;
  24224. // last buffer wasn't used all so just slice it and leave
  24225. if (len !== buf.length) {
  24226. this._buffers[--count] = buf.slice(len);
  24227. }
  24228. }
  24229. // remove all used buffers
  24230. if (count > 0) {
  24231. this._buffers.splice(0, count);
  24232. }
  24233. this._buffered -= read.length;
  24234. read.func.call(this, data);
  24235. };
  24236. ChunkStream.prototype._process = function() {
  24237. try {
  24238. // as long as there is any data and read requests
  24239. while (this._buffered > 0 && this._reads && this._reads.length > 0) {
  24240. var read = this._reads[0];
  24241. // read any data (but no more than length)
  24242. if (read.allowLess) {
  24243. this._processReadAllowingLess(read);
  24244. }
  24245. else if (this._buffered >= read.length) {
  24246. // ok we can meet some expectations
  24247. this._processRead(read);
  24248. }
  24249. else {
  24250. // not enought data to satisfy first request in queue
  24251. // so we need to wait for more
  24252. break;
  24253. }
  24254. }
  24255. if (this._buffers && this._buffers.length > 0 && this._buffers[0] === null) {
  24256. this._end();
  24257. }
  24258. }
  24259. catch (ex) {
  24260. this.emit('error', ex);
  24261. }
  24262. };
  24263. }).call(this,require('_process'),require("buffer").Buffer)
  24264. },{"_process":312,"buffer":47,"stream":334,"util":365}],292:[function(require,module,exports){
  24265. 'use strict';
  24266. module.exports = {
  24267. PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
  24268. TYPE_IHDR: 0x49484452,
  24269. TYPE_IEND: 0x49454e44,
  24270. TYPE_IDAT: 0x49444154,
  24271. TYPE_PLTE: 0x504c5445,
  24272. TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
  24273. TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
  24274. // color-type bits
  24275. COLORTYPE_GRAYSCALE: 0,
  24276. COLORTYPE_PALETTE: 1,
  24277. COLORTYPE_COLOR: 2,
  24278. COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
  24279. // color-type combinations
  24280. COLORTYPE_PALETTE_COLOR: 3,
  24281. COLORTYPE_COLOR_ALPHA: 6,
  24282. COLORTYPE_TO_BPP_MAP: {
  24283. 0: 1,
  24284. 2: 3,
  24285. 3: 1,
  24286. 4: 2,
  24287. 6: 4
  24288. },
  24289. GAMMA_DIVISION: 100000
  24290. };
  24291. },{}],293:[function(require,module,exports){
  24292. 'use strict';
  24293. var crcTable = [];
  24294. (function() {
  24295. for (var i = 0; i < 256; i++) {
  24296. var currentCrc = i;
  24297. for (var j = 0; j < 8; j++) {
  24298. if (currentCrc & 1) {
  24299. currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
  24300. }
  24301. else {
  24302. currentCrc = currentCrc >>> 1;
  24303. }
  24304. }
  24305. crcTable[i] = currentCrc;
  24306. }
  24307. }());
  24308. var CrcCalculator = module.exports = function() {
  24309. this._crc = -1;
  24310. };
  24311. CrcCalculator.prototype.write = function(data) {
  24312. for (var i = 0; i < data.length; i++) {
  24313. this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
  24314. }
  24315. return true;
  24316. };
  24317. CrcCalculator.prototype.crc32 = function() {
  24318. return this._crc ^ -1;
  24319. };
  24320. CrcCalculator.crc32 = function(buf) {
  24321. var crc = -1;
  24322. for (var i = 0; i < buf.length; i++) {
  24323. crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
  24324. }
  24325. return crc ^ -1;
  24326. };
  24327. },{}],294:[function(require,module,exports){
  24328. (function (Buffer){
  24329. 'use strict';
  24330. var paethPredictor = require('./paeth-predictor');
  24331. function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
  24332. for (var x = 0; x < byteWidth; x++) {
  24333. rawData[rawPos + x] = pxData[pxPos + x];
  24334. }
  24335. }
  24336. function filterSumNone(pxData, pxPos, byteWidth) {
  24337. var sum = 0;
  24338. var length = pxPos + byteWidth;
  24339. for (var i = pxPos; i < length; i++) {
  24340. sum += Math.abs(pxData[i]);
  24341. }
  24342. return sum;
  24343. }
  24344. function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  24345. for (var x = 0; x < byteWidth; x++) {
  24346. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24347. var val = pxData[pxPos + x] - left;
  24348. rawData[rawPos + x] = val;
  24349. }
  24350. }
  24351. function filterSumSub(pxData, pxPos, byteWidth, bpp) {
  24352. var sum = 0;
  24353. for (var x = 0; x < byteWidth; x++) {
  24354. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24355. var val = pxData[pxPos + x] - left;
  24356. sum += Math.abs(val);
  24357. }
  24358. return sum;
  24359. }
  24360. function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
  24361. for (var x = 0; x < byteWidth; x++) {
  24362. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  24363. var val = pxData[pxPos + x] - up;
  24364. rawData[rawPos + x] = val;
  24365. }
  24366. }
  24367. function filterSumUp(pxData, pxPos, byteWidth) {
  24368. var sum = 0;
  24369. var length = pxPos + byteWidth;
  24370. for (var x = pxPos; x < length; x++) {
  24371. var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
  24372. var val = pxData[x] - up;
  24373. sum += Math.abs(val);
  24374. }
  24375. return sum;
  24376. }
  24377. function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  24378. for (var x = 0; x < byteWidth; x++) {
  24379. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24380. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  24381. var val = pxData[pxPos + x] - ((left + up) >> 1);
  24382. rawData[rawPos + x] = val;
  24383. }
  24384. }
  24385. function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
  24386. var sum = 0;
  24387. for (var x = 0; x < byteWidth; x++) {
  24388. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24389. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  24390. var val = pxData[pxPos + x] - ((left + up) >> 1);
  24391. sum += Math.abs(val);
  24392. }
  24393. return sum;
  24394. }
  24395. function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  24396. for (var x = 0; x < byteWidth; x++) {
  24397. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24398. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  24399. var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  24400. var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  24401. rawData[rawPos + x] = val;
  24402. }
  24403. }
  24404. function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
  24405. var sum = 0;
  24406. for (var x = 0; x < byteWidth; x++) {
  24407. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  24408. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  24409. var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  24410. var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  24411. sum += Math.abs(val);
  24412. }
  24413. return sum;
  24414. }
  24415. var filters = {
  24416. 0: filterNone,
  24417. 1: filterSub,
  24418. 2: filterUp,
  24419. 3: filterAvg,
  24420. 4: filterPaeth
  24421. };
  24422. var filterSums = {
  24423. 0: filterSumNone,
  24424. 1: filterSumSub,
  24425. 2: filterSumUp,
  24426. 3: filterSumAvg,
  24427. 4: filterSumPaeth
  24428. };
  24429. module.exports = function(pxData, width, height, options, bpp) {
  24430. var filterTypes;
  24431. if (!('filterType' in options) || options.filterType === -1) {
  24432. filterTypes = [0, 1, 2, 3, 4];
  24433. }
  24434. else if (typeof options.filterType === 'number') {
  24435. filterTypes = [options.filterType];
  24436. }
  24437. else {
  24438. throw new Error('unrecognised filter types');
  24439. }
  24440. if (options.bitDepth === 16) bpp *= 2;
  24441. var byteWidth = width * bpp;
  24442. var rawPos = 0;
  24443. var pxPos = 0;
  24444. var rawData = new Buffer((byteWidth + 1) * height);
  24445. var sel = filterTypes[0];
  24446. for (var y = 0; y < height; y++) {
  24447. if (filterTypes.length > 1) {
  24448. // find best filter for this line (with lowest sum of values)
  24449. var min = Infinity;
  24450. for (var i = 0; i < filterTypes.length; i++) {
  24451. var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
  24452. if (sum < min) {
  24453. sel = filterTypes[i];
  24454. min = sum;
  24455. }
  24456. }
  24457. }
  24458. rawData[rawPos] = sel;
  24459. rawPos++;
  24460. filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
  24461. rawPos += byteWidth;
  24462. pxPos += byteWidth;
  24463. }
  24464. return rawData;
  24465. };
  24466. }).call(this,require("buffer").Buffer)
  24467. },{"./paeth-predictor":303,"buffer":47}],295:[function(require,module,exports){
  24468. (function (Buffer){
  24469. 'use strict';
  24470. var util = require('util');
  24471. var ChunkStream = require('./chunkstream');
  24472. var Filter = require('./filter-parse');
  24473. var FilterAsync = module.exports = function(bitmapInfo) {
  24474. ChunkStream.call(this);
  24475. var buffers = [];
  24476. var that = this;
  24477. this._filter = new Filter(bitmapInfo, {
  24478. read: this.read.bind(this),
  24479. write: function(buffer) {
  24480. buffers.push(buffer);
  24481. },
  24482. complete: function() {
  24483. that.emit('complete', Buffer.concat(buffers));
  24484. }
  24485. });
  24486. this._filter.start();
  24487. };
  24488. util.inherits(FilterAsync, ChunkStream);
  24489. }).call(this,require("buffer").Buffer)
  24490. },{"./chunkstream":291,"./filter-parse":297,"buffer":47,"util":365}],296:[function(require,module,exports){
  24491. (function (Buffer){
  24492. 'use strict';
  24493. var SyncReader = require('./sync-reader');
  24494. var Filter = require('./filter-parse');
  24495. exports.process = function(inBuffer, bitmapInfo) {
  24496. var outBuffers = [];
  24497. var reader = new SyncReader(inBuffer);
  24498. var filter = new Filter(bitmapInfo, {
  24499. read: reader.read.bind(reader),
  24500. write: function(bufferPart) {
  24501. outBuffers.push(bufferPart);
  24502. },
  24503. complete: function() {
  24504. }
  24505. });
  24506. filter.start();
  24507. reader.process();
  24508. return Buffer.concat(outBuffers);
  24509. };
  24510. }).call(this,require("buffer").Buffer)
  24511. },{"./filter-parse":297,"./sync-reader":310,"buffer":47}],297:[function(require,module,exports){
  24512. (function (Buffer){
  24513. 'use strict';
  24514. var interlaceUtils = require('./interlace');
  24515. var paethPredictor = require('./paeth-predictor');
  24516. function getByteWidth(width, bpp, depth) {
  24517. var byteWidth = width * bpp;
  24518. if (depth !== 8) {
  24519. byteWidth = Math.ceil(byteWidth / (8 / depth));
  24520. }
  24521. return byteWidth;
  24522. }
  24523. var Filter = module.exports = function(bitmapInfo, dependencies) {
  24524. var width = bitmapInfo.width;
  24525. var height = bitmapInfo.height;
  24526. var interlace = bitmapInfo.interlace;
  24527. var bpp = bitmapInfo.bpp;
  24528. var depth = bitmapInfo.depth;
  24529. this.read = dependencies.read;
  24530. this.write = dependencies.write;
  24531. this.complete = dependencies.complete;
  24532. this._imageIndex = 0;
  24533. this._images = [];
  24534. if (interlace) {
  24535. var passes = interlaceUtils.getImagePasses(width, height);
  24536. for (var i = 0; i < passes.length; i++) {
  24537. this._images.push({
  24538. byteWidth: getByteWidth(passes[i].width, bpp, depth),
  24539. height: passes[i].height,
  24540. lineIndex: 0
  24541. });
  24542. }
  24543. }
  24544. else {
  24545. this._images.push({
  24546. byteWidth: getByteWidth(width, bpp, depth),
  24547. height: height,
  24548. lineIndex: 0
  24549. });
  24550. }
  24551. // when filtering the line we look at the pixel to the left
  24552. // the spec also says it is done on a byte level regardless of the number of pixels
  24553. // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
  24554. // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
  24555. if (depth === 8) {
  24556. this._xComparison = bpp;
  24557. }
  24558. else if (depth === 16) {
  24559. this._xComparison = bpp * 2;
  24560. }
  24561. else {
  24562. this._xComparison = 1;
  24563. }
  24564. };
  24565. Filter.prototype.start = function() {
  24566. this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
  24567. };
  24568. Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
  24569. var xComparison = this._xComparison;
  24570. var xBiggerThan = xComparison - 1;
  24571. for (var x = 0; x < byteWidth; x++) {
  24572. var rawByte = rawData[1 + x];
  24573. var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  24574. unfilteredLine[x] = rawByte + f1Left;
  24575. }
  24576. };
  24577. Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
  24578. var lastLine = this._lastLine;
  24579. for (var x = 0; x < byteWidth; x++) {
  24580. var rawByte = rawData[1 + x];
  24581. var f2Up = lastLine ? lastLine[x] : 0;
  24582. unfilteredLine[x] = rawByte + f2Up;
  24583. }
  24584. };
  24585. Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
  24586. var xComparison = this._xComparison;
  24587. var xBiggerThan = xComparison - 1;
  24588. var lastLine = this._lastLine;
  24589. for (var x = 0; x < byteWidth; x++) {
  24590. var rawByte = rawData[1 + x];
  24591. var f3Up = lastLine ? lastLine[x] : 0;
  24592. var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  24593. var f3Add = Math.floor((f3Left + f3Up) / 2);
  24594. unfilteredLine[x] = rawByte + f3Add;
  24595. }
  24596. };
  24597. Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
  24598. var xComparison = this._xComparison;
  24599. var xBiggerThan = xComparison - 1;
  24600. var lastLine = this._lastLine;
  24601. for (var x = 0; x < byteWidth; x++) {
  24602. var rawByte = rawData[1 + x];
  24603. var f4Up = lastLine ? lastLine[x] : 0;
  24604. var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  24605. var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
  24606. var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
  24607. unfilteredLine[x] = rawByte + f4Add;
  24608. }
  24609. };
  24610. Filter.prototype._reverseFilterLine = function(rawData) {
  24611. var filter = rawData[0];
  24612. var unfilteredLine;
  24613. var currentImage = this._images[this._imageIndex];
  24614. var byteWidth = currentImage.byteWidth;
  24615. if (filter === 0) {
  24616. unfilteredLine = rawData.slice(1, byteWidth + 1);
  24617. }
  24618. else {
  24619. unfilteredLine = new Buffer(byteWidth);
  24620. switch (filter) {
  24621. case 1:
  24622. this._unFilterType1(rawData, unfilteredLine, byteWidth);
  24623. break;
  24624. case 2:
  24625. this._unFilterType2(rawData, unfilteredLine, byteWidth);
  24626. break;
  24627. case 3:
  24628. this._unFilterType3(rawData, unfilteredLine, byteWidth);
  24629. break;
  24630. case 4:
  24631. this._unFilterType4(rawData, unfilteredLine, byteWidth);
  24632. break;
  24633. default:
  24634. throw new Error('Unrecognised filter type - ' + filter);
  24635. }
  24636. }
  24637. this.write(unfilteredLine);
  24638. currentImage.lineIndex++;
  24639. if (currentImage.lineIndex >= currentImage.height) {
  24640. this._lastLine = null;
  24641. this._imageIndex++;
  24642. currentImage = this._images[this._imageIndex];
  24643. }
  24644. else {
  24645. this._lastLine = unfilteredLine;
  24646. }
  24647. if (currentImage) {
  24648. // read, using the byte width that may be from the new current image
  24649. this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
  24650. }
  24651. else {
  24652. this._lastLine = null;
  24653. this.complete();
  24654. }
  24655. };
  24656. }).call(this,require("buffer").Buffer)
  24657. },{"./interlace":299,"./paeth-predictor":303,"buffer":47}],298:[function(require,module,exports){
  24658. (function (Buffer){
  24659. 'use strict';
  24660. function dePalette(indata, outdata, width, height, palette) {
  24661. var pxPos = 0;
  24662. // use values from palette
  24663. for (var y = 0; y < height; y++) {
  24664. for (var x = 0; x < width; x++) {
  24665. var color = palette[indata[pxPos]];
  24666. if (!color) {
  24667. throw new Error('index ' + indata[pxPos] + ' not in palette');
  24668. }
  24669. for (var i = 0; i < 4; i++) {
  24670. outdata[pxPos + i] = color[i];
  24671. }
  24672. pxPos += 4;
  24673. }
  24674. }
  24675. }
  24676. function replaceTransparentColor(indata, outdata, width, height, transColor) {
  24677. var pxPos = 0;
  24678. for (var y = 0; y < height; y++) {
  24679. for (var x = 0; x < width; x++) {
  24680. var makeTrans = false;
  24681. if (transColor.length === 1) {
  24682. if (transColor[0] === indata[pxPos]) {
  24683. makeTrans = true;
  24684. }
  24685. }
  24686. else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
  24687. makeTrans = true;
  24688. }
  24689. if (makeTrans) {
  24690. for (var i = 0; i < 4; i++) {
  24691. outdata[pxPos + i] = 0;
  24692. }
  24693. }
  24694. pxPos += 4;
  24695. }
  24696. }
  24697. }
  24698. function scaleDepth(indata, outdata, width, height, depth) {
  24699. var maxOutSample = 255;
  24700. var maxInSample = Math.pow(2, depth) - 1;
  24701. var pxPos = 0;
  24702. for (var y = 0; y < height; y++) {
  24703. for (var x = 0; x < width; x++) {
  24704. for (var i = 0; i < 4; i++) {
  24705. outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
  24706. }
  24707. pxPos += 4;
  24708. }
  24709. }
  24710. }
  24711. module.exports = function(indata, imageData) {
  24712. var depth = imageData.depth;
  24713. var width = imageData.width;
  24714. var height = imageData.height;
  24715. var colorType = imageData.colorType;
  24716. var transColor = imageData.transColor;
  24717. var palette = imageData.palette;
  24718. var outdata = indata; // only different for 16 bits
  24719. if (colorType === 3) { // paletted
  24720. dePalette(indata, outdata, width, height, palette);
  24721. }
  24722. else {
  24723. if (transColor) {
  24724. replaceTransparentColor(indata, outdata, width, height, transColor);
  24725. }
  24726. // if it needs scaling
  24727. if (depth !== 8) {
  24728. // if we need to change the buffer size
  24729. if (depth === 16) {
  24730. outdata = new Buffer(width * height * 4);
  24731. }
  24732. scaleDepth(indata, outdata, width, height, depth);
  24733. }
  24734. }
  24735. return outdata;
  24736. };
  24737. }).call(this,require("buffer").Buffer)
  24738. },{"buffer":47}],299:[function(require,module,exports){
  24739. 'use strict';
  24740. // Adam 7
  24741. // 0 1 2 3 4 5 6 7
  24742. // 0 x 6 4 6 x 6 4 6
  24743. // 1 7 7 7 7 7 7 7 7
  24744. // 2 5 6 5 6 5 6 5 6
  24745. // 3 7 7 7 7 7 7 7 7
  24746. // 4 3 6 4 6 3 6 4 6
  24747. // 5 7 7 7 7 7 7 7 7
  24748. // 6 5 6 5 6 5 6 5 6
  24749. // 7 7 7 7 7 7 7 7 7
  24750. var imagePasses = [
  24751. { // pass 1 - 1px
  24752. x: [0],
  24753. y: [0]
  24754. },
  24755. { // pass 2 - 1px
  24756. x: [4],
  24757. y: [0]
  24758. },
  24759. { // pass 3 - 2px
  24760. x: [0, 4],
  24761. y: [4]
  24762. },
  24763. { // pass 4 - 4px
  24764. x: [2, 6],
  24765. y: [0, 4]
  24766. },
  24767. { // pass 5 - 8px
  24768. x: [0, 2, 4, 6],
  24769. y: [2, 6]
  24770. },
  24771. { // pass 6 - 16px
  24772. x: [1, 3, 5, 7],
  24773. y: [0, 2, 4, 6]
  24774. },
  24775. { // pass 7 - 32px
  24776. x: [0, 1, 2, 3, 4, 5, 6, 7],
  24777. y: [1, 3, 5, 7]
  24778. }
  24779. ];
  24780. exports.getImagePasses = function(width, height) {
  24781. var images = [];
  24782. var xLeftOver = width % 8;
  24783. var yLeftOver = height % 8;
  24784. var xRepeats = (width - xLeftOver) / 8;
  24785. var yRepeats = (height - yLeftOver) / 8;
  24786. for (var i = 0; i < imagePasses.length; i++) {
  24787. var pass = imagePasses[i];
  24788. var passWidth = xRepeats * pass.x.length;
  24789. var passHeight = yRepeats * pass.y.length;
  24790. for (var j = 0; j < pass.x.length; j++) {
  24791. if (pass.x[j] < xLeftOver) {
  24792. passWidth++;
  24793. }
  24794. else {
  24795. break;
  24796. }
  24797. }
  24798. for (j = 0; j < pass.y.length; j++) {
  24799. if (pass.y[j] < yLeftOver) {
  24800. passHeight++;
  24801. }
  24802. else {
  24803. break;
  24804. }
  24805. }
  24806. if (passWidth > 0 && passHeight > 0) {
  24807. images.push({ width: passWidth, height: passHeight, index: i });
  24808. }
  24809. }
  24810. return images;
  24811. };
  24812. exports.getInterlaceIterator = function(width) {
  24813. return function(x, y, pass) {
  24814. var outerXLeftOver = x % imagePasses[pass].x.length;
  24815. var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
  24816. var outerYLeftOver = y % imagePasses[pass].y.length;
  24817. var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
  24818. return (outerX * 4) + (outerY * width * 4);
  24819. };
  24820. };
  24821. },{}],300:[function(require,module,exports){
  24822. (function (Buffer){
  24823. 'use strict';
  24824. var util = require('util');
  24825. var Stream = require('stream');
  24826. var constants = require('./constants');
  24827. var Packer = require('./packer');
  24828. var PackerAsync = module.exports = function(opt) {
  24829. Stream.call(this);
  24830. var options = opt || {};
  24831. this._packer = new Packer(options);
  24832. this._deflate = this._packer.createDeflate();
  24833. this.readable = true;
  24834. };
  24835. util.inherits(PackerAsync, Stream);
  24836. PackerAsync.prototype.pack = function(data, width, height, gamma) {
  24837. // Signature
  24838. this.emit('data', new Buffer(constants.PNG_SIGNATURE));
  24839. this.emit('data', this._packer.packIHDR(width, height));
  24840. if (gamma) {
  24841. this.emit('data', this._packer.packGAMA(gamma));
  24842. }
  24843. var filteredData = this._packer.filterData(data, width, height);
  24844. // compress it
  24845. this._deflate.on('error', this.emit.bind(this, 'error'));
  24846. this._deflate.on('data', function(compressedData) {
  24847. this.emit('data', this._packer.packIDAT(compressedData));
  24848. }.bind(this));
  24849. this._deflate.on('end', function() {
  24850. this.emit('data', this._packer.packIEND());
  24851. this.emit('end');
  24852. }.bind(this));
  24853. this._deflate.end(filteredData);
  24854. };
  24855. }).call(this,require("buffer").Buffer)
  24856. },{"./constants":292,"./packer":302,"buffer":47,"stream":334,"util":365}],301:[function(require,module,exports){
  24857. (function (Buffer){
  24858. 'use strict';
  24859. var hasSyncZlib = true;
  24860. var zlib = require('zlib');
  24861. if (!zlib.deflateSync) {
  24862. hasSyncZlib = false;
  24863. }
  24864. var constants = require('./constants');
  24865. var Packer = require('./packer');
  24866. module.exports = function(metaData, opt) {
  24867. if (!hasSyncZlib) {
  24868. throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
  24869. }
  24870. var options = opt || {};
  24871. var packer = new Packer(options);
  24872. var chunks = [];
  24873. // Signature
  24874. chunks.push(new Buffer(constants.PNG_SIGNATURE));
  24875. // Header
  24876. chunks.push(packer.packIHDR(metaData.width, metaData.height));
  24877. if (metaData.gamma) {
  24878. chunks.push(packer.packGAMA(metaData.gamma));
  24879. }
  24880. var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
  24881. // compress it
  24882. var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
  24883. filteredData = null;
  24884. if (!compressedData || !compressedData.length) {
  24885. throw new Error('bad png - invalid compressed data response');
  24886. }
  24887. chunks.push(packer.packIDAT(compressedData));
  24888. // End
  24889. chunks.push(packer.packIEND());
  24890. return Buffer.concat(chunks);
  24891. };
  24892. }).call(this,require("buffer").Buffer)
  24893. },{"./constants":292,"./packer":302,"buffer":47,"zlib":34}],302:[function(require,module,exports){
  24894. (function (Buffer){
  24895. 'use strict';
  24896. var constants = require('./constants');
  24897. var CrcStream = require('./crc');
  24898. var bitPacker = require('./bitpacker');
  24899. var filter = require('./filter-pack');
  24900. var zlib = require('zlib');
  24901. var Packer = module.exports = function(options) {
  24902. this._options = options;
  24903. options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
  24904. options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
  24905. options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
  24906. options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
  24907. options.deflateFactory = options.deflateFactory || zlib.createDeflate;
  24908. options.bitDepth = options.bitDepth || 8;
  24909. // This is outputColorType
  24910. options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
  24911. options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
  24912. if ([
  24913. constants.COLORTYPE_GRAYSCALE,
  24914. constants.COLORTYPE_COLOR,
  24915. constants.COLORTYPE_COLOR_ALPHA,
  24916. constants.COLORTYPE_ALPHA
  24917. ].indexOf(options.colorType) === -1) {
  24918. throw new Error('option color type:' + options.colorType + ' is not supported at present');
  24919. }
  24920. if ([
  24921. constants.COLORTYPE_GRAYSCALE,
  24922. constants.COLORTYPE_COLOR,
  24923. constants.COLORTYPE_COLOR_ALPHA,
  24924. constants.COLORTYPE_ALPHA
  24925. ].indexOf(options.inputColorType) === -1) {
  24926. throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
  24927. }
  24928. if (options.bitDepth !== 8 && options.bitDepth !== 16) {
  24929. throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
  24930. }
  24931. };
  24932. Packer.prototype.getDeflateOptions = function() {
  24933. return {
  24934. chunkSize: this._options.deflateChunkSize,
  24935. level: this._options.deflateLevel,
  24936. strategy: this._options.deflateStrategy
  24937. };
  24938. };
  24939. Packer.prototype.createDeflate = function() {
  24940. return this._options.deflateFactory(this.getDeflateOptions());
  24941. };
  24942. Packer.prototype.filterData = function(data, width, height) {
  24943. // convert to correct format for filtering (e.g. right bpp and bit depth)
  24944. var packedData = bitPacker(data, width, height, this._options);
  24945. // filter pixel data
  24946. var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
  24947. var filteredData = filter(packedData, width, height, this._options, bpp);
  24948. return filteredData;
  24949. };
  24950. Packer.prototype._packChunk = function(type, data) {
  24951. var len = (data ? data.length : 0);
  24952. var buf = new Buffer(len + 12);
  24953. buf.writeUInt32BE(len, 0);
  24954. buf.writeUInt32BE(type, 4);
  24955. if (data) {
  24956. data.copy(buf, 8);
  24957. }
  24958. buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
  24959. return buf;
  24960. };
  24961. Packer.prototype.packGAMA = function(gamma) {
  24962. var buf = new Buffer(4);
  24963. buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
  24964. return this._packChunk(constants.TYPE_gAMA, buf);
  24965. };
  24966. Packer.prototype.packIHDR = function(width, height) {
  24967. var buf = new Buffer(13);
  24968. buf.writeUInt32BE(width, 0);
  24969. buf.writeUInt32BE(height, 4);
  24970. buf[8] = this._options.bitDepth; // Bit depth
  24971. buf[9] = this._options.colorType; // colorType
  24972. buf[10] = 0; // compression
  24973. buf[11] = 0; // filter
  24974. buf[12] = 0; // interlace
  24975. return this._packChunk(constants.TYPE_IHDR, buf);
  24976. };
  24977. Packer.prototype.packIDAT = function(data) {
  24978. return this._packChunk(constants.TYPE_IDAT, data);
  24979. };
  24980. Packer.prototype.packIEND = function() {
  24981. return this._packChunk(constants.TYPE_IEND, null);
  24982. };
  24983. }).call(this,require("buffer").Buffer)
  24984. },{"./bitpacker":290,"./constants":292,"./crc":293,"./filter-pack":294,"buffer":47,"zlib":34}],303:[function(require,module,exports){
  24985. 'use strict';
  24986. module.exports = function paethPredictor(left, above, upLeft) {
  24987. var paeth = left + above - upLeft;
  24988. var pLeft = Math.abs(paeth - left);
  24989. var pAbove = Math.abs(paeth - above);
  24990. var pUpLeft = Math.abs(paeth - upLeft);
  24991. if (pLeft <= pAbove && pLeft <= pUpLeft) {
  24992. return left;
  24993. }
  24994. if (pAbove <= pUpLeft) {
  24995. return above;
  24996. }
  24997. return upLeft;
  24998. };
  24999. },{}],304:[function(require,module,exports){
  25000. 'use strict';
  25001. var util = require('util');
  25002. var zlib = require('zlib');
  25003. var ChunkStream = require('./chunkstream');
  25004. var FilterAsync = require('./filter-parse-async');
  25005. var Parser = require('./parser');
  25006. var bitmapper = require('./bitmapper');
  25007. var formatNormaliser = require('./format-normaliser');
  25008. var ParserAsync = module.exports = function(options) {
  25009. ChunkStream.call(this);
  25010. this._parser = new Parser(options, {
  25011. read: this.read.bind(this),
  25012. error: this._handleError.bind(this),
  25013. metadata: this._handleMetaData.bind(this),
  25014. gamma: this.emit.bind(this, 'gamma'),
  25015. palette: this._handlePalette.bind(this),
  25016. transColor: this._handleTransColor.bind(this),
  25017. finished: this._finished.bind(this),
  25018. inflateData: this._inflateData.bind(this)
  25019. });
  25020. this._options = options;
  25021. this.writable = true;
  25022. this._parser.start();
  25023. };
  25024. util.inherits(ParserAsync, ChunkStream);
  25025. ParserAsync.prototype._handleError = function(err) {
  25026. this.emit('error', err);
  25027. this.writable = false;
  25028. this.destroy();
  25029. if (this._inflate && this._inflate.destroy) {
  25030. this._inflate.destroy();
  25031. }
  25032. if (this._filter) {
  25033. this._filter.destroy();
  25034. // For backward compatibility with Node 7 and below.
  25035. // Suppress errors due to _inflate calling write() even after
  25036. // it's destroy()'ed.
  25037. this._filter.on('error', function() {});
  25038. }
  25039. this.errord = true;
  25040. };
  25041. ParserAsync.prototype._inflateData = function(data) {
  25042. if (!this._inflate) {
  25043. if (this._bitmapInfo.interlace) {
  25044. this._inflate = zlib.createInflate();
  25045. this._inflate.on('error', this.emit.bind(this, 'error'));
  25046. this._filter.on('complete', this._complete.bind(this));
  25047. this._inflate.pipe(this._filter);
  25048. } else {
  25049. var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
  25050. var imageSize = rowSize * this._bitmapInfo.height;
  25051. var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
  25052. this._inflate = zlib.createInflate({ chunkSize: chunkSize });
  25053. var leftToInflate = imageSize;
  25054. var emitError = this.emit.bind(this, 'error');
  25055. this._inflate.on('error', function(err) {
  25056. if (!leftToInflate) {
  25057. return;
  25058. }
  25059. emitError(err);
  25060. });
  25061. this._filter.on('complete', this._complete.bind(this));
  25062. var filterWrite = this._filter.write.bind(this._filter);
  25063. this._inflate.on('data', function(chunk) {
  25064. if (!leftToInflate) {
  25065. return;
  25066. }
  25067. if (chunk.length > leftToInflate) {
  25068. chunk = chunk.slice(0, leftToInflate);
  25069. }
  25070. leftToInflate -= chunk.length;
  25071. filterWrite(chunk);
  25072. });
  25073. this._inflate.on('end', this._filter.end.bind(this._filter));
  25074. }
  25075. }
  25076. this._inflate.write(data);
  25077. };
  25078. ParserAsync.prototype._handleMetaData = function(metaData) {
  25079. this.emit('metadata', metaData);
  25080. this._bitmapInfo = Object.create(metaData);
  25081. this._filter = new FilterAsync(this._bitmapInfo);
  25082. };
  25083. ParserAsync.prototype._handleTransColor = function(transColor) {
  25084. this._bitmapInfo.transColor = transColor;
  25085. };
  25086. ParserAsync.prototype._handlePalette = function(palette) {
  25087. this._bitmapInfo.palette = palette;
  25088. };
  25089. ParserAsync.prototype._finished = function() {
  25090. if (this.errord) {
  25091. return;
  25092. }
  25093. if (!this._inflate) {
  25094. this.emit('error', 'No Inflate block');
  25095. }
  25096. else {
  25097. // no more data to inflate
  25098. this._inflate.end();
  25099. }
  25100. this.destroySoon();
  25101. };
  25102. ParserAsync.prototype._complete = function(filteredData) {
  25103. if (this.errord) {
  25104. return;
  25105. }
  25106. try {
  25107. var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
  25108. var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
  25109. bitmapData = null;
  25110. }
  25111. catch (ex) {
  25112. this._handleError(ex);
  25113. return;
  25114. }
  25115. this.emit('parsed', normalisedBitmapData);
  25116. };
  25117. },{"./bitmapper":289,"./chunkstream":291,"./filter-parse-async":295,"./format-normaliser":298,"./parser":306,"util":365,"zlib":34}],305:[function(require,module,exports){
  25118. (function (Buffer){
  25119. 'use strict';
  25120. var hasSyncZlib = true;
  25121. var zlib = require('zlib');
  25122. var inflateSync = require('./sync-inflate');
  25123. if (!zlib.deflateSync) {
  25124. hasSyncZlib = false;
  25125. }
  25126. var SyncReader = require('./sync-reader');
  25127. var FilterSync = require('./filter-parse-sync');
  25128. var Parser = require('./parser');
  25129. var bitmapper = require('./bitmapper');
  25130. var formatNormaliser = require('./format-normaliser');
  25131. module.exports = function(buffer, options) {
  25132. if (!hasSyncZlib) {
  25133. throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
  25134. }
  25135. var err;
  25136. function handleError(_err_) {
  25137. err = _err_;
  25138. }
  25139. var metaData;
  25140. function handleMetaData(_metaData_) {
  25141. metaData = _metaData_;
  25142. }
  25143. function handleTransColor(transColor) {
  25144. metaData.transColor = transColor;
  25145. }
  25146. function handlePalette(palette) {
  25147. metaData.palette = palette;
  25148. }
  25149. var gamma;
  25150. function handleGamma(_gamma_) {
  25151. gamma = _gamma_;
  25152. }
  25153. var inflateDataList = [];
  25154. function handleInflateData(inflatedData) {
  25155. inflateDataList.push(inflatedData);
  25156. }
  25157. var reader = new SyncReader(buffer);
  25158. var parser = new Parser(options, {
  25159. read: reader.read.bind(reader),
  25160. error: handleError,
  25161. metadata: handleMetaData,
  25162. gamma: handleGamma,
  25163. palette: handlePalette,
  25164. transColor: handleTransColor,
  25165. inflateData: handleInflateData
  25166. });
  25167. parser.start();
  25168. reader.process();
  25169. if (err) {
  25170. throw err;
  25171. }
  25172. //join together the inflate datas
  25173. var inflateData = Buffer.concat(inflateDataList);
  25174. inflateDataList.length = 0;
  25175. var inflatedData;
  25176. if (metaData.interlace) {
  25177. inflatedData = zlib.inflateSync(inflateData);
  25178. } else {
  25179. var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
  25180. var imageSize = rowSize * metaData.height;
  25181. inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
  25182. }
  25183. inflateData = null;
  25184. if (!inflatedData || !inflatedData.length) {
  25185. throw new Error('bad png - invalid inflate data response');
  25186. }
  25187. var unfilteredData = FilterSync.process(inflatedData, metaData);
  25188. inflateData = null;
  25189. var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
  25190. unfilteredData = null;
  25191. var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
  25192. metaData.data = normalisedBitmapData;
  25193. metaData.gamma = gamma || 0;
  25194. return metaData;
  25195. };
  25196. }).call(this,require("buffer").Buffer)
  25197. },{"./bitmapper":289,"./filter-parse-sync":296,"./format-normaliser":298,"./parser":306,"./sync-inflate":309,"./sync-reader":310,"buffer":47,"zlib":34}],306:[function(require,module,exports){
  25198. (function (Buffer){
  25199. 'use strict';
  25200. var constants = require('./constants');
  25201. var CrcCalculator = require('./crc');
  25202. var Parser = module.exports = function(options, dependencies) {
  25203. this._options = options;
  25204. options.checkCRC = options.checkCRC !== false;
  25205. this._hasIHDR = false;
  25206. this._hasIEND = false;
  25207. // input flags/metadata
  25208. this._palette = [];
  25209. this._colorType = 0;
  25210. this._chunks = {};
  25211. this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
  25212. this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
  25213. this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
  25214. this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
  25215. this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
  25216. this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
  25217. this.read = dependencies.read;
  25218. this.error = dependencies.error;
  25219. this.metadata = dependencies.metadata;
  25220. this.gamma = dependencies.gamma;
  25221. this.transColor = dependencies.transColor;
  25222. this.palette = dependencies.palette;
  25223. this.parsed = dependencies.parsed;
  25224. this.inflateData = dependencies.inflateData;
  25225. this.finished = dependencies.finished;
  25226. };
  25227. Parser.prototype.start = function() {
  25228. this.read(constants.PNG_SIGNATURE.length,
  25229. this._parseSignature.bind(this)
  25230. );
  25231. };
  25232. Parser.prototype._parseSignature = function(data) {
  25233. var signature = constants.PNG_SIGNATURE;
  25234. for (var i = 0; i < signature.length; i++) {
  25235. if (data[i] !== signature[i]) {
  25236. this.error(new Error('Invalid file signature'));
  25237. return;
  25238. }
  25239. }
  25240. this.read(8, this._parseChunkBegin.bind(this));
  25241. };
  25242. Parser.prototype._parseChunkBegin = function(data) {
  25243. // chunk content length
  25244. var length = data.readUInt32BE(0);
  25245. // chunk type
  25246. var type = data.readUInt32BE(4);
  25247. var name = '';
  25248. for (var i = 4; i < 8; i++) {
  25249. name += String.fromCharCode(data[i]);
  25250. }
  25251. //console.log('chunk ', name, length);
  25252. // chunk flags
  25253. var ancillary = Boolean(data[4] & 0x20); // or critical
  25254. // priv = Boolean(data[5] & 0x20), // or public
  25255. // safeToCopy = Boolean(data[7] & 0x20); // or unsafe
  25256. if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
  25257. this.error(new Error('Expected IHDR on beggining'));
  25258. return;
  25259. }
  25260. this._crc = new CrcCalculator();
  25261. this._crc.write(new Buffer(name));
  25262. if (this._chunks[type]) {
  25263. return this._chunks[type](length);
  25264. }
  25265. if (!ancillary) {
  25266. this.error(new Error('Unsupported critical chunk type ' + name));
  25267. return;
  25268. }
  25269. this.read(length + 4, this._skipChunk.bind(this));
  25270. };
  25271. Parser.prototype._skipChunk = function(/*data*/) {
  25272. this.read(8, this._parseChunkBegin.bind(this));
  25273. };
  25274. Parser.prototype._handleChunkEnd = function() {
  25275. this.read(4, this._parseChunkEnd.bind(this));
  25276. };
  25277. Parser.prototype._parseChunkEnd = function(data) {
  25278. var fileCrc = data.readInt32BE(0);
  25279. var calcCrc = this._crc.crc32();
  25280. // check CRC
  25281. if (this._options.checkCRC && calcCrc !== fileCrc) {
  25282. this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
  25283. return;
  25284. }
  25285. if (!this._hasIEND) {
  25286. this.read(8, this._parseChunkBegin.bind(this));
  25287. }
  25288. };
  25289. Parser.prototype._handleIHDR = function(length) {
  25290. this.read(length, this._parseIHDR.bind(this));
  25291. };
  25292. Parser.prototype._parseIHDR = function(data) {
  25293. this._crc.write(data);
  25294. var width = data.readUInt32BE(0);
  25295. var height = data.readUInt32BE(4);
  25296. var depth = data[8];
  25297. var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
  25298. var compr = data[10];
  25299. var filter = data[11];
  25300. var interlace = data[12];
  25301. // console.log(' width', width, 'height', height,
  25302. // 'depth', depth, 'colorType', colorType,
  25303. // 'compr', compr, 'filter', filter, 'interlace', interlace
  25304. // );
  25305. if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
  25306. this.error(new Error('Unsupported bit depth ' + depth));
  25307. return;
  25308. }
  25309. if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
  25310. this.error(new Error('Unsupported color type'));
  25311. return;
  25312. }
  25313. if (compr !== 0) {
  25314. this.error(new Error('Unsupported compression method'));
  25315. return;
  25316. }
  25317. if (filter !== 0) {
  25318. this.error(new Error('Unsupported filter method'));
  25319. return;
  25320. }
  25321. if (interlace !== 0 && interlace !== 1) {
  25322. this.error(new Error('Unsupported interlace method'));
  25323. return;
  25324. }
  25325. this._colorType = colorType;
  25326. var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
  25327. this._hasIHDR = true;
  25328. this.metadata({
  25329. width: width,
  25330. height: height,
  25331. depth: depth,
  25332. interlace: Boolean(interlace),
  25333. palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
  25334. color: Boolean(colorType & constants.COLORTYPE_COLOR),
  25335. alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
  25336. bpp: bpp,
  25337. colorType: colorType
  25338. });
  25339. this._handleChunkEnd();
  25340. };
  25341. Parser.prototype._handlePLTE = function(length) {
  25342. this.read(length, this._parsePLTE.bind(this));
  25343. };
  25344. Parser.prototype._parsePLTE = function(data) {
  25345. this._crc.write(data);
  25346. var entries = Math.floor(data.length / 3);
  25347. // console.log('Palette:', entries);
  25348. for (var i = 0; i < entries; i++) {
  25349. this._palette.push([
  25350. data[i * 3],
  25351. data[i * 3 + 1],
  25352. data[i * 3 + 2],
  25353. 0xff
  25354. ]);
  25355. }
  25356. this.palette(this._palette);
  25357. this._handleChunkEnd();
  25358. };
  25359. Parser.prototype._handleTRNS = function(length) {
  25360. this.read(length, this._parseTRNS.bind(this));
  25361. };
  25362. Parser.prototype._parseTRNS = function(data) {
  25363. this._crc.write(data);
  25364. // palette
  25365. if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
  25366. if (this._palette.length === 0) {
  25367. this.error(new Error('Transparency chunk must be after palette'));
  25368. return;
  25369. }
  25370. if (data.length > this._palette.length) {
  25371. this.error(new Error('More transparent colors than palette size'));
  25372. return;
  25373. }
  25374. for (var i = 0; i < data.length; i++) {
  25375. this._palette[i][3] = data[i];
  25376. }
  25377. this.palette(this._palette);
  25378. }
  25379. // for colorType 0 (grayscale) and 2 (rgb)
  25380. // there might be one gray/color defined as transparent
  25381. if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
  25382. // grey, 2 bytes
  25383. this.transColor([data.readUInt16BE(0)]);
  25384. }
  25385. if (this._colorType === constants.COLORTYPE_COLOR) {
  25386. this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
  25387. }
  25388. this._handleChunkEnd();
  25389. };
  25390. Parser.prototype._handleGAMA = function(length) {
  25391. this.read(length, this._parseGAMA.bind(this));
  25392. };
  25393. Parser.prototype._parseGAMA = function(data) {
  25394. this._crc.write(data);
  25395. this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
  25396. this._handleChunkEnd();
  25397. };
  25398. Parser.prototype._handleIDAT = function(length) {
  25399. this.read(-length, this._parseIDAT.bind(this, length));
  25400. };
  25401. Parser.prototype._parseIDAT = function(length, data) {
  25402. this._crc.write(data);
  25403. if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
  25404. throw new Error('Expected palette not found');
  25405. }
  25406. this.inflateData(data);
  25407. var leftOverLength = length - data.length;
  25408. if (leftOverLength > 0) {
  25409. this._handleIDAT(leftOverLength);
  25410. }
  25411. else {
  25412. this._handleChunkEnd();
  25413. }
  25414. };
  25415. Parser.prototype._handleIEND = function(length) {
  25416. this.read(length, this._parseIEND.bind(this));
  25417. };
  25418. Parser.prototype._parseIEND = function(data) {
  25419. this._crc.write(data);
  25420. this._hasIEND = true;
  25421. this._handleChunkEnd();
  25422. if (this.finished) {
  25423. this.finished();
  25424. }
  25425. };
  25426. }).call(this,require("buffer").Buffer)
  25427. },{"./constants":292,"./crc":293,"buffer":47}],307:[function(require,module,exports){
  25428. 'use strict';
  25429. var parse = require('./parser-sync');
  25430. var pack = require('./packer-sync');
  25431. exports.read = function(buffer, options) {
  25432. return parse(buffer, options || {});
  25433. };
  25434. exports.write = function(png, options) {
  25435. return pack(png, options);
  25436. };
  25437. },{"./packer-sync":301,"./parser-sync":305}],308:[function(require,module,exports){
  25438. (function (process,Buffer){
  25439. 'use strict';
  25440. var util = require('util');
  25441. var Stream = require('stream');
  25442. var Parser = require('./parser-async');
  25443. var Packer = require('./packer-async');
  25444. var PNGSync = require('./png-sync');
  25445. var PNG = exports.PNG = function(options) {
  25446. Stream.call(this);
  25447. options = options || {}; // eslint-disable-line no-param-reassign
  25448. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  25449. this.width = options.width | 0;
  25450. this.height = options.height | 0;
  25451. this.data = this.width > 0 && this.height > 0 ?
  25452. new Buffer(4 * this.width * this.height) : null;
  25453. if (options.fill && this.data) {
  25454. this.data.fill(0);
  25455. }
  25456. this.gamma = 0;
  25457. this.readable = this.writable = true;
  25458. this._parser = new Parser(options);
  25459. this._parser.on('error', this.emit.bind(this, 'error'));
  25460. this._parser.on('close', this._handleClose.bind(this));
  25461. this._parser.on('metadata', this._metadata.bind(this));
  25462. this._parser.on('gamma', this._gamma.bind(this));
  25463. this._parser.on('parsed', function(data) {
  25464. this.data = data;
  25465. this.emit('parsed', data);
  25466. }.bind(this));
  25467. this._packer = new Packer(options);
  25468. this._packer.on('data', this.emit.bind(this, 'data'));
  25469. this._packer.on('end', this.emit.bind(this, 'end'));
  25470. this._parser.on('close', this._handleClose.bind(this));
  25471. this._packer.on('error', this.emit.bind(this, 'error'));
  25472. };
  25473. util.inherits(PNG, Stream);
  25474. PNG.sync = PNGSync;
  25475. PNG.prototype.pack = function() {
  25476. if (!this.data || !this.data.length) {
  25477. this.emit('error', 'No data provided');
  25478. return this;
  25479. }
  25480. process.nextTick(function() {
  25481. this._packer.pack(this.data, this.width, this.height, this.gamma);
  25482. }.bind(this));
  25483. return this;
  25484. };
  25485. PNG.prototype.parse = function(data, callback) {
  25486. if (callback) {
  25487. var onParsed, onError;
  25488. onParsed = function(parsedData) {
  25489. this.removeListener('error', onError);
  25490. this.data = parsedData;
  25491. callback(null, this);
  25492. }.bind(this);
  25493. onError = function(err) {
  25494. this.removeListener('parsed', onParsed);
  25495. callback(err, null);
  25496. }.bind(this);
  25497. this.once('parsed', onParsed);
  25498. this.once('error', onError);
  25499. }
  25500. this.end(data);
  25501. return this;
  25502. };
  25503. PNG.prototype.write = function(data) {
  25504. this._parser.write(data);
  25505. return true;
  25506. };
  25507. PNG.prototype.end = function(data) {
  25508. this._parser.end(data);
  25509. };
  25510. PNG.prototype._metadata = function(metadata) {
  25511. this.width = metadata.width;
  25512. this.height = metadata.height;
  25513. this.emit('metadata', metadata);
  25514. };
  25515. PNG.prototype._gamma = function(gamma) {
  25516. this.gamma = gamma;
  25517. };
  25518. PNG.prototype._handleClose = function() {
  25519. if (!this._parser.writable && !this._packer.readable) {
  25520. this.emit('close');
  25521. }
  25522. };
  25523. PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
  25524. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  25525. /* eslint-disable no-param-reassign */
  25526. srcX |= 0;
  25527. srcY |= 0;
  25528. width |= 0;
  25529. height |= 0;
  25530. deltaX |= 0;
  25531. deltaY |= 0;
  25532. /* eslint-enable no-param-reassign */
  25533. if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
  25534. throw new Error('bitblt reading outside image');
  25535. }
  25536. if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
  25537. throw new Error('bitblt writing outside image');
  25538. }
  25539. for (var y = 0; y < height; y++) {
  25540. src.data.copy(dst.data,
  25541. ((deltaY + y) * dst.width + deltaX) << 2,
  25542. ((srcY + y) * src.width + srcX) << 2,
  25543. ((srcY + y) * src.width + srcX + width) << 2
  25544. );
  25545. }
  25546. };
  25547. PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
  25548. PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
  25549. return this;
  25550. };
  25551. PNG.adjustGamma = function(src) {
  25552. if (src.gamma) {
  25553. for (var y = 0; y < src.height; y++) {
  25554. for (var x = 0; x < src.width; x++) {
  25555. var idx = (src.width * y + x) << 2;
  25556. for (var i = 0; i < 3; i++) {
  25557. var sample = src.data[idx + i] / 255;
  25558. sample = Math.pow(sample, 1 / 2.2 / src.gamma);
  25559. src.data[idx + i] = Math.round(sample * 255);
  25560. }
  25561. }
  25562. }
  25563. src.gamma = 0;
  25564. }
  25565. };
  25566. PNG.prototype.adjustGamma = function() {
  25567. PNG.adjustGamma(this);
  25568. };
  25569. }).call(this,require('_process'),require("buffer").Buffer)
  25570. },{"./packer-async":300,"./parser-async":304,"./png-sync":307,"_process":312,"buffer":47,"stream":334,"util":365}],309:[function(require,module,exports){
  25571. (function (process,Buffer){
  25572. 'use strict';
  25573. var assert = require('assert').ok;
  25574. var zlib = require('zlib');
  25575. var util = require('util');
  25576. var kMaxLength = require('buffer').kMaxLength;
  25577. function Inflate(opts) {
  25578. if (!(this instanceof Inflate)) {
  25579. return new Inflate(opts);
  25580. }
  25581. if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
  25582. opts.chunkSize = zlib.Z_MIN_CHUNK;
  25583. }
  25584. zlib.Inflate.call(this, opts);
  25585. // Node 8 --> 9 compatibility check
  25586. this._offset = this._offset === undefined ? this._outOffset : this._offset;
  25587. this._buffer = this._buffer || this._outBuffer;
  25588. if (opts && opts.maxLength != null) {
  25589. this._maxLength = opts.maxLength;
  25590. }
  25591. }
  25592. function createInflate(opts) {
  25593. return new Inflate(opts);
  25594. }
  25595. function _close(engine, callback) {
  25596. if (callback) {
  25597. process.nextTick(callback);
  25598. }
  25599. // Caller may invoke .close after a zlib error (which will null _handle).
  25600. if (!engine._handle) {
  25601. return;
  25602. }
  25603. engine._handle.close();
  25604. engine._handle = null;
  25605. }
  25606. Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
  25607. if (typeof asyncCb === 'function') {
  25608. return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
  25609. }
  25610. var self = this;
  25611. var availInBefore = chunk && chunk.length;
  25612. var availOutBefore = this._chunkSize - this._offset;
  25613. var leftToInflate = this._maxLength;
  25614. var inOff = 0;
  25615. var buffers = [];
  25616. var nread = 0;
  25617. var error;
  25618. this.on('error', function(err) {
  25619. error = err;
  25620. });
  25621. function handleChunk(availInAfter, availOutAfter) {
  25622. if (self._hadError) {
  25623. return;
  25624. }
  25625. var have = availOutBefore - availOutAfter;
  25626. assert(have >= 0, 'have should not go down');
  25627. if (have > 0) {
  25628. var out = self._buffer.slice(self._offset, self._offset + have);
  25629. self._offset += have;
  25630. if (out.length > leftToInflate) {
  25631. out = out.slice(0, leftToInflate);
  25632. }
  25633. buffers.push(out);
  25634. nread += out.length;
  25635. leftToInflate -= out.length;
  25636. if (leftToInflate === 0) {
  25637. return false;
  25638. }
  25639. }
  25640. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  25641. availOutBefore = self._chunkSize;
  25642. self._offset = 0;
  25643. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  25644. }
  25645. if (availOutAfter === 0) {
  25646. inOff += (availInBefore - availInAfter);
  25647. availInBefore = availInAfter;
  25648. return true;
  25649. }
  25650. return false;
  25651. }
  25652. assert(this._handle, 'zlib binding closed');
  25653. do {
  25654. var res = this._handle.writeSync(flushFlag,
  25655. chunk, // in
  25656. inOff, // in_off
  25657. availInBefore, // in_len
  25658. this._buffer, // out
  25659. this._offset, //out_off
  25660. availOutBefore); // out_len
  25661. // Node 8 --> 9 compatibility check
  25662. res = res || this._writeState;
  25663. } while (!this._hadError && handleChunk(res[0], res[1]));
  25664. if (this._hadError) {
  25665. throw error;
  25666. }
  25667. if (nread >= kMaxLength) {
  25668. _close(this);
  25669. throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
  25670. }
  25671. var buf = Buffer.concat(buffers, nread);
  25672. _close(this);
  25673. return buf;
  25674. };
  25675. util.inherits(Inflate, zlib.Inflate);
  25676. function zlibBufferSync(engine, buffer) {
  25677. if (typeof buffer === 'string') {
  25678. buffer = Buffer.from(buffer);
  25679. }
  25680. if (!(buffer instanceof Buffer)) {
  25681. throw new TypeError('Not a string or buffer');
  25682. }
  25683. var flushFlag = engine._finishFlushFlag;
  25684. if (flushFlag == null) {
  25685. flushFlag = zlib.Z_FINISH;
  25686. }
  25687. return engine._processChunk(buffer, flushFlag);
  25688. }
  25689. function inflateSync(buffer, opts) {
  25690. return zlibBufferSync(new Inflate(opts), buffer);
  25691. }
  25692. module.exports = exports = inflateSync;
  25693. exports.Inflate = Inflate;
  25694. exports.createInflate = createInflate;
  25695. exports.inflateSync = inflateSync;
  25696. }).call(this,require('_process'),require("buffer").Buffer)
  25697. },{"_process":312,"assert":24,"buffer":47,"util":365,"zlib":34}],310:[function(require,module,exports){
  25698. 'use strict';
  25699. var SyncReader = module.exports = function(buffer) {
  25700. this._buffer = buffer;
  25701. this._reads = [];
  25702. };
  25703. SyncReader.prototype.read = function(length, callback) {
  25704. this._reads.push({
  25705. length: Math.abs(length), // if length < 0 then at most this length
  25706. allowLess: length < 0,
  25707. func: callback
  25708. });
  25709. };
  25710. SyncReader.prototype.process = function() {
  25711. // as long as there is any data and read requests
  25712. while (this._reads.length > 0 && this._buffer.length) {
  25713. var read = this._reads[0];
  25714. if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
  25715. // ok there is any data so that we can satisfy this request
  25716. this._reads.shift(); // == read
  25717. var buf = this._buffer;
  25718. this._buffer = buf.slice(read.length);
  25719. read.func.call(this, buf.slice(0, read.length));
  25720. }
  25721. else {
  25722. break;
  25723. }
  25724. }
  25725. if (this._reads.length > 0) {
  25726. return new Error('There are some read requests waitng on finished stream');
  25727. }
  25728. if (this._buffer.length > 0) {
  25729. return new Error('unrecognised content at end of stream');
  25730. }
  25731. };
  25732. },{}],311:[function(require,module,exports){
  25733. (function (process){
  25734. 'use strict';
  25735. if (typeof process === 'undefined' ||
  25736. !process.version ||
  25737. process.version.indexOf('v0.') === 0 ||
  25738. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  25739. module.exports = { nextTick: nextTick };
  25740. } else {
  25741. module.exports = process
  25742. }
  25743. function nextTick(fn, arg1, arg2, arg3) {
  25744. if (typeof fn !== 'function') {
  25745. throw new TypeError('"callback" argument must be a function');
  25746. }
  25747. var len = arguments.length;
  25748. var args, i;
  25749. switch (len) {
  25750. case 0:
  25751. case 1:
  25752. return process.nextTick(fn);
  25753. case 2:
  25754. return process.nextTick(function afterTickOne() {
  25755. fn.call(null, arg1);
  25756. });
  25757. case 3:
  25758. return process.nextTick(function afterTickTwo() {
  25759. fn.call(null, arg1, arg2);
  25760. });
  25761. case 4:
  25762. return process.nextTick(function afterTickThree() {
  25763. fn.call(null, arg1, arg2, arg3);
  25764. });
  25765. default:
  25766. args = new Array(len - 1);
  25767. i = 0;
  25768. while (i < args.length) {
  25769. args[i++] = arguments[i];
  25770. }
  25771. return process.nextTick(function afterTick() {
  25772. fn.apply(null, args);
  25773. });
  25774. }
  25775. }
  25776. }).call(this,require('_process'))
  25777. },{"_process":312}],312:[function(require,module,exports){
  25778. // shim for using process in browser
  25779. var process = module.exports = {};
  25780. // cached from whatever global is present so that test runners that stub it
  25781. // don't break things. But we need to wrap it in a try catch in case it is
  25782. // wrapped in strict mode code which doesn't define any globals. It's inside a
  25783. // function because try/catches deoptimize in certain engines.
  25784. var cachedSetTimeout;
  25785. var cachedClearTimeout;
  25786. function defaultSetTimout() {
  25787. throw new Error('setTimeout has not been defined');
  25788. }
  25789. function defaultClearTimeout () {
  25790. throw new Error('clearTimeout has not been defined');
  25791. }
  25792. (function () {
  25793. try {
  25794. if (typeof setTimeout === 'function') {
  25795. cachedSetTimeout = setTimeout;
  25796. } else {
  25797. cachedSetTimeout = defaultSetTimout;
  25798. }
  25799. } catch (e) {
  25800. cachedSetTimeout = defaultSetTimout;
  25801. }
  25802. try {
  25803. if (typeof clearTimeout === 'function') {
  25804. cachedClearTimeout = clearTimeout;
  25805. } else {
  25806. cachedClearTimeout = defaultClearTimeout;
  25807. }
  25808. } catch (e) {
  25809. cachedClearTimeout = defaultClearTimeout;
  25810. }
  25811. } ())
  25812. function runTimeout(fun) {
  25813. if (cachedSetTimeout === setTimeout) {
  25814. //normal enviroments in sane situations
  25815. return setTimeout(fun, 0);
  25816. }
  25817. // if setTimeout wasn't available but was latter defined
  25818. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  25819. cachedSetTimeout = setTimeout;
  25820. return setTimeout(fun, 0);
  25821. }
  25822. try {
  25823. // when when somebody has screwed with setTimeout but no I.E. maddness
  25824. return cachedSetTimeout(fun, 0);
  25825. } catch(e){
  25826. try {
  25827. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  25828. return cachedSetTimeout.call(null, fun, 0);
  25829. } catch(e){
  25830. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  25831. return cachedSetTimeout.call(this, fun, 0);
  25832. }
  25833. }
  25834. }
  25835. function runClearTimeout(marker) {
  25836. if (cachedClearTimeout === clearTimeout) {
  25837. //normal enviroments in sane situations
  25838. return clearTimeout(marker);
  25839. }
  25840. // if clearTimeout wasn't available but was latter defined
  25841. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  25842. cachedClearTimeout = clearTimeout;
  25843. return clearTimeout(marker);
  25844. }
  25845. try {
  25846. // when when somebody has screwed with setTimeout but no I.E. maddness
  25847. return cachedClearTimeout(marker);
  25848. } catch (e){
  25849. try {
  25850. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  25851. return cachedClearTimeout.call(null, marker);
  25852. } catch (e){
  25853. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  25854. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  25855. return cachedClearTimeout.call(this, marker);
  25856. }
  25857. }
  25858. }
  25859. var queue = [];
  25860. var draining = false;
  25861. var currentQueue;
  25862. var queueIndex = -1;
  25863. function cleanUpNextTick() {
  25864. if (!draining || !currentQueue) {
  25865. return;
  25866. }
  25867. draining = false;
  25868. if (currentQueue.length) {
  25869. queue = currentQueue.concat(queue);
  25870. } else {
  25871. queueIndex = -1;
  25872. }
  25873. if (queue.length) {
  25874. drainQueue();
  25875. }
  25876. }
  25877. function drainQueue() {
  25878. if (draining) {
  25879. return;
  25880. }
  25881. var timeout = runTimeout(cleanUpNextTick);
  25882. draining = true;
  25883. var len = queue.length;
  25884. while(len) {
  25885. currentQueue = queue;
  25886. queue = [];
  25887. while (++queueIndex < len) {
  25888. if (currentQueue) {
  25889. currentQueue[queueIndex].run();
  25890. }
  25891. }
  25892. queueIndex = -1;
  25893. len = queue.length;
  25894. }
  25895. currentQueue = null;
  25896. draining = false;
  25897. runClearTimeout(timeout);
  25898. }
  25899. process.nextTick = function (fun) {
  25900. var args = new Array(arguments.length - 1);
  25901. if (arguments.length > 1) {
  25902. for (var i = 1; i < arguments.length; i++) {
  25903. args[i - 1] = arguments[i];
  25904. }
  25905. }
  25906. queue.push(new Item(fun, args));
  25907. if (queue.length === 1 && !draining) {
  25908. runTimeout(drainQueue);
  25909. }
  25910. };
  25911. // v8 likes predictible objects
  25912. function Item(fun, array) {
  25913. this.fun = fun;
  25914. this.array = array;
  25915. }
  25916. Item.prototype.run = function () {
  25917. this.fun.apply(null, this.array);
  25918. };
  25919. process.title = 'browser';
  25920. process.browser = true;
  25921. process.env = {};
  25922. process.argv = [];
  25923. process.version = ''; // empty string to avoid regexp issues
  25924. process.versions = {};
  25925. function noop() {}
  25926. process.on = noop;
  25927. process.addListener = noop;
  25928. process.once = noop;
  25929. process.off = noop;
  25930. process.removeListener = noop;
  25931. process.removeAllListeners = noop;
  25932. process.emit = noop;
  25933. process.prependListener = noop;
  25934. process.prependOnceListener = noop;
  25935. process.listeners = function (name) { return [] }
  25936. process.binding = function (name) {
  25937. throw new Error('process.binding is not supported');
  25938. };
  25939. process.cwd = function () { return '/' };
  25940. process.chdir = function (dir) {
  25941. throw new Error('process.chdir is not supported');
  25942. };
  25943. process.umask = function() { return 0; };
  25944. },{}],313:[function(require,module,exports){
  25945. (function (global){
  25946. /*! https://mths.be/punycode v1.4.1 by @mathias */
  25947. ;(function(root) {
  25948. /** Detect free variables */
  25949. var freeExports = typeof exports == 'object' && exports &&
  25950. !exports.nodeType && exports;
  25951. var freeModule = typeof module == 'object' && module &&
  25952. !module.nodeType && module;
  25953. var freeGlobal = typeof global == 'object' && global;
  25954. if (
  25955. freeGlobal.global === freeGlobal ||
  25956. freeGlobal.window === freeGlobal ||
  25957. freeGlobal.self === freeGlobal
  25958. ) {
  25959. root = freeGlobal;
  25960. }
  25961. /**
  25962. * The `punycode` object.
  25963. * @name punycode
  25964. * @type Object
  25965. */
  25966. var punycode,
  25967. /** Highest positive signed 32-bit float value */
  25968. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  25969. /** Bootstring parameters */
  25970. base = 36,
  25971. tMin = 1,
  25972. tMax = 26,
  25973. skew = 38,
  25974. damp = 700,
  25975. initialBias = 72,
  25976. initialN = 128, // 0x80
  25977. delimiter = '-', // '\x2D'
  25978. /** Regular expressions */
  25979. regexPunycode = /^xn--/,
  25980. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  25981. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  25982. /** Error messages */
  25983. errors = {
  25984. 'overflow': 'Overflow: input needs wider integers to process',
  25985. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  25986. 'invalid-input': 'Invalid input'
  25987. },
  25988. /** Convenience shortcuts */
  25989. baseMinusTMin = base - tMin,
  25990. floor = Math.floor,
  25991. stringFromCharCode = String.fromCharCode,
  25992. /** Temporary variable */
  25993. key;
  25994. /*--------------------------------------------------------------------------*/
  25995. /**
  25996. * A generic error utility function.
  25997. * @private
  25998. * @param {String} type The error type.
  25999. * @returns {Error} Throws a `RangeError` with the applicable error message.
  26000. */
  26001. function error(type) {
  26002. throw new RangeError(errors[type]);
  26003. }
  26004. /**
  26005. * A generic `Array#map` utility function.
  26006. * @private
  26007. * @param {Array} array The array to iterate over.
  26008. * @param {Function} callback The function that gets called for every array
  26009. * item.
  26010. * @returns {Array} A new array of values returned by the callback function.
  26011. */
  26012. function map(array, fn) {
  26013. var length = array.length;
  26014. var result = [];
  26015. while (length--) {
  26016. result[length] = fn(array[length]);
  26017. }
  26018. return result;
  26019. }
  26020. /**
  26021. * A simple `Array#map`-like wrapper to work with domain name strings or email
  26022. * addresses.
  26023. * @private
  26024. * @param {String} domain The domain name or email address.
  26025. * @param {Function} callback The function that gets called for every
  26026. * character.
  26027. * @returns {Array} A new string of characters returned by the callback
  26028. * function.
  26029. */
  26030. function mapDomain(string, fn) {
  26031. var parts = string.split('@');
  26032. var result = '';
  26033. if (parts.length > 1) {
  26034. // In email addresses, only the domain name should be punycoded. Leave
  26035. // the local part (i.e. everything up to `@`) intact.
  26036. result = parts[0] + '@';
  26037. string = parts[1];
  26038. }
  26039. // Avoid `split(regex)` for IE8 compatibility. See #17.
  26040. string = string.replace(regexSeparators, '\x2E');
  26041. var labels = string.split('.');
  26042. var encoded = map(labels, fn).join('.');
  26043. return result + encoded;
  26044. }
  26045. /**
  26046. * Creates an array containing the numeric code points of each Unicode
  26047. * character in the string. While JavaScript uses UCS-2 internally,
  26048. * this function will convert a pair of surrogate halves (each of which
  26049. * UCS-2 exposes as separate characters) into a single code point,
  26050. * matching UTF-16.
  26051. * @see `punycode.ucs2.encode`
  26052. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  26053. * @memberOf punycode.ucs2
  26054. * @name decode
  26055. * @param {String} string The Unicode input string (UCS-2).
  26056. * @returns {Array} The new array of code points.
  26057. */
  26058. function ucs2decode(string) {
  26059. var output = [],
  26060. counter = 0,
  26061. length = string.length,
  26062. value,
  26063. extra;
  26064. while (counter < length) {
  26065. value = string.charCodeAt(counter++);
  26066. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  26067. // high surrogate, and there is a next character
  26068. extra = string.charCodeAt(counter++);
  26069. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  26070. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  26071. } else {
  26072. // unmatched surrogate; only append this code unit, in case the next
  26073. // code unit is the high surrogate of a surrogate pair
  26074. output.push(value);
  26075. counter--;
  26076. }
  26077. } else {
  26078. output.push(value);
  26079. }
  26080. }
  26081. return output;
  26082. }
  26083. /**
  26084. * Creates a string based on an array of numeric code points.
  26085. * @see `punycode.ucs2.decode`
  26086. * @memberOf punycode.ucs2
  26087. * @name encode
  26088. * @param {Array} codePoints The array of numeric code points.
  26089. * @returns {String} The new Unicode string (UCS-2).
  26090. */
  26091. function ucs2encode(array) {
  26092. return map(array, function(value) {
  26093. var output = '';
  26094. if (value > 0xFFFF) {
  26095. value -= 0x10000;
  26096. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  26097. value = 0xDC00 | value & 0x3FF;
  26098. }
  26099. output += stringFromCharCode(value);
  26100. return output;
  26101. }).join('');
  26102. }
  26103. /**
  26104. * Converts a basic code point into a digit/integer.
  26105. * @see `digitToBasic()`
  26106. * @private
  26107. * @param {Number} codePoint The basic numeric code point value.
  26108. * @returns {Number} The numeric value of a basic code point (for use in
  26109. * representing integers) in the range `0` to `base - 1`, or `base` if
  26110. * the code point does not represent a value.
  26111. */
  26112. function basicToDigit(codePoint) {
  26113. if (codePoint - 48 < 10) {
  26114. return codePoint - 22;
  26115. }
  26116. if (codePoint - 65 < 26) {
  26117. return codePoint - 65;
  26118. }
  26119. if (codePoint - 97 < 26) {
  26120. return codePoint - 97;
  26121. }
  26122. return base;
  26123. }
  26124. /**
  26125. * Converts a digit/integer into a basic code point.
  26126. * @see `basicToDigit()`
  26127. * @private
  26128. * @param {Number} digit The numeric value of a basic code point.
  26129. * @returns {Number} The basic code point whose value (when used for
  26130. * representing integers) is `digit`, which needs to be in the range
  26131. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  26132. * used; else, the lowercase form is used. The behavior is undefined
  26133. * if `flag` is non-zero and `digit` has no uppercase form.
  26134. */
  26135. function digitToBasic(digit, flag) {
  26136. // 0..25 map to ASCII a..z or A..Z
  26137. // 26..35 map to ASCII 0..9
  26138. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  26139. }
  26140. /**
  26141. * Bias adaptation function as per section 3.4 of RFC 3492.
  26142. * https://tools.ietf.org/html/rfc3492#section-3.4
  26143. * @private
  26144. */
  26145. function adapt(delta, numPoints, firstTime) {
  26146. var k = 0;
  26147. delta = firstTime ? floor(delta / damp) : delta >> 1;
  26148. delta += floor(delta / numPoints);
  26149. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  26150. delta = floor(delta / baseMinusTMin);
  26151. }
  26152. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  26153. }
  26154. /**
  26155. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  26156. * symbols.
  26157. * @memberOf punycode
  26158. * @param {String} input The Punycode string of ASCII-only symbols.
  26159. * @returns {String} The resulting string of Unicode symbols.
  26160. */
  26161. function decode(input) {
  26162. // Don't use UCS-2
  26163. var output = [],
  26164. inputLength = input.length,
  26165. out,
  26166. i = 0,
  26167. n = initialN,
  26168. bias = initialBias,
  26169. basic,
  26170. j,
  26171. index,
  26172. oldi,
  26173. w,
  26174. k,
  26175. digit,
  26176. t,
  26177. /** Cached calculation results */
  26178. baseMinusT;
  26179. // Handle the basic code points: let `basic` be the number of input code
  26180. // points before the last delimiter, or `0` if there is none, then copy
  26181. // the first basic code points to the output.
  26182. basic = input.lastIndexOf(delimiter);
  26183. if (basic < 0) {
  26184. basic = 0;
  26185. }
  26186. for (j = 0; j < basic; ++j) {
  26187. // if it's not a basic code point
  26188. if (input.charCodeAt(j) >= 0x80) {
  26189. error('not-basic');
  26190. }
  26191. output.push(input.charCodeAt(j));
  26192. }
  26193. // Main decoding loop: start just after the last delimiter if any basic code
  26194. // points were copied; start at the beginning otherwise.
  26195. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  26196. // `index` is the index of the next character to be consumed.
  26197. // Decode a generalized variable-length integer into `delta`,
  26198. // which gets added to `i`. The overflow checking is easier
  26199. // if we increase `i` as we go, then subtract off its starting
  26200. // value at the end to obtain `delta`.
  26201. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  26202. if (index >= inputLength) {
  26203. error('invalid-input');
  26204. }
  26205. digit = basicToDigit(input.charCodeAt(index++));
  26206. if (digit >= base || digit > floor((maxInt - i) / w)) {
  26207. error('overflow');
  26208. }
  26209. i += digit * w;
  26210. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  26211. if (digit < t) {
  26212. break;
  26213. }
  26214. baseMinusT = base - t;
  26215. if (w > floor(maxInt / baseMinusT)) {
  26216. error('overflow');
  26217. }
  26218. w *= baseMinusT;
  26219. }
  26220. out = output.length + 1;
  26221. bias = adapt(i - oldi, out, oldi == 0);
  26222. // `i` was supposed to wrap around from `out` to `0`,
  26223. // incrementing `n` each time, so we'll fix that now:
  26224. if (floor(i / out) > maxInt - n) {
  26225. error('overflow');
  26226. }
  26227. n += floor(i / out);
  26228. i %= out;
  26229. // Insert `n` at position `i` of the output
  26230. output.splice(i++, 0, n);
  26231. }
  26232. return ucs2encode(output);
  26233. }
  26234. /**
  26235. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  26236. * Punycode string of ASCII-only symbols.
  26237. * @memberOf punycode
  26238. * @param {String} input The string of Unicode symbols.
  26239. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  26240. */
  26241. function encode(input) {
  26242. var n,
  26243. delta,
  26244. handledCPCount,
  26245. basicLength,
  26246. bias,
  26247. j,
  26248. m,
  26249. q,
  26250. k,
  26251. t,
  26252. currentValue,
  26253. output = [],
  26254. /** `inputLength` will hold the number of code points in `input`. */
  26255. inputLength,
  26256. /** Cached calculation results */
  26257. handledCPCountPlusOne,
  26258. baseMinusT,
  26259. qMinusT;
  26260. // Convert the input in UCS-2 to Unicode
  26261. input = ucs2decode(input);
  26262. // Cache the length
  26263. inputLength = input.length;
  26264. // Initialize the state
  26265. n = initialN;
  26266. delta = 0;
  26267. bias = initialBias;
  26268. // Handle the basic code points
  26269. for (j = 0; j < inputLength; ++j) {
  26270. currentValue = input[j];
  26271. if (currentValue < 0x80) {
  26272. output.push(stringFromCharCode(currentValue));
  26273. }
  26274. }
  26275. handledCPCount = basicLength = output.length;
  26276. // `handledCPCount` is the number of code points that have been handled;
  26277. // `basicLength` is the number of basic code points.
  26278. // Finish the basic string - if it is not empty - with a delimiter
  26279. if (basicLength) {
  26280. output.push(delimiter);
  26281. }
  26282. // Main encoding loop:
  26283. while (handledCPCount < inputLength) {
  26284. // All non-basic code points < n have been handled already. Find the next
  26285. // larger one:
  26286. for (m = maxInt, j = 0; j < inputLength; ++j) {
  26287. currentValue = input[j];
  26288. if (currentValue >= n && currentValue < m) {
  26289. m = currentValue;
  26290. }
  26291. }
  26292. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  26293. // but guard against overflow
  26294. handledCPCountPlusOne = handledCPCount + 1;
  26295. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  26296. error('overflow');
  26297. }
  26298. delta += (m - n) * handledCPCountPlusOne;
  26299. n = m;
  26300. for (j = 0; j < inputLength; ++j) {
  26301. currentValue = input[j];
  26302. if (currentValue < n && ++delta > maxInt) {
  26303. error('overflow');
  26304. }
  26305. if (currentValue == n) {
  26306. // Represent delta as a generalized variable-length integer
  26307. for (q = delta, k = base; /* no condition */; k += base) {
  26308. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  26309. if (q < t) {
  26310. break;
  26311. }
  26312. qMinusT = q - t;
  26313. baseMinusT = base - t;
  26314. output.push(
  26315. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  26316. );
  26317. q = floor(qMinusT / baseMinusT);
  26318. }
  26319. output.push(stringFromCharCode(digitToBasic(q, 0)));
  26320. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  26321. delta = 0;
  26322. ++handledCPCount;
  26323. }
  26324. }
  26325. ++delta;
  26326. ++n;
  26327. }
  26328. return output.join('');
  26329. }
  26330. /**
  26331. * Converts a Punycode string representing a domain name or an email address
  26332. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  26333. * it doesn't matter if you call it on a string that has already been
  26334. * converted to Unicode.
  26335. * @memberOf punycode
  26336. * @param {String} input The Punycoded domain name or email address to
  26337. * convert to Unicode.
  26338. * @returns {String} The Unicode representation of the given Punycode
  26339. * string.
  26340. */
  26341. function toUnicode(input) {
  26342. return mapDomain(input, function(string) {
  26343. return regexPunycode.test(string)
  26344. ? decode(string.slice(4).toLowerCase())
  26345. : string;
  26346. });
  26347. }
  26348. /**
  26349. * Converts a Unicode string representing a domain name or an email address to
  26350. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  26351. * i.e. it doesn't matter if you call it with a domain that's already in
  26352. * ASCII.
  26353. * @memberOf punycode
  26354. * @param {String} input The domain name or email address to convert, as a
  26355. * Unicode string.
  26356. * @returns {String} The Punycode representation of the given domain name or
  26357. * email address.
  26358. */
  26359. function toASCII(input) {
  26360. return mapDomain(input, function(string) {
  26361. return regexNonASCII.test(string)
  26362. ? 'xn--' + encode(string)
  26363. : string;
  26364. });
  26365. }
  26366. /*--------------------------------------------------------------------------*/
  26367. /** Define the public API */
  26368. punycode = {
  26369. /**
  26370. * A string representing the current Punycode.js version number.
  26371. * @memberOf punycode
  26372. * @type String
  26373. */
  26374. 'version': '1.4.1',
  26375. /**
  26376. * An object of methods to convert from JavaScript's internal character
  26377. * representation (UCS-2) to Unicode code points, and back.
  26378. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  26379. * @memberOf punycode
  26380. * @type Object
  26381. */
  26382. 'ucs2': {
  26383. 'decode': ucs2decode,
  26384. 'encode': ucs2encode
  26385. },
  26386. 'decode': decode,
  26387. 'encode': encode,
  26388. 'toASCII': toASCII,
  26389. 'toUnicode': toUnicode
  26390. };
  26391. /** Expose `punycode` */
  26392. // Some AMD build optimizers, like r.js, check for specific condition patterns
  26393. // like the following:
  26394. if (
  26395. typeof define == 'function' &&
  26396. typeof define.amd == 'object' &&
  26397. define.amd
  26398. ) {
  26399. define('punycode', function() {
  26400. return punycode;
  26401. });
  26402. } else if (freeExports && freeModule) {
  26403. if (module.exports == freeExports) {
  26404. // in Node.js, io.js, or RingoJS v0.8.0+
  26405. freeModule.exports = punycode;
  26406. } else {
  26407. // in Narwhal or RingoJS v0.7.0-
  26408. for (key in punycode) {
  26409. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  26410. }
  26411. }
  26412. } else {
  26413. // in Rhino or a web browser
  26414. root.punycode = punycode;
  26415. }
  26416. }(this));
  26417. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26418. },{}],314:[function(require,module,exports){
  26419. // Copyright Joyent, Inc. and other Node contributors.
  26420. //
  26421. // Permission is hereby granted, free of charge, to any person obtaining a
  26422. // copy of this software and associated documentation files (the
  26423. // "Software"), to deal in the Software without restriction, including
  26424. // without limitation the rights to use, copy, modify, merge, publish,
  26425. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26426. // persons to whom the Software is furnished to do so, subject to the
  26427. // following conditions:
  26428. //
  26429. // The above copyright notice and this permission notice shall be included
  26430. // in all copies or substantial portions of the Software.
  26431. //
  26432. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26433. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26434. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26435. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26436. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26437. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26438. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26439. 'use strict';
  26440. // If obj.hasOwnProperty has been overridden, then calling
  26441. // obj.hasOwnProperty(prop) will break.
  26442. // See: https://github.com/joyent/node/issues/1707
  26443. function hasOwnProperty(obj, prop) {
  26444. return Object.prototype.hasOwnProperty.call(obj, prop);
  26445. }
  26446. module.exports = function(qs, sep, eq, options) {
  26447. sep = sep || '&';
  26448. eq = eq || '=';
  26449. var obj = {};
  26450. if (typeof qs !== 'string' || qs.length === 0) {
  26451. return obj;
  26452. }
  26453. var regexp = /\+/g;
  26454. qs = qs.split(sep);
  26455. var maxKeys = 1000;
  26456. if (options && typeof options.maxKeys === 'number') {
  26457. maxKeys = options.maxKeys;
  26458. }
  26459. var len = qs.length;
  26460. // maxKeys <= 0 means that we should not limit keys count
  26461. if (maxKeys > 0 && len > maxKeys) {
  26462. len = maxKeys;
  26463. }
  26464. for (var i = 0; i < len; ++i) {
  26465. var x = qs[i].replace(regexp, '%20'),
  26466. idx = x.indexOf(eq),
  26467. kstr, vstr, k, v;
  26468. if (idx >= 0) {
  26469. kstr = x.substr(0, idx);
  26470. vstr = x.substr(idx + 1);
  26471. } else {
  26472. kstr = x;
  26473. vstr = '';
  26474. }
  26475. k = decodeURIComponent(kstr);
  26476. v = decodeURIComponent(vstr);
  26477. if (!hasOwnProperty(obj, k)) {
  26478. obj[k] = v;
  26479. } else if (isArray(obj[k])) {
  26480. obj[k].push(v);
  26481. } else {
  26482. obj[k] = [obj[k], v];
  26483. }
  26484. }
  26485. return obj;
  26486. };
  26487. var isArray = Array.isArray || function (xs) {
  26488. return Object.prototype.toString.call(xs) === '[object Array]';
  26489. };
  26490. },{}],315:[function(require,module,exports){
  26491. // Copyright Joyent, Inc. and other Node contributors.
  26492. //
  26493. // Permission is hereby granted, free of charge, to any person obtaining a
  26494. // copy of this software and associated documentation files (the
  26495. // "Software"), to deal in the Software without restriction, including
  26496. // without limitation the rights to use, copy, modify, merge, publish,
  26497. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26498. // persons to whom the Software is furnished to do so, subject to the
  26499. // following conditions:
  26500. //
  26501. // The above copyright notice and this permission notice shall be included
  26502. // in all copies or substantial portions of the Software.
  26503. //
  26504. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26505. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26506. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26507. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26508. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26509. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26510. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26511. 'use strict';
  26512. var stringifyPrimitive = function(v) {
  26513. switch (typeof v) {
  26514. case 'string':
  26515. return v;
  26516. case 'boolean':
  26517. return v ? 'true' : 'false';
  26518. case 'number':
  26519. return isFinite(v) ? v : '';
  26520. default:
  26521. return '';
  26522. }
  26523. };
  26524. module.exports = function(obj, sep, eq, name) {
  26525. sep = sep || '&';
  26526. eq = eq || '=';
  26527. if (obj === null) {
  26528. obj = undefined;
  26529. }
  26530. if (typeof obj === 'object') {
  26531. return map(objectKeys(obj), function(k) {
  26532. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  26533. if (isArray(obj[k])) {
  26534. return map(obj[k], function(v) {
  26535. return ks + encodeURIComponent(stringifyPrimitive(v));
  26536. }).join(sep);
  26537. } else {
  26538. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  26539. }
  26540. }).join(sep);
  26541. }
  26542. if (!name) return '';
  26543. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  26544. encodeURIComponent(stringifyPrimitive(obj));
  26545. };
  26546. var isArray = Array.isArray || function (xs) {
  26547. return Object.prototype.toString.call(xs) === '[object Array]';
  26548. };
  26549. function map (xs, f) {
  26550. if (xs.map) return xs.map(f);
  26551. var res = [];
  26552. for (var i = 0; i < xs.length; i++) {
  26553. res.push(f(xs[i], i));
  26554. }
  26555. return res;
  26556. }
  26557. var objectKeys = Object.keys || function (obj) {
  26558. var res = [];
  26559. for (var key in obj) {
  26560. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  26561. }
  26562. return res;
  26563. };
  26564. },{}],316:[function(require,module,exports){
  26565. 'use strict';
  26566. exports.decode = exports.parse = require('./decode');
  26567. exports.encode = exports.stringify = require('./encode');
  26568. },{"./decode":314,"./encode":315}],317:[function(require,module,exports){
  26569. module.exports = require('./lib/_stream_duplex.js');
  26570. },{"./lib/_stream_duplex.js":318}],318:[function(require,module,exports){
  26571. // Copyright Joyent, Inc. and other Node contributors.
  26572. //
  26573. // Permission is hereby granted, free of charge, to any person obtaining a
  26574. // copy of this software and associated documentation files (the
  26575. // "Software"), to deal in the Software without restriction, including
  26576. // without limitation the rights to use, copy, modify, merge, publish,
  26577. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26578. // persons to whom the Software is furnished to do so, subject to the
  26579. // following conditions:
  26580. //
  26581. // The above copyright notice and this permission notice shall be included
  26582. // in all copies or substantial portions of the Software.
  26583. //
  26584. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26585. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26586. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26587. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26588. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26589. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26590. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26591. // a duplex stream is just a stream that is both readable and writable.
  26592. // Since JS doesn't have multiple prototypal inheritance, this class
  26593. // prototypally inherits from Readable, and then parasitically from
  26594. // Writable.
  26595. 'use strict';
  26596. /*<replacement>*/
  26597. var pna = require('process-nextick-args');
  26598. /*</replacement>*/
  26599. /*<replacement>*/
  26600. var objectKeys = Object.keys || function (obj) {
  26601. var keys = [];
  26602. for (var key in obj) {
  26603. keys.push(key);
  26604. }return keys;
  26605. };
  26606. /*</replacement>*/
  26607. module.exports = Duplex;
  26608. /*<replacement>*/
  26609. var util = require('core-util-is');
  26610. util.inherits = require('inherits');
  26611. /*</replacement>*/
  26612. var Readable = require('./_stream_readable');
  26613. var Writable = require('./_stream_writable');
  26614. util.inherits(Duplex, Readable);
  26615. {
  26616. // avoid scope creep, the keys array can then be collected
  26617. var keys = objectKeys(Writable.prototype);
  26618. for (var v = 0; v < keys.length; v++) {
  26619. var method = keys[v];
  26620. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  26621. }
  26622. }
  26623. function Duplex(options) {
  26624. if (!(this instanceof Duplex)) return new Duplex(options);
  26625. Readable.call(this, options);
  26626. Writable.call(this, options);
  26627. if (options && options.readable === false) this.readable = false;
  26628. if (options && options.writable === false) this.writable = false;
  26629. this.allowHalfOpen = true;
  26630. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  26631. this.once('end', onend);
  26632. }
  26633. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  26634. // making it explicit this property is not enumerable
  26635. // because otherwise some prototype manipulation in
  26636. // userland will fail
  26637. enumerable: false,
  26638. get: function () {
  26639. return this._writableState.highWaterMark;
  26640. }
  26641. });
  26642. // the no-half-open enforcer
  26643. function onend() {
  26644. // if we allow half-open state, or if the writable side ended,
  26645. // then we're ok.
  26646. if (this.allowHalfOpen || this._writableState.ended) return;
  26647. // no more data can be written.
  26648. // But allow more writes to happen in this tick.
  26649. pna.nextTick(onEndNT, this);
  26650. }
  26651. function onEndNT(self) {
  26652. self.end();
  26653. }
  26654. Object.defineProperty(Duplex.prototype, 'destroyed', {
  26655. get: function () {
  26656. if (this._readableState === undefined || this._writableState === undefined) {
  26657. return false;
  26658. }
  26659. return this._readableState.destroyed && this._writableState.destroyed;
  26660. },
  26661. set: function (value) {
  26662. // we ignore the value if the stream
  26663. // has not been initialized yet
  26664. if (this._readableState === undefined || this._writableState === undefined) {
  26665. return;
  26666. }
  26667. // backward compatibility, the user is explicitly
  26668. // managing destroyed
  26669. this._readableState.destroyed = value;
  26670. this._writableState.destroyed = value;
  26671. }
  26672. });
  26673. Duplex.prototype._destroy = function (err, cb) {
  26674. this.push(null);
  26675. this.end();
  26676. pna.nextTick(cb, err);
  26677. };
  26678. },{"./_stream_readable":320,"./_stream_writable":322,"core-util-is":238,"inherits":254,"process-nextick-args":311}],319:[function(require,module,exports){
  26679. // Copyright Joyent, Inc. and other Node contributors.
  26680. //
  26681. // Permission is hereby granted, free of charge, to any person obtaining a
  26682. // copy of this software and associated documentation files (the
  26683. // "Software"), to deal in the Software without restriction, including
  26684. // without limitation the rights to use, copy, modify, merge, publish,
  26685. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26686. // persons to whom the Software is furnished to do so, subject to the
  26687. // following conditions:
  26688. //
  26689. // The above copyright notice and this permission notice shall be included
  26690. // in all copies or substantial portions of the Software.
  26691. //
  26692. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26693. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26694. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26695. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26696. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26697. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26698. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26699. // a passthrough stream.
  26700. // basically just the most minimal sort of Transform stream.
  26701. // Every written chunk gets output as-is.
  26702. 'use strict';
  26703. module.exports = PassThrough;
  26704. var Transform = require('./_stream_transform');
  26705. /*<replacement>*/
  26706. var util = require('core-util-is');
  26707. util.inherits = require('inherits');
  26708. /*</replacement>*/
  26709. util.inherits(PassThrough, Transform);
  26710. function PassThrough(options) {
  26711. if (!(this instanceof PassThrough)) return new PassThrough(options);
  26712. Transform.call(this, options);
  26713. }
  26714. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  26715. cb(null, chunk);
  26716. };
  26717. },{"./_stream_transform":321,"core-util-is":238,"inherits":254}],320:[function(require,module,exports){
  26718. (function (process,global){
  26719. // Copyright Joyent, Inc. and other Node contributors.
  26720. //
  26721. // Permission is hereby granted, free of charge, to any person obtaining a
  26722. // copy of this software and associated documentation files (the
  26723. // "Software"), to deal in the Software without restriction, including
  26724. // without limitation the rights to use, copy, modify, merge, publish,
  26725. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26726. // persons to whom the Software is furnished to do so, subject to the
  26727. // following conditions:
  26728. //
  26729. // The above copyright notice and this permission notice shall be included
  26730. // in all copies or substantial portions of the Software.
  26731. //
  26732. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26733. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26734. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26735. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26736. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26737. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26738. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26739. 'use strict';
  26740. /*<replacement>*/
  26741. var pna = require('process-nextick-args');
  26742. /*</replacement>*/
  26743. module.exports = Readable;
  26744. /*<replacement>*/
  26745. var isArray = require('isarray');
  26746. /*</replacement>*/
  26747. /*<replacement>*/
  26748. var Duplex;
  26749. /*</replacement>*/
  26750. Readable.ReadableState = ReadableState;
  26751. /*<replacement>*/
  26752. var EE = require('events').EventEmitter;
  26753. var EElistenerCount = function (emitter, type) {
  26754. return emitter.listeners(type).length;
  26755. };
  26756. /*</replacement>*/
  26757. /*<replacement>*/
  26758. var Stream = require('./internal/streams/stream');
  26759. /*</replacement>*/
  26760. /*<replacement>*/
  26761. var Buffer = require('safe-buffer').Buffer;
  26762. var OurUint8Array = global.Uint8Array || function () {};
  26763. function _uint8ArrayToBuffer(chunk) {
  26764. return Buffer.from(chunk);
  26765. }
  26766. function _isUint8Array(obj) {
  26767. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  26768. }
  26769. /*</replacement>*/
  26770. /*<replacement>*/
  26771. var util = require('core-util-is');
  26772. util.inherits = require('inherits');
  26773. /*</replacement>*/
  26774. /*<replacement>*/
  26775. var debugUtil = require('util');
  26776. var debug = void 0;
  26777. if (debugUtil && debugUtil.debuglog) {
  26778. debug = debugUtil.debuglog('stream');
  26779. } else {
  26780. debug = function () {};
  26781. }
  26782. /*</replacement>*/
  26783. var BufferList = require('./internal/streams/BufferList');
  26784. var destroyImpl = require('./internal/streams/destroy');
  26785. var StringDecoder;
  26786. util.inherits(Readable, Stream);
  26787. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  26788. function prependListener(emitter, event, fn) {
  26789. // Sadly this is not cacheable as some libraries bundle their own
  26790. // event emitter implementation with them.
  26791. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  26792. // This is a hack to make sure that our error handler is attached before any
  26793. // userland ones. NEVER DO THIS. This is here only because this code needs
  26794. // to continue to work with older versions of Node.js that do not include
  26795. // the prependListener() method. The goal is to eventually remove this hack.
  26796. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  26797. }
  26798. function ReadableState(options, stream) {
  26799. Duplex = Duplex || require('./_stream_duplex');
  26800. options = options || {};
  26801. // Duplex streams are both readable and writable, but share
  26802. // the same options object.
  26803. // However, some cases require setting options to different
  26804. // values for the readable and the writable sides of the duplex stream.
  26805. // These options can be provided separately as readableXXX and writableXXX.
  26806. var isDuplex = stream instanceof Duplex;
  26807. // object stream flag. Used to make read(n) ignore n and to
  26808. // make all the buffer merging and length checks go away
  26809. this.objectMode = !!options.objectMode;
  26810. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  26811. // the point at which it stops calling _read() to fill the buffer
  26812. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  26813. var hwm = options.highWaterMark;
  26814. var readableHwm = options.readableHighWaterMark;
  26815. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  26816. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  26817. // cast to ints.
  26818. this.highWaterMark = Math.floor(this.highWaterMark);
  26819. // A linked list is used to store data chunks instead of an array because the
  26820. // linked list can remove elements from the beginning faster than
  26821. // array.shift()
  26822. this.buffer = new BufferList();
  26823. this.length = 0;
  26824. this.pipes = null;
  26825. this.pipesCount = 0;
  26826. this.flowing = null;
  26827. this.ended = false;
  26828. this.endEmitted = false;
  26829. this.reading = false;
  26830. // a flag to be able to tell if the event 'readable'/'data' is emitted
  26831. // immediately, or on a later tick. We set this to true at first, because
  26832. // any actions that shouldn't happen until "later" should generally also
  26833. // not happen before the first read call.
  26834. this.sync = true;
  26835. // whenever we return null, then we set a flag to say
  26836. // that we're awaiting a 'readable' event emission.
  26837. this.needReadable = false;
  26838. this.emittedReadable = false;
  26839. this.readableListening = false;
  26840. this.resumeScheduled = false;
  26841. // has it been destroyed
  26842. this.destroyed = false;
  26843. // Crypto is kind of old and crusty. Historically, its default string
  26844. // encoding is 'binary' so we have to make this configurable.
  26845. // Everything else in the universe uses 'utf8', though.
  26846. this.defaultEncoding = options.defaultEncoding || 'utf8';
  26847. // the number of writers that are awaiting a drain event in .pipe()s
  26848. this.awaitDrain = 0;
  26849. // if true, a maybeReadMore has been scheduled
  26850. this.readingMore = false;
  26851. this.decoder = null;
  26852. this.encoding = null;
  26853. if (options.encoding) {
  26854. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  26855. this.decoder = new StringDecoder(options.encoding);
  26856. this.encoding = options.encoding;
  26857. }
  26858. }
  26859. function Readable(options) {
  26860. Duplex = Duplex || require('./_stream_duplex');
  26861. if (!(this instanceof Readable)) return new Readable(options);
  26862. this._readableState = new ReadableState(options, this);
  26863. // legacy
  26864. this.readable = true;
  26865. if (options) {
  26866. if (typeof options.read === 'function') this._read = options.read;
  26867. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  26868. }
  26869. Stream.call(this);
  26870. }
  26871. Object.defineProperty(Readable.prototype, 'destroyed', {
  26872. get: function () {
  26873. if (this._readableState === undefined) {
  26874. return false;
  26875. }
  26876. return this._readableState.destroyed;
  26877. },
  26878. set: function (value) {
  26879. // we ignore the value if the stream
  26880. // has not been initialized yet
  26881. if (!this._readableState) {
  26882. return;
  26883. }
  26884. // backward compatibility, the user is explicitly
  26885. // managing destroyed
  26886. this._readableState.destroyed = value;
  26887. }
  26888. });
  26889. Readable.prototype.destroy = destroyImpl.destroy;
  26890. Readable.prototype._undestroy = destroyImpl.undestroy;
  26891. Readable.prototype._destroy = function (err, cb) {
  26892. this.push(null);
  26893. cb(err);
  26894. };
  26895. // Manually shove something into the read() buffer.
  26896. // This returns true if the highWaterMark has not been hit yet,
  26897. // similar to how Writable.write() returns true if you should
  26898. // write() some more.
  26899. Readable.prototype.push = function (chunk, encoding) {
  26900. var state = this._readableState;
  26901. var skipChunkCheck;
  26902. if (!state.objectMode) {
  26903. if (typeof chunk === 'string') {
  26904. encoding = encoding || state.defaultEncoding;
  26905. if (encoding !== state.encoding) {
  26906. chunk = Buffer.from(chunk, encoding);
  26907. encoding = '';
  26908. }
  26909. skipChunkCheck = true;
  26910. }
  26911. } else {
  26912. skipChunkCheck = true;
  26913. }
  26914. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  26915. };
  26916. // Unshift should *always* be something directly out of read()
  26917. Readable.prototype.unshift = function (chunk) {
  26918. return readableAddChunk(this, chunk, null, true, false);
  26919. };
  26920. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  26921. var state = stream._readableState;
  26922. if (chunk === null) {
  26923. state.reading = false;
  26924. onEofChunk(stream, state);
  26925. } else {
  26926. var er;
  26927. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  26928. if (er) {
  26929. stream.emit('error', er);
  26930. } else if (state.objectMode || chunk && chunk.length > 0) {
  26931. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  26932. chunk = _uint8ArrayToBuffer(chunk);
  26933. }
  26934. if (addToFront) {
  26935. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  26936. } else if (state.ended) {
  26937. stream.emit('error', new Error('stream.push() after EOF'));
  26938. } else {
  26939. state.reading = false;
  26940. if (state.decoder && !encoding) {
  26941. chunk = state.decoder.write(chunk);
  26942. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  26943. } else {
  26944. addChunk(stream, state, chunk, false);
  26945. }
  26946. }
  26947. } else if (!addToFront) {
  26948. state.reading = false;
  26949. }
  26950. }
  26951. return needMoreData(state);
  26952. }
  26953. function addChunk(stream, state, chunk, addToFront) {
  26954. if (state.flowing && state.length === 0 && !state.sync) {
  26955. stream.emit('data', chunk);
  26956. stream.read(0);
  26957. } else {
  26958. // update the buffer info.
  26959. state.length += state.objectMode ? 1 : chunk.length;
  26960. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  26961. if (state.needReadable) emitReadable(stream);
  26962. }
  26963. maybeReadMore(stream, state);
  26964. }
  26965. function chunkInvalid(state, chunk) {
  26966. var er;
  26967. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  26968. er = new TypeError('Invalid non-string/buffer chunk');
  26969. }
  26970. return er;
  26971. }
  26972. // if it's past the high water mark, we can push in some more.
  26973. // Also, if we have no data yet, we can stand some
  26974. // more bytes. This is to work around cases where hwm=0,
  26975. // such as the repl. Also, if the push() triggered a
  26976. // readable event, and the user called read(largeNumber) such that
  26977. // needReadable was set, then we ought to push more, so that another
  26978. // 'readable' event will be triggered.
  26979. function needMoreData(state) {
  26980. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  26981. }
  26982. Readable.prototype.isPaused = function () {
  26983. return this._readableState.flowing === false;
  26984. };
  26985. // backwards compatibility.
  26986. Readable.prototype.setEncoding = function (enc) {
  26987. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  26988. this._readableState.decoder = new StringDecoder(enc);
  26989. this._readableState.encoding = enc;
  26990. return this;
  26991. };
  26992. // Don't raise the hwm > 8MB
  26993. var MAX_HWM = 0x800000;
  26994. function computeNewHighWaterMark(n) {
  26995. if (n >= MAX_HWM) {
  26996. n = MAX_HWM;
  26997. } else {
  26998. // Get the next highest power of 2 to prevent increasing hwm excessively in
  26999. // tiny amounts
  27000. n--;
  27001. n |= n >>> 1;
  27002. n |= n >>> 2;
  27003. n |= n >>> 4;
  27004. n |= n >>> 8;
  27005. n |= n >>> 16;
  27006. n++;
  27007. }
  27008. return n;
  27009. }
  27010. // This function is designed to be inlinable, so please take care when making
  27011. // changes to the function body.
  27012. function howMuchToRead(n, state) {
  27013. if (n <= 0 || state.length === 0 && state.ended) return 0;
  27014. if (state.objectMode) return 1;
  27015. if (n !== n) {
  27016. // Only flow one buffer at a time
  27017. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  27018. }
  27019. // If we're asking for more than the current hwm, then raise the hwm.
  27020. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  27021. if (n <= state.length) return n;
  27022. // Don't have enough
  27023. if (!state.ended) {
  27024. state.needReadable = true;
  27025. return 0;
  27026. }
  27027. return state.length;
  27028. }
  27029. // you can override either this method, or the async _read(n) below.
  27030. Readable.prototype.read = function (n) {
  27031. debug('read', n);
  27032. n = parseInt(n, 10);
  27033. var state = this._readableState;
  27034. var nOrig = n;
  27035. if (n !== 0) state.emittedReadable = false;
  27036. // if we're doing read(0) to trigger a readable event, but we
  27037. // already have a bunch of data in the buffer, then just trigger
  27038. // the 'readable' event and move on.
  27039. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  27040. debug('read: emitReadable', state.length, state.ended);
  27041. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  27042. return null;
  27043. }
  27044. n = howMuchToRead(n, state);
  27045. // if we've ended, and we're now clear, then finish it up.
  27046. if (n === 0 && state.ended) {
  27047. if (state.length === 0) endReadable(this);
  27048. return null;
  27049. }
  27050. // All the actual chunk generation logic needs to be
  27051. // *below* the call to _read. The reason is that in certain
  27052. // synthetic stream cases, such as passthrough streams, _read
  27053. // may be a completely synchronous operation which may change
  27054. // the state of the read buffer, providing enough data when
  27055. // before there was *not* enough.
  27056. //
  27057. // So, the steps are:
  27058. // 1. Figure out what the state of things will be after we do
  27059. // a read from the buffer.
  27060. //
  27061. // 2. If that resulting state will trigger a _read, then call _read.
  27062. // Note that this may be asynchronous, or synchronous. Yes, it is
  27063. // deeply ugly to write APIs this way, but that still doesn't mean
  27064. // that the Readable class should behave improperly, as streams are
  27065. // designed to be sync/async agnostic.
  27066. // Take note if the _read call is sync or async (ie, if the read call
  27067. // has returned yet), so that we know whether or not it's safe to emit
  27068. // 'readable' etc.
  27069. //
  27070. // 3. Actually pull the requested chunks out of the buffer and return.
  27071. // if we need a readable event, then we need to do some reading.
  27072. var doRead = state.needReadable;
  27073. debug('need readable', doRead);
  27074. // if we currently have less than the highWaterMark, then also read some
  27075. if (state.length === 0 || state.length - n < state.highWaterMark) {
  27076. doRead = true;
  27077. debug('length less than watermark', doRead);
  27078. }
  27079. // however, if we've ended, then there's no point, and if we're already
  27080. // reading, then it's unnecessary.
  27081. if (state.ended || state.reading) {
  27082. doRead = false;
  27083. debug('reading or ended', doRead);
  27084. } else if (doRead) {
  27085. debug('do read');
  27086. state.reading = true;
  27087. state.sync = true;
  27088. // if the length is currently zero, then we *need* a readable event.
  27089. if (state.length === 0) state.needReadable = true;
  27090. // call internal read method
  27091. this._read(state.highWaterMark);
  27092. state.sync = false;
  27093. // If _read pushed data synchronously, then `reading` will be false,
  27094. // and we need to re-evaluate how much data we can return to the user.
  27095. if (!state.reading) n = howMuchToRead(nOrig, state);
  27096. }
  27097. var ret;
  27098. if (n > 0) ret = fromList(n, state);else ret = null;
  27099. if (ret === null) {
  27100. state.needReadable = true;
  27101. n = 0;
  27102. } else {
  27103. state.length -= n;
  27104. }
  27105. if (state.length === 0) {
  27106. // If we have nothing in the buffer, then we want to know
  27107. // as soon as we *do* get something into the buffer.
  27108. if (!state.ended) state.needReadable = true;
  27109. // If we tried to read() past the EOF, then emit end on the next tick.
  27110. if (nOrig !== n && state.ended) endReadable(this);
  27111. }
  27112. if (ret !== null) this.emit('data', ret);
  27113. return ret;
  27114. };
  27115. function onEofChunk(stream, state) {
  27116. if (state.ended) return;
  27117. if (state.decoder) {
  27118. var chunk = state.decoder.end();
  27119. if (chunk && chunk.length) {
  27120. state.buffer.push(chunk);
  27121. state.length += state.objectMode ? 1 : chunk.length;
  27122. }
  27123. }
  27124. state.ended = true;
  27125. // emit 'readable' now to make sure it gets picked up.
  27126. emitReadable(stream);
  27127. }
  27128. // Don't emit readable right away in sync mode, because this can trigger
  27129. // another read() call => stack overflow. This way, it might trigger
  27130. // a nextTick recursion warning, but that's not so bad.
  27131. function emitReadable(stream) {
  27132. var state = stream._readableState;
  27133. state.needReadable = false;
  27134. if (!state.emittedReadable) {
  27135. debug('emitReadable', state.flowing);
  27136. state.emittedReadable = true;
  27137. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  27138. }
  27139. }
  27140. function emitReadable_(stream) {
  27141. debug('emit readable');
  27142. stream.emit('readable');
  27143. flow(stream);
  27144. }
  27145. // at this point, the user has presumably seen the 'readable' event,
  27146. // and called read() to consume some data. that may have triggered
  27147. // in turn another _read(n) call, in which case reading = true if
  27148. // it's in progress.
  27149. // However, if we're not ended, or reading, and the length < hwm,
  27150. // then go ahead and try to read some more preemptively.
  27151. function maybeReadMore(stream, state) {
  27152. if (!state.readingMore) {
  27153. state.readingMore = true;
  27154. pna.nextTick(maybeReadMore_, stream, state);
  27155. }
  27156. }
  27157. function maybeReadMore_(stream, state) {
  27158. var len = state.length;
  27159. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  27160. debug('maybeReadMore read 0');
  27161. stream.read(0);
  27162. if (len === state.length)
  27163. // didn't get any data, stop spinning.
  27164. break;else len = state.length;
  27165. }
  27166. state.readingMore = false;
  27167. }
  27168. // abstract method. to be overridden in specific implementation classes.
  27169. // call cb(er, data) where data is <= n in length.
  27170. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  27171. // arbitrary, and perhaps not very meaningful.
  27172. Readable.prototype._read = function (n) {
  27173. this.emit('error', new Error('_read() is not implemented'));
  27174. };
  27175. Readable.prototype.pipe = function (dest, pipeOpts) {
  27176. var src = this;
  27177. var state = this._readableState;
  27178. switch (state.pipesCount) {
  27179. case 0:
  27180. state.pipes = dest;
  27181. break;
  27182. case 1:
  27183. state.pipes = [state.pipes, dest];
  27184. break;
  27185. default:
  27186. state.pipes.push(dest);
  27187. break;
  27188. }
  27189. state.pipesCount += 1;
  27190. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  27191. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  27192. var endFn = doEnd ? onend : unpipe;
  27193. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  27194. dest.on('unpipe', onunpipe);
  27195. function onunpipe(readable, unpipeInfo) {
  27196. debug('onunpipe');
  27197. if (readable === src) {
  27198. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  27199. unpipeInfo.hasUnpiped = true;
  27200. cleanup();
  27201. }
  27202. }
  27203. }
  27204. function onend() {
  27205. debug('onend');
  27206. dest.end();
  27207. }
  27208. // when the dest drains, it reduces the awaitDrain counter
  27209. // on the source. This would be more elegant with a .once()
  27210. // handler in flow(), but adding and removing repeatedly is
  27211. // too slow.
  27212. var ondrain = pipeOnDrain(src);
  27213. dest.on('drain', ondrain);
  27214. var cleanedUp = false;
  27215. function cleanup() {
  27216. debug('cleanup');
  27217. // cleanup event handlers once the pipe is broken
  27218. dest.removeListener('close', onclose);
  27219. dest.removeListener('finish', onfinish);
  27220. dest.removeListener('drain', ondrain);
  27221. dest.removeListener('error', onerror);
  27222. dest.removeListener('unpipe', onunpipe);
  27223. src.removeListener('end', onend);
  27224. src.removeListener('end', unpipe);
  27225. src.removeListener('data', ondata);
  27226. cleanedUp = true;
  27227. // if the reader is waiting for a drain event from this
  27228. // specific writer, then it would cause it to never start
  27229. // flowing again.
  27230. // So, if this is awaiting a drain, then we just call it now.
  27231. // If we don't know, then assume that we are waiting for one.
  27232. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  27233. }
  27234. // If the user pushes more data while we're writing to dest then we'll end up
  27235. // in ondata again. However, we only want to increase awaitDrain once because
  27236. // dest will only emit one 'drain' event for the multiple writes.
  27237. // => Introduce a guard on increasing awaitDrain.
  27238. var increasedAwaitDrain = false;
  27239. src.on('data', ondata);
  27240. function ondata(chunk) {
  27241. debug('ondata');
  27242. increasedAwaitDrain = false;
  27243. var ret = dest.write(chunk);
  27244. if (false === ret && !increasedAwaitDrain) {
  27245. // If the user unpiped during `dest.write()`, it is possible
  27246. // to get stuck in a permanently paused state if that write
  27247. // also returned false.
  27248. // => Check whether `dest` is still a piping destination.
  27249. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  27250. debug('false write response, pause', src._readableState.awaitDrain);
  27251. src._readableState.awaitDrain++;
  27252. increasedAwaitDrain = true;
  27253. }
  27254. src.pause();
  27255. }
  27256. }
  27257. // if the dest has an error, then stop piping into it.
  27258. // however, don't suppress the throwing behavior for this.
  27259. function onerror(er) {
  27260. debug('onerror', er);
  27261. unpipe();
  27262. dest.removeListener('error', onerror);
  27263. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  27264. }
  27265. // Make sure our error handler is attached before userland ones.
  27266. prependListener(dest, 'error', onerror);
  27267. // Both close and finish should trigger unpipe, but only once.
  27268. function onclose() {
  27269. dest.removeListener('finish', onfinish);
  27270. unpipe();
  27271. }
  27272. dest.once('close', onclose);
  27273. function onfinish() {
  27274. debug('onfinish');
  27275. dest.removeListener('close', onclose);
  27276. unpipe();
  27277. }
  27278. dest.once('finish', onfinish);
  27279. function unpipe() {
  27280. debug('unpipe');
  27281. src.unpipe(dest);
  27282. }
  27283. // tell the dest that it's being piped to
  27284. dest.emit('pipe', src);
  27285. // start the flow if it hasn't been started already.
  27286. if (!state.flowing) {
  27287. debug('pipe resume');
  27288. src.resume();
  27289. }
  27290. return dest;
  27291. };
  27292. function pipeOnDrain(src) {
  27293. return function () {
  27294. var state = src._readableState;
  27295. debug('pipeOnDrain', state.awaitDrain);
  27296. if (state.awaitDrain) state.awaitDrain--;
  27297. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  27298. state.flowing = true;
  27299. flow(src);
  27300. }
  27301. };
  27302. }
  27303. Readable.prototype.unpipe = function (dest) {
  27304. var state = this._readableState;
  27305. var unpipeInfo = { hasUnpiped: false };
  27306. // if we're not piping anywhere, then do nothing.
  27307. if (state.pipesCount === 0) return this;
  27308. // just one destination. most common case.
  27309. if (state.pipesCount === 1) {
  27310. // passed in one, but it's not the right one.
  27311. if (dest && dest !== state.pipes) return this;
  27312. if (!dest) dest = state.pipes;
  27313. // got a match.
  27314. state.pipes = null;
  27315. state.pipesCount = 0;
  27316. state.flowing = false;
  27317. if (dest) dest.emit('unpipe', this, unpipeInfo);
  27318. return this;
  27319. }
  27320. // slow case. multiple pipe destinations.
  27321. if (!dest) {
  27322. // remove all.
  27323. var dests = state.pipes;
  27324. var len = state.pipesCount;
  27325. state.pipes = null;
  27326. state.pipesCount = 0;
  27327. state.flowing = false;
  27328. for (var i = 0; i < len; i++) {
  27329. dests[i].emit('unpipe', this, unpipeInfo);
  27330. }return this;
  27331. }
  27332. // try to find the right one.
  27333. var index = indexOf(state.pipes, dest);
  27334. if (index === -1) return this;
  27335. state.pipes.splice(index, 1);
  27336. state.pipesCount -= 1;
  27337. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  27338. dest.emit('unpipe', this, unpipeInfo);
  27339. return this;
  27340. };
  27341. // set up data events if they are asked for
  27342. // Ensure readable listeners eventually get something
  27343. Readable.prototype.on = function (ev, fn) {
  27344. var res = Stream.prototype.on.call(this, ev, fn);
  27345. if (ev === 'data') {
  27346. // Start flowing on next tick if stream isn't explicitly paused
  27347. if (this._readableState.flowing !== false) this.resume();
  27348. } else if (ev === 'readable') {
  27349. var state = this._readableState;
  27350. if (!state.endEmitted && !state.readableListening) {
  27351. state.readableListening = state.needReadable = true;
  27352. state.emittedReadable = false;
  27353. if (!state.reading) {
  27354. pna.nextTick(nReadingNextTick, this);
  27355. } else if (state.length) {
  27356. emitReadable(this);
  27357. }
  27358. }
  27359. }
  27360. return res;
  27361. };
  27362. Readable.prototype.addListener = Readable.prototype.on;
  27363. function nReadingNextTick(self) {
  27364. debug('readable nexttick read 0');
  27365. self.read(0);
  27366. }
  27367. // pause() and resume() are remnants of the legacy readable stream API
  27368. // If the user uses them, then switch into old mode.
  27369. Readable.prototype.resume = function () {
  27370. var state = this._readableState;
  27371. if (!state.flowing) {
  27372. debug('resume');
  27373. state.flowing = true;
  27374. resume(this, state);
  27375. }
  27376. return this;
  27377. };
  27378. function resume(stream, state) {
  27379. if (!state.resumeScheduled) {
  27380. state.resumeScheduled = true;
  27381. pna.nextTick(resume_, stream, state);
  27382. }
  27383. }
  27384. function resume_(stream, state) {
  27385. if (!state.reading) {
  27386. debug('resume read 0');
  27387. stream.read(0);
  27388. }
  27389. state.resumeScheduled = false;
  27390. state.awaitDrain = 0;
  27391. stream.emit('resume');
  27392. flow(stream);
  27393. if (state.flowing && !state.reading) stream.read(0);
  27394. }
  27395. Readable.prototype.pause = function () {
  27396. debug('call pause flowing=%j', this._readableState.flowing);
  27397. if (false !== this._readableState.flowing) {
  27398. debug('pause');
  27399. this._readableState.flowing = false;
  27400. this.emit('pause');
  27401. }
  27402. return this;
  27403. };
  27404. function flow(stream) {
  27405. var state = stream._readableState;
  27406. debug('flow', state.flowing);
  27407. while (state.flowing && stream.read() !== null) {}
  27408. }
  27409. // wrap an old-style stream as the async data source.
  27410. // This is *not* part of the readable stream interface.
  27411. // It is an ugly unfortunate mess of history.
  27412. Readable.prototype.wrap = function (stream) {
  27413. var _this = this;
  27414. var state = this._readableState;
  27415. var paused = false;
  27416. stream.on('end', function () {
  27417. debug('wrapped end');
  27418. if (state.decoder && !state.ended) {
  27419. var chunk = state.decoder.end();
  27420. if (chunk && chunk.length) _this.push(chunk);
  27421. }
  27422. _this.push(null);
  27423. });
  27424. stream.on('data', function (chunk) {
  27425. debug('wrapped data');
  27426. if (state.decoder) chunk = state.decoder.write(chunk);
  27427. // don't skip over falsy values in objectMode
  27428. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  27429. var ret = _this.push(chunk);
  27430. if (!ret) {
  27431. paused = true;
  27432. stream.pause();
  27433. }
  27434. });
  27435. // proxy all the other methods.
  27436. // important when wrapping filters and duplexes.
  27437. for (var i in stream) {
  27438. if (this[i] === undefined && typeof stream[i] === 'function') {
  27439. this[i] = function (method) {
  27440. return function () {
  27441. return stream[method].apply(stream, arguments);
  27442. };
  27443. }(i);
  27444. }
  27445. }
  27446. // proxy certain important events.
  27447. for (var n = 0; n < kProxyEvents.length; n++) {
  27448. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  27449. }
  27450. // when we try to consume some more bytes, simply unpause the
  27451. // underlying stream.
  27452. this._read = function (n) {
  27453. debug('wrapped _read', n);
  27454. if (paused) {
  27455. paused = false;
  27456. stream.resume();
  27457. }
  27458. };
  27459. return this;
  27460. };
  27461. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  27462. // making it explicit this property is not enumerable
  27463. // because otherwise some prototype manipulation in
  27464. // userland will fail
  27465. enumerable: false,
  27466. get: function () {
  27467. return this._readableState.highWaterMark;
  27468. }
  27469. });
  27470. // exposed for testing purposes only.
  27471. Readable._fromList = fromList;
  27472. // Pluck off n bytes from an array of buffers.
  27473. // Length is the combined lengths of all the buffers in the list.
  27474. // This function is designed to be inlinable, so please take care when making
  27475. // changes to the function body.
  27476. function fromList(n, state) {
  27477. // nothing buffered
  27478. if (state.length === 0) return null;
  27479. var ret;
  27480. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  27481. // read it all, truncate the list
  27482. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  27483. state.buffer.clear();
  27484. } else {
  27485. // read part of list
  27486. ret = fromListPartial(n, state.buffer, state.decoder);
  27487. }
  27488. return ret;
  27489. }
  27490. // Extracts only enough buffered data to satisfy the amount requested.
  27491. // This function is designed to be inlinable, so please take care when making
  27492. // changes to the function body.
  27493. function fromListPartial(n, list, hasStrings) {
  27494. var ret;
  27495. if (n < list.head.data.length) {
  27496. // slice is the same for buffers and strings
  27497. ret = list.head.data.slice(0, n);
  27498. list.head.data = list.head.data.slice(n);
  27499. } else if (n === list.head.data.length) {
  27500. // first chunk is a perfect match
  27501. ret = list.shift();
  27502. } else {
  27503. // result spans more than one buffer
  27504. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  27505. }
  27506. return ret;
  27507. }
  27508. // Copies a specified amount of characters from the list of buffered data
  27509. // chunks.
  27510. // This function is designed to be inlinable, so please take care when making
  27511. // changes to the function body.
  27512. function copyFromBufferString(n, list) {
  27513. var p = list.head;
  27514. var c = 1;
  27515. var ret = p.data;
  27516. n -= ret.length;
  27517. while (p = p.next) {
  27518. var str = p.data;
  27519. var nb = n > str.length ? str.length : n;
  27520. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  27521. n -= nb;
  27522. if (n === 0) {
  27523. if (nb === str.length) {
  27524. ++c;
  27525. if (p.next) list.head = p.next;else list.head = list.tail = null;
  27526. } else {
  27527. list.head = p;
  27528. p.data = str.slice(nb);
  27529. }
  27530. break;
  27531. }
  27532. ++c;
  27533. }
  27534. list.length -= c;
  27535. return ret;
  27536. }
  27537. // Copies a specified amount of bytes from the list of buffered data chunks.
  27538. // This function is designed to be inlinable, so please take care when making
  27539. // changes to the function body.
  27540. function copyFromBuffer(n, list) {
  27541. var ret = Buffer.allocUnsafe(n);
  27542. var p = list.head;
  27543. var c = 1;
  27544. p.data.copy(ret);
  27545. n -= p.data.length;
  27546. while (p = p.next) {
  27547. var buf = p.data;
  27548. var nb = n > buf.length ? buf.length : n;
  27549. buf.copy(ret, ret.length - n, 0, nb);
  27550. n -= nb;
  27551. if (n === 0) {
  27552. if (nb === buf.length) {
  27553. ++c;
  27554. if (p.next) list.head = p.next;else list.head = list.tail = null;
  27555. } else {
  27556. list.head = p;
  27557. p.data = buf.slice(nb);
  27558. }
  27559. break;
  27560. }
  27561. ++c;
  27562. }
  27563. list.length -= c;
  27564. return ret;
  27565. }
  27566. function endReadable(stream) {
  27567. var state = stream._readableState;
  27568. // If we get here before consuming all the bytes, then that is a
  27569. // bug in node. Should never happen.
  27570. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  27571. if (!state.endEmitted) {
  27572. state.ended = true;
  27573. pna.nextTick(endReadableNT, state, stream);
  27574. }
  27575. }
  27576. function endReadableNT(state, stream) {
  27577. // Check that we didn't get one last unshift.
  27578. if (!state.endEmitted && state.length === 0) {
  27579. state.endEmitted = true;
  27580. stream.readable = false;
  27581. stream.emit('end');
  27582. }
  27583. }
  27584. function indexOf(xs, x) {
  27585. for (var i = 0, l = xs.length; i < l; i++) {
  27586. if (xs[i] === x) return i;
  27587. }
  27588. return -1;
  27589. }
  27590. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27591. },{"./_stream_duplex":318,"./internal/streams/BufferList":323,"./internal/streams/destroy":324,"./internal/streams/stream":325,"_process":312,"core-util-is":238,"events":239,"inherits":254,"isarray":258,"process-nextick-args":311,"safe-buffer":326,"string_decoder/":327,"util":32}],321:[function(require,module,exports){
  27592. // Copyright Joyent, Inc. and other Node contributors.
  27593. //
  27594. // Permission is hereby granted, free of charge, to any person obtaining a
  27595. // copy of this software and associated documentation files (the
  27596. // "Software"), to deal in the Software without restriction, including
  27597. // without limitation the rights to use, copy, modify, merge, publish,
  27598. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27599. // persons to whom the Software is furnished to do so, subject to the
  27600. // following conditions:
  27601. //
  27602. // The above copyright notice and this permission notice shall be included
  27603. // in all copies or substantial portions of the Software.
  27604. //
  27605. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27606. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27607. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27608. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27609. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27610. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27611. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27612. // a transform stream is a readable/writable stream where you do
  27613. // something with the data. Sometimes it's called a "filter",
  27614. // but that's not a great name for it, since that implies a thing where
  27615. // some bits pass through, and others are simply ignored. (That would
  27616. // be a valid example of a transform, of course.)
  27617. //
  27618. // While the output is causally related to the input, it's not a
  27619. // necessarily symmetric or synchronous transformation. For example,
  27620. // a zlib stream might take multiple plain-text writes(), and then
  27621. // emit a single compressed chunk some time in the future.
  27622. //
  27623. // Here's how this works:
  27624. //
  27625. // The Transform stream has all the aspects of the readable and writable
  27626. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  27627. // internally, and returns false if there's a lot of pending writes
  27628. // buffered up. When you call read(), that calls _read(n) until
  27629. // there's enough pending readable data buffered up.
  27630. //
  27631. // In a transform stream, the written data is placed in a buffer. When
  27632. // _read(n) is called, it transforms the queued up data, calling the
  27633. // buffered _write cb's as it consumes chunks. If consuming a single
  27634. // written chunk would result in multiple output chunks, then the first
  27635. // outputted bit calls the readcb, and subsequent chunks just go into
  27636. // the read buffer, and will cause it to emit 'readable' if necessary.
  27637. //
  27638. // This way, back-pressure is actually determined by the reading side,
  27639. // since _read has to be called to start processing a new chunk. However,
  27640. // a pathological inflate type of transform can cause excessive buffering
  27641. // here. For example, imagine a stream where every byte of input is
  27642. // interpreted as an integer from 0-255, and then results in that many
  27643. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  27644. // 1kb of data being output. In this case, you could write a very small
  27645. // amount of input, and end up with a very large amount of output. In
  27646. // such a pathological inflating mechanism, there'd be no way to tell
  27647. // the system to stop doing the transform. A single 4MB write could
  27648. // cause the system to run out of memory.
  27649. //
  27650. // However, even in such a pathological case, only a single written chunk
  27651. // would be consumed, and then the rest would wait (un-transformed) until
  27652. // the results of the previous transformed chunk were consumed.
  27653. 'use strict';
  27654. module.exports = Transform;
  27655. var Duplex = require('./_stream_duplex');
  27656. /*<replacement>*/
  27657. var util = require('core-util-is');
  27658. util.inherits = require('inherits');
  27659. /*</replacement>*/
  27660. util.inherits(Transform, Duplex);
  27661. function afterTransform(er, data) {
  27662. var ts = this._transformState;
  27663. ts.transforming = false;
  27664. var cb = ts.writecb;
  27665. if (!cb) {
  27666. return this.emit('error', new Error('write callback called multiple times'));
  27667. }
  27668. ts.writechunk = null;
  27669. ts.writecb = null;
  27670. if (data != null) // single equals check for both `null` and `undefined`
  27671. this.push(data);
  27672. cb(er);
  27673. var rs = this._readableState;
  27674. rs.reading = false;
  27675. if (rs.needReadable || rs.length < rs.highWaterMark) {
  27676. this._read(rs.highWaterMark);
  27677. }
  27678. }
  27679. function Transform(options) {
  27680. if (!(this instanceof Transform)) return new Transform(options);
  27681. Duplex.call(this, options);
  27682. this._transformState = {
  27683. afterTransform: afterTransform.bind(this),
  27684. needTransform: false,
  27685. transforming: false,
  27686. writecb: null,
  27687. writechunk: null,
  27688. writeencoding: null
  27689. };
  27690. // start out asking for a readable event once data is transformed.
  27691. this._readableState.needReadable = true;
  27692. // we have implemented the _read method, and done the other things
  27693. // that Readable wants before the first _read call, so unset the
  27694. // sync guard flag.
  27695. this._readableState.sync = false;
  27696. if (options) {
  27697. if (typeof options.transform === 'function') this._transform = options.transform;
  27698. if (typeof options.flush === 'function') this._flush = options.flush;
  27699. }
  27700. // When the writable side finishes, then flush out anything remaining.
  27701. this.on('prefinish', prefinish);
  27702. }
  27703. function prefinish() {
  27704. var _this = this;
  27705. if (typeof this._flush === 'function') {
  27706. this._flush(function (er, data) {
  27707. done(_this, er, data);
  27708. });
  27709. } else {
  27710. done(this, null, null);
  27711. }
  27712. }
  27713. Transform.prototype.push = function (chunk, encoding) {
  27714. this._transformState.needTransform = false;
  27715. return Duplex.prototype.push.call(this, chunk, encoding);
  27716. };
  27717. // This is the part where you do stuff!
  27718. // override this function in implementation classes.
  27719. // 'chunk' is an input chunk.
  27720. //
  27721. // Call `push(newChunk)` to pass along transformed output
  27722. // to the readable side. You may call 'push' zero or more times.
  27723. //
  27724. // Call `cb(err)` when you are done with this chunk. If you pass
  27725. // an error, then that'll put the hurt on the whole operation. If you
  27726. // never call cb(), then you'll never get another chunk.
  27727. Transform.prototype._transform = function (chunk, encoding, cb) {
  27728. throw new Error('_transform() is not implemented');
  27729. };
  27730. Transform.prototype._write = function (chunk, encoding, cb) {
  27731. var ts = this._transformState;
  27732. ts.writecb = cb;
  27733. ts.writechunk = chunk;
  27734. ts.writeencoding = encoding;
  27735. if (!ts.transforming) {
  27736. var rs = this._readableState;
  27737. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  27738. }
  27739. };
  27740. // Doesn't matter what the args are here.
  27741. // _transform does all the work.
  27742. // That we got here means that the readable side wants more data.
  27743. Transform.prototype._read = function (n) {
  27744. var ts = this._transformState;
  27745. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  27746. ts.transforming = true;
  27747. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  27748. } else {
  27749. // mark that we need a transform, so that any data that comes in
  27750. // will get processed, now that we've asked for it.
  27751. ts.needTransform = true;
  27752. }
  27753. };
  27754. Transform.prototype._destroy = function (err, cb) {
  27755. var _this2 = this;
  27756. Duplex.prototype._destroy.call(this, err, function (err2) {
  27757. cb(err2);
  27758. _this2.emit('close');
  27759. });
  27760. };
  27761. function done(stream, er, data) {
  27762. if (er) return stream.emit('error', er);
  27763. if (data != null) // single equals check for both `null` and `undefined`
  27764. stream.push(data);
  27765. // if there's nothing in the write buffer, then that means
  27766. // that nothing more will ever be provided
  27767. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  27768. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  27769. return stream.push(null);
  27770. }
  27771. },{"./_stream_duplex":318,"core-util-is":238,"inherits":254}],322:[function(require,module,exports){
  27772. (function (process,global,setImmediate){
  27773. // Copyright Joyent, Inc. and other Node contributors.
  27774. //
  27775. // Permission is hereby granted, free of charge, to any person obtaining a
  27776. // copy of this software and associated documentation files (the
  27777. // "Software"), to deal in the Software without restriction, including
  27778. // without limitation the rights to use, copy, modify, merge, publish,
  27779. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27780. // persons to whom the Software is furnished to do so, subject to the
  27781. // following conditions:
  27782. //
  27783. // The above copyright notice and this permission notice shall be included
  27784. // in all copies or substantial portions of the Software.
  27785. //
  27786. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27787. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27788. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27789. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27790. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27791. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27792. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27793. // A bit simpler than readable streams.
  27794. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  27795. // the drain event emission and buffering.
  27796. 'use strict';
  27797. /*<replacement>*/
  27798. var pna = require('process-nextick-args');
  27799. /*</replacement>*/
  27800. module.exports = Writable;
  27801. /* <replacement> */
  27802. function WriteReq(chunk, encoding, cb) {
  27803. this.chunk = chunk;
  27804. this.encoding = encoding;
  27805. this.callback = cb;
  27806. this.next = null;
  27807. }
  27808. // It seems a linked list but it is not
  27809. // there will be only 2 of these for each stream
  27810. function CorkedRequest(state) {
  27811. var _this = this;
  27812. this.next = null;
  27813. this.entry = null;
  27814. this.finish = function () {
  27815. onCorkedFinish(_this, state);
  27816. };
  27817. }
  27818. /* </replacement> */
  27819. /*<replacement>*/
  27820. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  27821. /*</replacement>*/
  27822. /*<replacement>*/
  27823. var Duplex;
  27824. /*</replacement>*/
  27825. Writable.WritableState = WritableState;
  27826. /*<replacement>*/
  27827. var util = require('core-util-is');
  27828. util.inherits = require('inherits');
  27829. /*</replacement>*/
  27830. /*<replacement>*/
  27831. var internalUtil = {
  27832. deprecate: require('util-deprecate')
  27833. };
  27834. /*</replacement>*/
  27835. /*<replacement>*/
  27836. var Stream = require('./internal/streams/stream');
  27837. /*</replacement>*/
  27838. /*<replacement>*/
  27839. var Buffer = require('safe-buffer').Buffer;
  27840. var OurUint8Array = global.Uint8Array || function () {};
  27841. function _uint8ArrayToBuffer(chunk) {
  27842. return Buffer.from(chunk);
  27843. }
  27844. function _isUint8Array(obj) {
  27845. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  27846. }
  27847. /*</replacement>*/
  27848. var destroyImpl = require('./internal/streams/destroy');
  27849. util.inherits(Writable, Stream);
  27850. function nop() {}
  27851. function WritableState(options, stream) {
  27852. Duplex = Duplex || require('./_stream_duplex');
  27853. options = options || {};
  27854. // Duplex streams are both readable and writable, but share
  27855. // the same options object.
  27856. // However, some cases require setting options to different
  27857. // values for the readable and the writable sides of the duplex stream.
  27858. // These options can be provided separately as readableXXX and writableXXX.
  27859. var isDuplex = stream instanceof Duplex;
  27860. // object stream flag to indicate whether or not this stream
  27861. // contains buffers or objects.
  27862. this.objectMode = !!options.objectMode;
  27863. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  27864. // the point at which write() starts returning false
  27865. // Note: 0 is a valid value, means that we always return false if
  27866. // the entire buffer is not flushed immediately on write()
  27867. var hwm = options.highWaterMark;
  27868. var writableHwm = options.writableHighWaterMark;
  27869. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  27870. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  27871. // cast to ints.
  27872. this.highWaterMark = Math.floor(this.highWaterMark);
  27873. // if _final has been called
  27874. this.finalCalled = false;
  27875. // drain event flag.
  27876. this.needDrain = false;
  27877. // at the start of calling end()
  27878. this.ending = false;
  27879. // when end() has been called, and returned
  27880. this.ended = false;
  27881. // when 'finish' is emitted
  27882. this.finished = false;
  27883. // has it been destroyed
  27884. this.destroyed = false;
  27885. // should we decode strings into buffers before passing to _write?
  27886. // this is here so that some node-core streams can optimize string
  27887. // handling at a lower level.
  27888. var noDecode = options.decodeStrings === false;
  27889. this.decodeStrings = !noDecode;
  27890. // Crypto is kind of old and crusty. Historically, its default string
  27891. // encoding is 'binary' so we have to make this configurable.
  27892. // Everything else in the universe uses 'utf8', though.
  27893. this.defaultEncoding = options.defaultEncoding || 'utf8';
  27894. // not an actual buffer we keep track of, but a measurement
  27895. // of how much we're waiting to get pushed to some underlying
  27896. // socket or file.
  27897. this.length = 0;
  27898. // a flag to see when we're in the middle of a write.
  27899. this.writing = false;
  27900. // when true all writes will be buffered until .uncork() call
  27901. this.corked = 0;
  27902. // a flag to be able to tell if the onwrite cb is called immediately,
  27903. // or on a later tick. We set this to true at first, because any
  27904. // actions that shouldn't happen until "later" should generally also
  27905. // not happen before the first write call.
  27906. this.sync = true;
  27907. // a flag to know if we're processing previously buffered items, which
  27908. // may call the _write() callback in the same tick, so that we don't
  27909. // end up in an overlapped onwrite situation.
  27910. this.bufferProcessing = false;
  27911. // the callback that's passed to _write(chunk,cb)
  27912. this.onwrite = function (er) {
  27913. onwrite(stream, er);
  27914. };
  27915. // the callback that the user supplies to write(chunk,encoding,cb)
  27916. this.writecb = null;
  27917. // the amount that is being written when _write is called.
  27918. this.writelen = 0;
  27919. this.bufferedRequest = null;
  27920. this.lastBufferedRequest = null;
  27921. // number of pending user-supplied write callbacks
  27922. // this must be 0 before 'finish' can be emitted
  27923. this.pendingcb = 0;
  27924. // emit prefinish if the only thing we're waiting for is _write cbs
  27925. // This is relevant for synchronous Transform streams
  27926. this.prefinished = false;
  27927. // True if the error was already emitted and should not be thrown again
  27928. this.errorEmitted = false;
  27929. // count buffered requests
  27930. this.bufferedRequestCount = 0;
  27931. // allocate the first CorkedRequest, there is always
  27932. // one allocated and free to use, and we maintain at most two
  27933. this.corkedRequestsFree = new CorkedRequest(this);
  27934. }
  27935. WritableState.prototype.getBuffer = function getBuffer() {
  27936. var current = this.bufferedRequest;
  27937. var out = [];
  27938. while (current) {
  27939. out.push(current);
  27940. current = current.next;
  27941. }
  27942. return out;
  27943. };
  27944. (function () {
  27945. try {
  27946. Object.defineProperty(WritableState.prototype, 'buffer', {
  27947. get: internalUtil.deprecate(function () {
  27948. return this.getBuffer();
  27949. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  27950. });
  27951. } catch (_) {}
  27952. })();
  27953. // Test _writableState for inheritance to account for Duplex streams,
  27954. // whose prototype chain only points to Readable.
  27955. var realHasInstance;
  27956. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  27957. realHasInstance = Function.prototype[Symbol.hasInstance];
  27958. Object.defineProperty(Writable, Symbol.hasInstance, {
  27959. value: function (object) {
  27960. if (realHasInstance.call(this, object)) return true;
  27961. if (this !== Writable) return false;
  27962. return object && object._writableState instanceof WritableState;
  27963. }
  27964. });
  27965. } else {
  27966. realHasInstance = function (object) {
  27967. return object instanceof this;
  27968. };
  27969. }
  27970. function Writable(options) {
  27971. Duplex = Duplex || require('./_stream_duplex');
  27972. // Writable ctor is applied to Duplexes, too.
  27973. // `realHasInstance` is necessary because using plain `instanceof`
  27974. // would return false, as no `_writableState` property is attached.
  27975. // Trying to use the custom `instanceof` for Writable here will also break the
  27976. // Node.js LazyTransform implementation, which has a non-trivial getter for
  27977. // `_writableState` that would lead to infinite recursion.
  27978. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  27979. return new Writable(options);
  27980. }
  27981. this._writableState = new WritableState(options, this);
  27982. // legacy.
  27983. this.writable = true;
  27984. if (options) {
  27985. if (typeof options.write === 'function') this._write = options.write;
  27986. if (typeof options.writev === 'function') this._writev = options.writev;
  27987. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  27988. if (typeof options.final === 'function') this._final = options.final;
  27989. }
  27990. Stream.call(this);
  27991. }
  27992. // Otherwise people can pipe Writable streams, which is just wrong.
  27993. Writable.prototype.pipe = function () {
  27994. this.emit('error', new Error('Cannot pipe, not readable'));
  27995. };
  27996. function writeAfterEnd(stream, cb) {
  27997. var er = new Error('write after end');
  27998. // TODO: defer error events consistently everywhere, not just the cb
  27999. stream.emit('error', er);
  28000. pna.nextTick(cb, er);
  28001. }
  28002. // Checks that a user-supplied chunk is valid, especially for the particular
  28003. // mode the stream is in. Currently this means that `null` is never accepted
  28004. // and undefined/non-string values are only allowed in object mode.
  28005. function validChunk(stream, state, chunk, cb) {
  28006. var valid = true;
  28007. var er = false;
  28008. if (chunk === null) {
  28009. er = new TypeError('May not write null values to stream');
  28010. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  28011. er = new TypeError('Invalid non-string/buffer chunk');
  28012. }
  28013. if (er) {
  28014. stream.emit('error', er);
  28015. pna.nextTick(cb, er);
  28016. valid = false;
  28017. }
  28018. return valid;
  28019. }
  28020. Writable.prototype.write = function (chunk, encoding, cb) {
  28021. var state = this._writableState;
  28022. var ret = false;
  28023. var isBuf = !state.objectMode && _isUint8Array(chunk);
  28024. if (isBuf && !Buffer.isBuffer(chunk)) {
  28025. chunk = _uint8ArrayToBuffer(chunk);
  28026. }
  28027. if (typeof encoding === 'function') {
  28028. cb = encoding;
  28029. encoding = null;
  28030. }
  28031. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  28032. if (typeof cb !== 'function') cb = nop;
  28033. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  28034. state.pendingcb++;
  28035. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  28036. }
  28037. return ret;
  28038. };
  28039. Writable.prototype.cork = function () {
  28040. var state = this._writableState;
  28041. state.corked++;
  28042. };
  28043. Writable.prototype.uncork = function () {
  28044. var state = this._writableState;
  28045. if (state.corked) {
  28046. state.corked--;
  28047. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  28048. }
  28049. };
  28050. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  28051. // node::ParseEncoding() requires lower case.
  28052. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  28053. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  28054. this._writableState.defaultEncoding = encoding;
  28055. return this;
  28056. };
  28057. function decodeChunk(state, chunk, encoding) {
  28058. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  28059. chunk = Buffer.from(chunk, encoding);
  28060. }
  28061. return chunk;
  28062. }
  28063. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  28064. // making it explicit this property is not enumerable
  28065. // because otherwise some prototype manipulation in
  28066. // userland will fail
  28067. enumerable: false,
  28068. get: function () {
  28069. return this._writableState.highWaterMark;
  28070. }
  28071. });
  28072. // if we're already writing something, then just put this
  28073. // in the queue, and wait our turn. Otherwise, call _write
  28074. // If we return false, then we need a drain event, so set that flag.
  28075. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  28076. if (!isBuf) {
  28077. var newChunk = decodeChunk(state, chunk, encoding);
  28078. if (chunk !== newChunk) {
  28079. isBuf = true;
  28080. encoding = 'buffer';
  28081. chunk = newChunk;
  28082. }
  28083. }
  28084. var len = state.objectMode ? 1 : chunk.length;
  28085. state.length += len;
  28086. var ret = state.length < state.highWaterMark;
  28087. // we must ensure that previous needDrain will not be reset to false.
  28088. if (!ret) state.needDrain = true;
  28089. if (state.writing || state.corked) {
  28090. var last = state.lastBufferedRequest;
  28091. state.lastBufferedRequest = {
  28092. chunk: chunk,
  28093. encoding: encoding,
  28094. isBuf: isBuf,
  28095. callback: cb,
  28096. next: null
  28097. };
  28098. if (last) {
  28099. last.next = state.lastBufferedRequest;
  28100. } else {
  28101. state.bufferedRequest = state.lastBufferedRequest;
  28102. }
  28103. state.bufferedRequestCount += 1;
  28104. } else {
  28105. doWrite(stream, state, false, len, chunk, encoding, cb);
  28106. }
  28107. return ret;
  28108. }
  28109. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  28110. state.writelen = len;
  28111. state.writecb = cb;
  28112. state.writing = true;
  28113. state.sync = true;
  28114. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  28115. state.sync = false;
  28116. }
  28117. function onwriteError(stream, state, sync, er, cb) {
  28118. --state.pendingcb;
  28119. if (sync) {
  28120. // defer the callback if we are being called synchronously
  28121. // to avoid piling up things on the stack
  28122. pna.nextTick(cb, er);
  28123. // this can emit finish, and it will always happen
  28124. // after error
  28125. pna.nextTick(finishMaybe, stream, state);
  28126. stream._writableState.errorEmitted = true;
  28127. stream.emit('error', er);
  28128. } else {
  28129. // the caller expect this to happen before if
  28130. // it is async
  28131. cb(er);
  28132. stream._writableState.errorEmitted = true;
  28133. stream.emit('error', er);
  28134. // this can emit finish, but finish must
  28135. // always follow error
  28136. finishMaybe(stream, state);
  28137. }
  28138. }
  28139. function onwriteStateUpdate(state) {
  28140. state.writing = false;
  28141. state.writecb = null;
  28142. state.length -= state.writelen;
  28143. state.writelen = 0;
  28144. }
  28145. function onwrite(stream, er) {
  28146. var state = stream._writableState;
  28147. var sync = state.sync;
  28148. var cb = state.writecb;
  28149. onwriteStateUpdate(state);
  28150. if (er) onwriteError(stream, state, sync, er, cb);else {
  28151. // Check if we're actually ready to finish, but don't emit yet
  28152. var finished = needFinish(state);
  28153. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  28154. clearBuffer(stream, state);
  28155. }
  28156. if (sync) {
  28157. /*<replacement>*/
  28158. asyncWrite(afterWrite, stream, state, finished, cb);
  28159. /*</replacement>*/
  28160. } else {
  28161. afterWrite(stream, state, finished, cb);
  28162. }
  28163. }
  28164. }
  28165. function afterWrite(stream, state, finished, cb) {
  28166. if (!finished) onwriteDrain(stream, state);
  28167. state.pendingcb--;
  28168. cb();
  28169. finishMaybe(stream, state);
  28170. }
  28171. // Must force callback to be called on nextTick, so that we don't
  28172. // emit 'drain' before the write() consumer gets the 'false' return
  28173. // value, and has a chance to attach a 'drain' listener.
  28174. function onwriteDrain(stream, state) {
  28175. if (state.length === 0 && state.needDrain) {
  28176. state.needDrain = false;
  28177. stream.emit('drain');
  28178. }
  28179. }
  28180. // if there's something in the buffer waiting, then process it
  28181. function clearBuffer(stream, state) {
  28182. state.bufferProcessing = true;
  28183. var entry = state.bufferedRequest;
  28184. if (stream._writev && entry && entry.next) {
  28185. // Fast case, write everything using _writev()
  28186. var l = state.bufferedRequestCount;
  28187. var buffer = new Array(l);
  28188. var holder = state.corkedRequestsFree;
  28189. holder.entry = entry;
  28190. var count = 0;
  28191. var allBuffers = true;
  28192. while (entry) {
  28193. buffer[count] = entry;
  28194. if (!entry.isBuf) allBuffers = false;
  28195. entry = entry.next;
  28196. count += 1;
  28197. }
  28198. buffer.allBuffers = allBuffers;
  28199. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  28200. // doWrite is almost always async, defer these to save a bit of time
  28201. // as the hot path ends with doWrite
  28202. state.pendingcb++;
  28203. state.lastBufferedRequest = null;
  28204. if (holder.next) {
  28205. state.corkedRequestsFree = holder.next;
  28206. holder.next = null;
  28207. } else {
  28208. state.corkedRequestsFree = new CorkedRequest(state);
  28209. }
  28210. state.bufferedRequestCount = 0;
  28211. } else {
  28212. // Slow case, write chunks one-by-one
  28213. while (entry) {
  28214. var chunk = entry.chunk;
  28215. var encoding = entry.encoding;
  28216. var cb = entry.callback;
  28217. var len = state.objectMode ? 1 : chunk.length;
  28218. doWrite(stream, state, false, len, chunk, encoding, cb);
  28219. entry = entry.next;
  28220. state.bufferedRequestCount--;
  28221. // if we didn't call the onwrite immediately, then
  28222. // it means that we need to wait until it does.
  28223. // also, that means that the chunk and cb are currently
  28224. // being processed, so move the buffer counter past them.
  28225. if (state.writing) {
  28226. break;
  28227. }
  28228. }
  28229. if (entry === null) state.lastBufferedRequest = null;
  28230. }
  28231. state.bufferedRequest = entry;
  28232. state.bufferProcessing = false;
  28233. }
  28234. Writable.prototype._write = function (chunk, encoding, cb) {
  28235. cb(new Error('_write() is not implemented'));
  28236. };
  28237. Writable.prototype._writev = null;
  28238. Writable.prototype.end = function (chunk, encoding, cb) {
  28239. var state = this._writableState;
  28240. if (typeof chunk === 'function') {
  28241. cb = chunk;
  28242. chunk = null;
  28243. encoding = null;
  28244. } else if (typeof encoding === 'function') {
  28245. cb = encoding;
  28246. encoding = null;
  28247. }
  28248. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  28249. // .end() fully uncorks
  28250. if (state.corked) {
  28251. state.corked = 1;
  28252. this.uncork();
  28253. }
  28254. // ignore unnecessary end() calls.
  28255. if (!state.ending && !state.finished) endWritable(this, state, cb);
  28256. };
  28257. function needFinish(state) {
  28258. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  28259. }
  28260. function callFinal(stream, state) {
  28261. stream._final(function (err) {
  28262. state.pendingcb--;
  28263. if (err) {
  28264. stream.emit('error', err);
  28265. }
  28266. state.prefinished = true;
  28267. stream.emit('prefinish');
  28268. finishMaybe(stream, state);
  28269. });
  28270. }
  28271. function prefinish(stream, state) {
  28272. if (!state.prefinished && !state.finalCalled) {
  28273. if (typeof stream._final === 'function') {
  28274. state.pendingcb++;
  28275. state.finalCalled = true;
  28276. pna.nextTick(callFinal, stream, state);
  28277. } else {
  28278. state.prefinished = true;
  28279. stream.emit('prefinish');
  28280. }
  28281. }
  28282. }
  28283. function finishMaybe(stream, state) {
  28284. var need = needFinish(state);
  28285. if (need) {
  28286. prefinish(stream, state);
  28287. if (state.pendingcb === 0) {
  28288. state.finished = true;
  28289. stream.emit('finish');
  28290. }
  28291. }
  28292. return need;
  28293. }
  28294. function endWritable(stream, state, cb) {
  28295. state.ending = true;
  28296. finishMaybe(stream, state);
  28297. if (cb) {
  28298. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  28299. }
  28300. state.ended = true;
  28301. stream.writable = false;
  28302. }
  28303. function onCorkedFinish(corkReq, state, err) {
  28304. var entry = corkReq.entry;
  28305. corkReq.entry = null;
  28306. while (entry) {
  28307. var cb = entry.callback;
  28308. state.pendingcb--;
  28309. cb(err);
  28310. entry = entry.next;
  28311. }
  28312. if (state.corkedRequestsFree) {
  28313. state.corkedRequestsFree.next = corkReq;
  28314. } else {
  28315. state.corkedRequestsFree = corkReq;
  28316. }
  28317. }
  28318. Object.defineProperty(Writable.prototype, 'destroyed', {
  28319. get: function () {
  28320. if (this._writableState === undefined) {
  28321. return false;
  28322. }
  28323. return this._writableState.destroyed;
  28324. },
  28325. set: function (value) {
  28326. // we ignore the value if the stream
  28327. // has not been initialized yet
  28328. if (!this._writableState) {
  28329. return;
  28330. }
  28331. // backward compatibility, the user is explicitly
  28332. // managing destroyed
  28333. this._writableState.destroyed = value;
  28334. }
  28335. });
  28336. Writable.prototype.destroy = destroyImpl.destroy;
  28337. Writable.prototype._undestroy = destroyImpl.undestroy;
  28338. Writable.prototype._destroy = function (err, cb) {
  28339. this.end();
  28340. cb(err);
  28341. };
  28342. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  28343. },{"./_stream_duplex":318,"./internal/streams/destroy":324,"./internal/streams/stream":325,"_process":312,"core-util-is":238,"inherits":254,"process-nextick-args":311,"safe-buffer":326,"timers":355,"util-deprecate":362}],323:[function(require,module,exports){
  28344. 'use strict';
  28345. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28346. var Buffer = require('safe-buffer').Buffer;
  28347. var util = require('util');
  28348. function copyBuffer(src, target, offset) {
  28349. src.copy(target, offset);
  28350. }
  28351. module.exports = function () {
  28352. function BufferList() {
  28353. _classCallCheck(this, BufferList);
  28354. this.head = null;
  28355. this.tail = null;
  28356. this.length = 0;
  28357. }
  28358. BufferList.prototype.push = function push(v) {
  28359. var entry = { data: v, next: null };
  28360. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  28361. this.tail = entry;
  28362. ++this.length;
  28363. };
  28364. BufferList.prototype.unshift = function unshift(v) {
  28365. var entry = { data: v, next: this.head };
  28366. if (this.length === 0) this.tail = entry;
  28367. this.head = entry;
  28368. ++this.length;
  28369. };
  28370. BufferList.prototype.shift = function shift() {
  28371. if (this.length === 0) return;
  28372. var ret = this.head.data;
  28373. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  28374. --this.length;
  28375. return ret;
  28376. };
  28377. BufferList.prototype.clear = function clear() {
  28378. this.head = this.tail = null;
  28379. this.length = 0;
  28380. };
  28381. BufferList.prototype.join = function join(s) {
  28382. if (this.length === 0) return '';
  28383. var p = this.head;
  28384. var ret = '' + p.data;
  28385. while (p = p.next) {
  28386. ret += s + p.data;
  28387. }return ret;
  28388. };
  28389. BufferList.prototype.concat = function concat(n) {
  28390. if (this.length === 0) return Buffer.alloc(0);
  28391. if (this.length === 1) return this.head.data;
  28392. var ret = Buffer.allocUnsafe(n >>> 0);
  28393. var p = this.head;
  28394. var i = 0;
  28395. while (p) {
  28396. copyBuffer(p.data, ret, i);
  28397. i += p.data.length;
  28398. p = p.next;
  28399. }
  28400. return ret;
  28401. };
  28402. return BufferList;
  28403. }();
  28404. if (util && util.inspect && util.inspect.custom) {
  28405. module.exports.prototype[util.inspect.custom] = function () {
  28406. var obj = util.inspect({ length: this.length });
  28407. return this.constructor.name + ' ' + obj;
  28408. };
  28409. }
  28410. },{"safe-buffer":326,"util":32}],324:[function(require,module,exports){
  28411. 'use strict';
  28412. /*<replacement>*/
  28413. var pna = require('process-nextick-args');
  28414. /*</replacement>*/
  28415. // undocumented cb() API, needed for core, not for public API
  28416. function destroy(err, cb) {
  28417. var _this = this;
  28418. var readableDestroyed = this._readableState && this._readableState.destroyed;
  28419. var writableDestroyed = this._writableState && this._writableState.destroyed;
  28420. if (readableDestroyed || writableDestroyed) {
  28421. if (cb) {
  28422. cb(err);
  28423. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  28424. pna.nextTick(emitErrorNT, this, err);
  28425. }
  28426. return this;
  28427. }
  28428. // we set destroyed to true before firing error callbacks in order
  28429. // to make it re-entrance safe in case destroy() is called within callbacks
  28430. if (this._readableState) {
  28431. this._readableState.destroyed = true;
  28432. }
  28433. // if this is a duplex stream mark the writable part as destroyed as well
  28434. if (this._writableState) {
  28435. this._writableState.destroyed = true;
  28436. }
  28437. this._destroy(err || null, function (err) {
  28438. if (!cb && err) {
  28439. pna.nextTick(emitErrorNT, _this, err);
  28440. if (_this._writableState) {
  28441. _this._writableState.errorEmitted = true;
  28442. }
  28443. } else if (cb) {
  28444. cb(err);
  28445. }
  28446. });
  28447. return this;
  28448. }
  28449. function undestroy() {
  28450. if (this._readableState) {
  28451. this._readableState.destroyed = false;
  28452. this._readableState.reading = false;
  28453. this._readableState.ended = false;
  28454. this._readableState.endEmitted = false;
  28455. }
  28456. if (this._writableState) {
  28457. this._writableState.destroyed = false;
  28458. this._writableState.ended = false;
  28459. this._writableState.ending = false;
  28460. this._writableState.finished = false;
  28461. this._writableState.errorEmitted = false;
  28462. }
  28463. }
  28464. function emitErrorNT(self, err) {
  28465. self.emit('error', err);
  28466. }
  28467. module.exports = {
  28468. destroy: destroy,
  28469. undestroy: undestroy
  28470. };
  28471. },{"process-nextick-args":311}],325:[function(require,module,exports){
  28472. module.exports = require('events').EventEmitter;
  28473. },{"events":239}],326:[function(require,module,exports){
  28474. /* eslint-disable node/no-deprecated-api */
  28475. var buffer = require('buffer')
  28476. var Buffer = buffer.Buffer
  28477. // alternative to using Object.keys for old browsers
  28478. function copyProps (src, dst) {
  28479. for (var key in src) {
  28480. dst[key] = src[key]
  28481. }
  28482. }
  28483. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  28484. module.exports = buffer
  28485. } else {
  28486. // Copy properties from require('buffer')
  28487. copyProps(buffer, exports)
  28488. exports.Buffer = SafeBuffer
  28489. }
  28490. function SafeBuffer (arg, encodingOrOffset, length) {
  28491. return Buffer(arg, encodingOrOffset, length)
  28492. }
  28493. // Copy static methods from Buffer
  28494. copyProps(Buffer, SafeBuffer)
  28495. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  28496. if (typeof arg === 'number') {
  28497. throw new TypeError('Argument must not be a number')
  28498. }
  28499. return Buffer(arg, encodingOrOffset, length)
  28500. }
  28501. SafeBuffer.alloc = function (size, fill, encoding) {
  28502. if (typeof size !== 'number') {
  28503. throw new TypeError('Argument must be a number')
  28504. }
  28505. var buf = Buffer(size)
  28506. if (fill !== undefined) {
  28507. if (typeof encoding === 'string') {
  28508. buf.fill(fill, encoding)
  28509. } else {
  28510. buf.fill(fill)
  28511. }
  28512. } else {
  28513. buf.fill(0)
  28514. }
  28515. return buf
  28516. }
  28517. SafeBuffer.allocUnsafe = function (size) {
  28518. if (typeof size !== 'number') {
  28519. throw new TypeError('Argument must be a number')
  28520. }
  28521. return Buffer(size)
  28522. }
  28523. SafeBuffer.allocUnsafeSlow = function (size) {
  28524. if (typeof size !== 'number') {
  28525. throw new TypeError('Argument must be a number')
  28526. }
  28527. return buffer.SlowBuffer(size)
  28528. }
  28529. },{"buffer":47}],327:[function(require,module,exports){
  28530. // Copyright Joyent, Inc. and other Node contributors.
  28531. //
  28532. // Permission is hereby granted, free of charge, to any person obtaining a
  28533. // copy of this software and associated documentation files (the
  28534. // "Software"), to deal in the Software without restriction, including
  28535. // without limitation the rights to use, copy, modify, merge, publish,
  28536. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28537. // persons to whom the Software is furnished to do so, subject to the
  28538. // following conditions:
  28539. //
  28540. // The above copyright notice and this permission notice shall be included
  28541. // in all copies or substantial portions of the Software.
  28542. //
  28543. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28544. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28545. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28546. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28547. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28548. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28549. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28550. 'use strict';
  28551. /*<replacement>*/
  28552. var Buffer = require('safe-buffer').Buffer;
  28553. /*</replacement>*/
  28554. var isEncoding = Buffer.isEncoding || function (encoding) {
  28555. encoding = '' + encoding;
  28556. switch (encoding && encoding.toLowerCase()) {
  28557. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  28558. return true;
  28559. default:
  28560. return false;
  28561. }
  28562. };
  28563. function _normalizeEncoding(enc) {
  28564. if (!enc) return 'utf8';
  28565. var retried;
  28566. while (true) {
  28567. switch (enc) {
  28568. case 'utf8':
  28569. case 'utf-8':
  28570. return 'utf8';
  28571. case 'ucs2':
  28572. case 'ucs-2':
  28573. case 'utf16le':
  28574. case 'utf-16le':
  28575. return 'utf16le';
  28576. case 'latin1':
  28577. case 'binary':
  28578. return 'latin1';
  28579. case 'base64':
  28580. case 'ascii':
  28581. case 'hex':
  28582. return enc;
  28583. default:
  28584. if (retried) return; // undefined
  28585. enc = ('' + enc).toLowerCase();
  28586. retried = true;
  28587. }
  28588. }
  28589. };
  28590. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  28591. // modules monkey-patch it to support additional encodings
  28592. function normalizeEncoding(enc) {
  28593. var nenc = _normalizeEncoding(enc);
  28594. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  28595. return nenc || enc;
  28596. }
  28597. // StringDecoder provides an interface for efficiently splitting a series of
  28598. // buffers into a series of JS strings without breaking apart multi-byte
  28599. // characters.
  28600. exports.StringDecoder = StringDecoder;
  28601. function StringDecoder(encoding) {
  28602. this.encoding = normalizeEncoding(encoding);
  28603. var nb;
  28604. switch (this.encoding) {
  28605. case 'utf16le':
  28606. this.text = utf16Text;
  28607. this.end = utf16End;
  28608. nb = 4;
  28609. break;
  28610. case 'utf8':
  28611. this.fillLast = utf8FillLast;
  28612. nb = 4;
  28613. break;
  28614. case 'base64':
  28615. this.text = base64Text;
  28616. this.end = base64End;
  28617. nb = 3;
  28618. break;
  28619. default:
  28620. this.write = simpleWrite;
  28621. this.end = simpleEnd;
  28622. return;
  28623. }
  28624. this.lastNeed = 0;
  28625. this.lastTotal = 0;
  28626. this.lastChar = Buffer.allocUnsafe(nb);
  28627. }
  28628. StringDecoder.prototype.write = function (buf) {
  28629. if (buf.length === 0) return '';
  28630. var r;
  28631. var i;
  28632. if (this.lastNeed) {
  28633. r = this.fillLast(buf);
  28634. if (r === undefined) return '';
  28635. i = this.lastNeed;
  28636. this.lastNeed = 0;
  28637. } else {
  28638. i = 0;
  28639. }
  28640. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  28641. return r || '';
  28642. };
  28643. StringDecoder.prototype.end = utf8End;
  28644. // Returns only complete characters in a Buffer
  28645. StringDecoder.prototype.text = utf8Text;
  28646. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  28647. StringDecoder.prototype.fillLast = function (buf) {
  28648. if (this.lastNeed <= buf.length) {
  28649. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  28650. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  28651. }
  28652. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  28653. this.lastNeed -= buf.length;
  28654. };
  28655. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  28656. // continuation byte. If an invalid byte is detected, -2 is returned.
  28657. function utf8CheckByte(byte) {
  28658. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  28659. return byte >> 6 === 0x02 ? -1 : -2;
  28660. }
  28661. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  28662. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  28663. // needed to complete the UTF-8 character (if applicable) are returned.
  28664. function utf8CheckIncomplete(self, buf, i) {
  28665. var j = buf.length - 1;
  28666. if (j < i) return 0;
  28667. var nb = utf8CheckByte(buf[j]);
  28668. if (nb >= 0) {
  28669. if (nb > 0) self.lastNeed = nb - 1;
  28670. return nb;
  28671. }
  28672. if (--j < i || nb === -2) return 0;
  28673. nb = utf8CheckByte(buf[j]);
  28674. if (nb >= 0) {
  28675. if (nb > 0) self.lastNeed = nb - 2;
  28676. return nb;
  28677. }
  28678. if (--j < i || nb === -2) return 0;
  28679. nb = utf8CheckByte(buf[j]);
  28680. if (nb >= 0) {
  28681. if (nb > 0) {
  28682. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  28683. }
  28684. return nb;
  28685. }
  28686. return 0;
  28687. }
  28688. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  28689. // needed or are available. If we see a non-continuation byte where we expect
  28690. // one, we "replace" the validated continuation bytes we've seen so far with
  28691. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  28692. // behavior. The continuation byte check is included three times in the case
  28693. // where all of the continuation bytes for a character exist in the same buffer.
  28694. // It is also done this way as a slight performance increase instead of using a
  28695. // loop.
  28696. function utf8CheckExtraBytes(self, buf, p) {
  28697. if ((buf[0] & 0xC0) !== 0x80) {
  28698. self.lastNeed = 0;
  28699. return '\ufffd';
  28700. }
  28701. if (self.lastNeed > 1 && buf.length > 1) {
  28702. if ((buf[1] & 0xC0) !== 0x80) {
  28703. self.lastNeed = 1;
  28704. return '\ufffd';
  28705. }
  28706. if (self.lastNeed > 2 && buf.length > 2) {
  28707. if ((buf[2] & 0xC0) !== 0x80) {
  28708. self.lastNeed = 2;
  28709. return '\ufffd';
  28710. }
  28711. }
  28712. }
  28713. }
  28714. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  28715. function utf8FillLast(buf) {
  28716. var p = this.lastTotal - this.lastNeed;
  28717. var r = utf8CheckExtraBytes(this, buf, p);
  28718. if (r !== undefined) return r;
  28719. if (this.lastNeed <= buf.length) {
  28720. buf.copy(this.lastChar, p, 0, this.lastNeed);
  28721. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  28722. }
  28723. buf.copy(this.lastChar, p, 0, buf.length);
  28724. this.lastNeed -= buf.length;
  28725. }
  28726. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  28727. // partial character, the character's bytes are buffered until the required
  28728. // number of bytes are available.
  28729. function utf8Text(buf, i) {
  28730. var total = utf8CheckIncomplete(this, buf, i);
  28731. if (!this.lastNeed) return buf.toString('utf8', i);
  28732. this.lastTotal = total;
  28733. var end = buf.length - (total - this.lastNeed);
  28734. buf.copy(this.lastChar, 0, end);
  28735. return buf.toString('utf8', i, end);
  28736. }
  28737. // For UTF-8, a replacement character is added when ending on a partial
  28738. // character.
  28739. function utf8End(buf) {
  28740. var r = buf && buf.length ? this.write(buf) : '';
  28741. if (this.lastNeed) return r + '\ufffd';
  28742. return r;
  28743. }
  28744. // UTF-16LE typically needs two bytes per character, but even if we have an even
  28745. // number of bytes available, we need to check if we end on a leading/high
  28746. // surrogate. In that case, we need to wait for the next two bytes in order to
  28747. // decode the last character properly.
  28748. function utf16Text(buf, i) {
  28749. if ((buf.length - i) % 2 === 0) {
  28750. var r = buf.toString('utf16le', i);
  28751. if (r) {
  28752. var c = r.charCodeAt(r.length - 1);
  28753. if (c >= 0xD800 && c <= 0xDBFF) {
  28754. this.lastNeed = 2;
  28755. this.lastTotal = 4;
  28756. this.lastChar[0] = buf[buf.length - 2];
  28757. this.lastChar[1] = buf[buf.length - 1];
  28758. return r.slice(0, -1);
  28759. }
  28760. }
  28761. return r;
  28762. }
  28763. this.lastNeed = 1;
  28764. this.lastTotal = 2;
  28765. this.lastChar[0] = buf[buf.length - 1];
  28766. return buf.toString('utf16le', i, buf.length - 1);
  28767. }
  28768. // For UTF-16LE we do not explicitly append special replacement characters if we
  28769. // end on a partial character, we simply let v8 handle that.
  28770. function utf16End(buf) {
  28771. var r = buf && buf.length ? this.write(buf) : '';
  28772. if (this.lastNeed) {
  28773. var end = this.lastTotal - this.lastNeed;
  28774. return r + this.lastChar.toString('utf16le', 0, end);
  28775. }
  28776. return r;
  28777. }
  28778. function base64Text(buf, i) {
  28779. var n = (buf.length - i) % 3;
  28780. if (n === 0) return buf.toString('base64', i);
  28781. this.lastNeed = 3 - n;
  28782. this.lastTotal = 3;
  28783. if (n === 1) {
  28784. this.lastChar[0] = buf[buf.length - 1];
  28785. } else {
  28786. this.lastChar[0] = buf[buf.length - 2];
  28787. this.lastChar[1] = buf[buf.length - 1];
  28788. }
  28789. return buf.toString('base64', i, buf.length - n);
  28790. }
  28791. function base64End(buf) {
  28792. var r = buf && buf.length ? this.write(buf) : '';
  28793. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  28794. return r;
  28795. }
  28796. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  28797. function simpleWrite(buf) {
  28798. return buf.toString(this.encoding);
  28799. }
  28800. function simpleEnd(buf) {
  28801. return buf && buf.length ? this.write(buf) : '';
  28802. }
  28803. },{"safe-buffer":326}],328:[function(require,module,exports){
  28804. module.exports = require('./readable').PassThrough
  28805. },{"./readable":329}],329:[function(require,module,exports){
  28806. exports = module.exports = require('./lib/_stream_readable.js');
  28807. exports.Stream = exports;
  28808. exports.Readable = exports;
  28809. exports.Writable = require('./lib/_stream_writable.js');
  28810. exports.Duplex = require('./lib/_stream_duplex.js');
  28811. exports.Transform = require('./lib/_stream_transform.js');
  28812. exports.PassThrough = require('./lib/_stream_passthrough.js');
  28813. },{"./lib/_stream_duplex.js":318,"./lib/_stream_passthrough.js":319,"./lib/_stream_readable.js":320,"./lib/_stream_transform.js":321,"./lib/_stream_writable.js":322}],330:[function(require,module,exports){
  28814. module.exports = require('./readable').Transform
  28815. },{"./readable":329}],331:[function(require,module,exports){
  28816. module.exports = require('./lib/_stream_writable.js');
  28817. },{"./lib/_stream_writable.js":322}],332:[function(require,module,exports){
  28818. /**
  28819. * Copyright (c) 2014-present, Facebook, Inc.
  28820. *
  28821. * This source code is licensed under the MIT license found in the
  28822. * LICENSE file in the root directory of this source tree.
  28823. */
  28824. var runtime = (function (exports) {
  28825. "use strict";
  28826. var Op = Object.prototype;
  28827. var hasOwn = Op.hasOwnProperty;
  28828. var undefined; // More compressible than void 0.
  28829. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  28830. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  28831. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  28832. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  28833. function wrap(innerFn, outerFn, self, tryLocsList) {
  28834. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  28835. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  28836. var generator = Object.create(protoGenerator.prototype);
  28837. var context = new Context(tryLocsList || []);
  28838. // The ._invoke method unifies the implementations of the .next,
  28839. // .throw, and .return methods.
  28840. generator._invoke = makeInvokeMethod(innerFn, self, context);
  28841. return generator;
  28842. }
  28843. exports.wrap = wrap;
  28844. // Try/catch helper to minimize deoptimizations. Returns a completion
  28845. // record like context.tryEntries[i].completion. This interface could
  28846. // have been (and was previously) designed to take a closure to be
  28847. // invoked without arguments, but in all the cases we care about we
  28848. // already have an existing method we want to call, so there's no need
  28849. // to create a new function object. We can even get away with assuming
  28850. // the method takes exactly one argument, since that happens to be true
  28851. // in every case, so we don't have to touch the arguments object. The
  28852. // only additional allocation required is the completion record, which
  28853. // has a stable shape and so hopefully should be cheap to allocate.
  28854. function tryCatch(fn, obj, arg) {
  28855. try {
  28856. return { type: "normal", arg: fn.call(obj, arg) };
  28857. } catch (err) {
  28858. return { type: "throw", arg: err };
  28859. }
  28860. }
  28861. var GenStateSuspendedStart = "suspendedStart";
  28862. var GenStateSuspendedYield = "suspendedYield";
  28863. var GenStateExecuting = "executing";
  28864. var GenStateCompleted = "completed";
  28865. // Returning this object from the innerFn has the same effect as
  28866. // breaking out of the dispatch switch statement.
  28867. var ContinueSentinel = {};
  28868. // Dummy constructor functions that we use as the .constructor and
  28869. // .constructor.prototype properties for functions that return Generator
  28870. // objects. For full spec compliance, you may wish to configure your
  28871. // minifier not to mangle the names of these two functions.
  28872. function Generator() {}
  28873. function GeneratorFunction() {}
  28874. function GeneratorFunctionPrototype() {}
  28875. // This is a polyfill for %IteratorPrototype% for environments that
  28876. // don't natively support it.
  28877. var IteratorPrototype = {};
  28878. IteratorPrototype[iteratorSymbol] = function () {
  28879. return this;
  28880. };
  28881. var getProto = Object.getPrototypeOf;
  28882. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  28883. if (NativeIteratorPrototype &&
  28884. NativeIteratorPrototype !== Op &&
  28885. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  28886. // This environment has a native %IteratorPrototype%; use it instead
  28887. // of the polyfill.
  28888. IteratorPrototype = NativeIteratorPrototype;
  28889. }
  28890. var Gp = GeneratorFunctionPrototype.prototype =
  28891. Generator.prototype = Object.create(IteratorPrototype);
  28892. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  28893. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  28894. GeneratorFunctionPrototype[toStringTagSymbol] =
  28895. GeneratorFunction.displayName = "GeneratorFunction";
  28896. // Helper for defining the .next, .throw, and .return methods of the
  28897. // Iterator interface in terms of a single ._invoke method.
  28898. function defineIteratorMethods(prototype) {
  28899. ["next", "throw", "return"].forEach(function(method) {
  28900. prototype[method] = function(arg) {
  28901. return this._invoke(method, arg);
  28902. };
  28903. });
  28904. }
  28905. exports.isGeneratorFunction = function(genFun) {
  28906. var ctor = typeof genFun === "function" && genFun.constructor;
  28907. return ctor
  28908. ? ctor === GeneratorFunction ||
  28909. // For the native GeneratorFunction constructor, the best we can
  28910. // do is to check its .name property.
  28911. (ctor.displayName || ctor.name) === "GeneratorFunction"
  28912. : false;
  28913. };
  28914. exports.mark = function(genFun) {
  28915. if (Object.setPrototypeOf) {
  28916. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  28917. } else {
  28918. genFun.__proto__ = GeneratorFunctionPrototype;
  28919. if (!(toStringTagSymbol in genFun)) {
  28920. genFun[toStringTagSymbol] = "GeneratorFunction";
  28921. }
  28922. }
  28923. genFun.prototype = Object.create(Gp);
  28924. return genFun;
  28925. };
  28926. // Within the body of any async function, `await x` is transformed to
  28927. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  28928. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  28929. // meant to be awaited.
  28930. exports.awrap = function(arg) {
  28931. return { __await: arg };
  28932. };
  28933. function AsyncIterator(generator) {
  28934. function invoke(method, arg, resolve, reject) {
  28935. var record = tryCatch(generator[method], generator, arg);
  28936. if (record.type === "throw") {
  28937. reject(record.arg);
  28938. } else {
  28939. var result = record.arg;
  28940. var value = result.value;
  28941. if (value &&
  28942. typeof value === "object" &&
  28943. hasOwn.call(value, "__await")) {
  28944. return Promise.resolve(value.__await).then(function(value) {
  28945. invoke("next", value, resolve, reject);
  28946. }, function(err) {
  28947. invoke("throw", err, resolve, reject);
  28948. });
  28949. }
  28950. return Promise.resolve(value).then(function(unwrapped) {
  28951. // When a yielded Promise is resolved, its final value becomes
  28952. // the .value of the Promise<{value,done}> result for the
  28953. // current iteration.
  28954. result.value = unwrapped;
  28955. resolve(result);
  28956. }, function(error) {
  28957. // If a rejected Promise was yielded, throw the rejection back
  28958. // into the async generator function so it can be handled there.
  28959. return invoke("throw", error, resolve, reject);
  28960. });
  28961. }
  28962. }
  28963. var previousPromise;
  28964. function enqueue(method, arg) {
  28965. function callInvokeWithMethodAndArg() {
  28966. return new Promise(function(resolve, reject) {
  28967. invoke(method, arg, resolve, reject);
  28968. });
  28969. }
  28970. return previousPromise =
  28971. // If enqueue has been called before, then we want to wait until
  28972. // all previous Promises have been resolved before calling invoke,
  28973. // so that results are always delivered in the correct order. If
  28974. // enqueue has not been called before, then it is important to
  28975. // call invoke immediately, without waiting on a callback to fire,
  28976. // so that the async generator function has the opportunity to do
  28977. // any necessary setup in a predictable way. This predictability
  28978. // is why the Promise constructor synchronously invokes its
  28979. // executor callback, and why async functions synchronously
  28980. // execute code before the first await. Since we implement simple
  28981. // async functions in terms of async generators, it is especially
  28982. // important to get this right, even though it requires care.
  28983. previousPromise ? previousPromise.then(
  28984. callInvokeWithMethodAndArg,
  28985. // Avoid propagating failures to Promises returned by later
  28986. // invocations of the iterator.
  28987. callInvokeWithMethodAndArg
  28988. ) : callInvokeWithMethodAndArg();
  28989. }
  28990. // Define the unified helper method that is used to implement .next,
  28991. // .throw, and .return (see defineIteratorMethods).
  28992. this._invoke = enqueue;
  28993. }
  28994. defineIteratorMethods(AsyncIterator.prototype);
  28995. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  28996. return this;
  28997. };
  28998. exports.AsyncIterator = AsyncIterator;
  28999. // Note that simple async functions are implemented on top of
  29000. // AsyncIterator objects; they just return a Promise for the value of
  29001. // the final result produced by the iterator.
  29002. exports.async = function(innerFn, outerFn, self, tryLocsList) {
  29003. var iter = new AsyncIterator(
  29004. wrap(innerFn, outerFn, self, tryLocsList)
  29005. );
  29006. return exports.isGeneratorFunction(outerFn)
  29007. ? iter // If outerFn is a generator, return the full iterator.
  29008. : iter.next().then(function(result) {
  29009. return result.done ? result.value : iter.next();
  29010. });
  29011. };
  29012. function makeInvokeMethod(innerFn, self, context) {
  29013. var state = GenStateSuspendedStart;
  29014. return function invoke(method, arg) {
  29015. if (state === GenStateExecuting) {
  29016. throw new Error("Generator is already running");
  29017. }
  29018. if (state === GenStateCompleted) {
  29019. if (method === "throw") {
  29020. throw arg;
  29021. }
  29022. // Be forgiving, per 25.3.3.3.3 of the spec:
  29023. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  29024. return doneResult();
  29025. }
  29026. context.method = method;
  29027. context.arg = arg;
  29028. while (true) {
  29029. var delegate = context.delegate;
  29030. if (delegate) {
  29031. var delegateResult = maybeInvokeDelegate(delegate, context);
  29032. if (delegateResult) {
  29033. if (delegateResult === ContinueSentinel) continue;
  29034. return delegateResult;
  29035. }
  29036. }
  29037. if (context.method === "next") {
  29038. // Setting context._sent for legacy support of Babel's
  29039. // function.sent implementation.
  29040. context.sent = context._sent = context.arg;
  29041. } else if (context.method === "throw") {
  29042. if (state === GenStateSuspendedStart) {
  29043. state = GenStateCompleted;
  29044. throw context.arg;
  29045. }
  29046. context.dispatchException(context.arg);
  29047. } else if (context.method === "return") {
  29048. context.abrupt("return", context.arg);
  29049. }
  29050. state = GenStateExecuting;
  29051. var record = tryCatch(innerFn, self, context);
  29052. if (record.type === "normal") {
  29053. // If an exception is thrown from innerFn, we leave state ===
  29054. // GenStateExecuting and loop back for another invocation.
  29055. state = context.done
  29056. ? GenStateCompleted
  29057. : GenStateSuspendedYield;
  29058. if (record.arg === ContinueSentinel) {
  29059. continue;
  29060. }
  29061. return {
  29062. value: record.arg,
  29063. done: context.done
  29064. };
  29065. } else if (record.type === "throw") {
  29066. state = GenStateCompleted;
  29067. // Dispatch the exception by looping back around to the
  29068. // context.dispatchException(context.arg) call above.
  29069. context.method = "throw";
  29070. context.arg = record.arg;
  29071. }
  29072. }
  29073. };
  29074. }
  29075. // Call delegate.iterator[context.method](context.arg) and handle the
  29076. // result, either by returning a { value, done } result from the
  29077. // delegate iterator, or by modifying context.method and context.arg,
  29078. // setting context.delegate to null, and returning the ContinueSentinel.
  29079. function maybeInvokeDelegate(delegate, context) {
  29080. var method = delegate.iterator[context.method];
  29081. if (method === undefined) {
  29082. // A .throw or .return when the delegate iterator has no .throw
  29083. // method always terminates the yield* loop.
  29084. context.delegate = null;
  29085. if (context.method === "throw") {
  29086. // Note: ["return"] must be used for ES3 parsing compatibility.
  29087. if (delegate.iterator["return"]) {
  29088. // If the delegate iterator has a return method, give it a
  29089. // chance to clean up.
  29090. context.method = "return";
  29091. context.arg = undefined;
  29092. maybeInvokeDelegate(delegate, context);
  29093. if (context.method === "throw") {
  29094. // If maybeInvokeDelegate(context) changed context.method from
  29095. // "return" to "throw", let that override the TypeError below.
  29096. return ContinueSentinel;
  29097. }
  29098. }
  29099. context.method = "throw";
  29100. context.arg = new TypeError(
  29101. "The iterator does not provide a 'throw' method");
  29102. }
  29103. return ContinueSentinel;
  29104. }
  29105. var record = tryCatch(method, delegate.iterator, context.arg);
  29106. if (record.type === "throw") {
  29107. context.method = "throw";
  29108. context.arg = record.arg;
  29109. context.delegate = null;
  29110. return ContinueSentinel;
  29111. }
  29112. var info = record.arg;
  29113. if (! info) {
  29114. context.method = "throw";
  29115. context.arg = new TypeError("iterator result is not an object");
  29116. context.delegate = null;
  29117. return ContinueSentinel;
  29118. }
  29119. if (info.done) {
  29120. // Assign the result of the finished delegate to the temporary
  29121. // variable specified by delegate.resultName (see delegateYield).
  29122. context[delegate.resultName] = info.value;
  29123. // Resume execution at the desired location (see delegateYield).
  29124. context.next = delegate.nextLoc;
  29125. // If context.method was "throw" but the delegate handled the
  29126. // exception, let the outer generator proceed normally. If
  29127. // context.method was "next", forget context.arg since it has been
  29128. // "consumed" by the delegate iterator. If context.method was
  29129. // "return", allow the original .return call to continue in the
  29130. // outer generator.
  29131. if (context.method !== "return") {
  29132. context.method = "next";
  29133. context.arg = undefined;
  29134. }
  29135. } else {
  29136. // Re-yield the result returned by the delegate method.
  29137. return info;
  29138. }
  29139. // The delegate iterator is finished, so forget it and continue with
  29140. // the outer generator.
  29141. context.delegate = null;
  29142. return ContinueSentinel;
  29143. }
  29144. // Define Generator.prototype.{next,throw,return} in terms of the
  29145. // unified ._invoke helper method.
  29146. defineIteratorMethods(Gp);
  29147. Gp[toStringTagSymbol] = "Generator";
  29148. // A Generator should always return itself as the iterator object when the
  29149. // @@iterator function is called on it. Some browsers' implementations of the
  29150. // iterator prototype chain incorrectly implement this, causing the Generator
  29151. // object to not be returned from this call. This ensures that doesn't happen.
  29152. // See https://github.com/facebook/regenerator/issues/274 for more details.
  29153. Gp[iteratorSymbol] = function() {
  29154. return this;
  29155. };
  29156. Gp.toString = function() {
  29157. return "[object Generator]";
  29158. };
  29159. function pushTryEntry(locs) {
  29160. var entry = { tryLoc: locs[0] };
  29161. if (1 in locs) {
  29162. entry.catchLoc = locs[1];
  29163. }
  29164. if (2 in locs) {
  29165. entry.finallyLoc = locs[2];
  29166. entry.afterLoc = locs[3];
  29167. }
  29168. this.tryEntries.push(entry);
  29169. }
  29170. function resetTryEntry(entry) {
  29171. var record = entry.completion || {};
  29172. record.type = "normal";
  29173. delete record.arg;
  29174. entry.completion = record;
  29175. }
  29176. function Context(tryLocsList) {
  29177. // The root entry object (effectively a try statement without a catch
  29178. // or a finally block) gives us a place to store values thrown from
  29179. // locations where there is no enclosing try statement.
  29180. this.tryEntries = [{ tryLoc: "root" }];
  29181. tryLocsList.forEach(pushTryEntry, this);
  29182. this.reset(true);
  29183. }
  29184. exports.keys = function(object) {
  29185. var keys = [];
  29186. for (var key in object) {
  29187. keys.push(key);
  29188. }
  29189. keys.reverse();
  29190. // Rather than returning an object with a next method, we keep
  29191. // things simple and return the next function itself.
  29192. return function next() {
  29193. while (keys.length) {
  29194. var key = keys.pop();
  29195. if (key in object) {
  29196. next.value = key;
  29197. next.done = false;
  29198. return next;
  29199. }
  29200. }
  29201. // To avoid creating an additional object, we just hang the .value
  29202. // and .done properties off the next function object itself. This
  29203. // also ensures that the minifier will not anonymize the function.
  29204. next.done = true;
  29205. return next;
  29206. };
  29207. };
  29208. function values(iterable) {
  29209. if (iterable) {
  29210. var iteratorMethod = iterable[iteratorSymbol];
  29211. if (iteratorMethod) {
  29212. return iteratorMethod.call(iterable);
  29213. }
  29214. if (typeof iterable.next === "function") {
  29215. return iterable;
  29216. }
  29217. if (!isNaN(iterable.length)) {
  29218. var i = -1, next = function next() {
  29219. while (++i < iterable.length) {
  29220. if (hasOwn.call(iterable, i)) {
  29221. next.value = iterable[i];
  29222. next.done = false;
  29223. return next;
  29224. }
  29225. }
  29226. next.value = undefined;
  29227. next.done = true;
  29228. return next;
  29229. };
  29230. return next.next = next;
  29231. }
  29232. }
  29233. // Return an iterator with no values.
  29234. return { next: doneResult };
  29235. }
  29236. exports.values = values;
  29237. function doneResult() {
  29238. return { value: undefined, done: true };
  29239. }
  29240. Context.prototype = {
  29241. constructor: Context,
  29242. reset: function(skipTempReset) {
  29243. this.prev = 0;
  29244. this.next = 0;
  29245. // Resetting context._sent for legacy support of Babel's
  29246. // function.sent implementation.
  29247. this.sent = this._sent = undefined;
  29248. this.done = false;
  29249. this.delegate = null;
  29250. this.method = "next";
  29251. this.arg = undefined;
  29252. this.tryEntries.forEach(resetTryEntry);
  29253. if (!skipTempReset) {
  29254. for (var name in this) {
  29255. // Not sure about the optimal order of these conditions:
  29256. if (name.charAt(0) === "t" &&
  29257. hasOwn.call(this, name) &&
  29258. !isNaN(+name.slice(1))) {
  29259. this[name] = undefined;
  29260. }
  29261. }
  29262. }
  29263. },
  29264. stop: function() {
  29265. this.done = true;
  29266. var rootEntry = this.tryEntries[0];
  29267. var rootRecord = rootEntry.completion;
  29268. if (rootRecord.type === "throw") {
  29269. throw rootRecord.arg;
  29270. }
  29271. return this.rval;
  29272. },
  29273. dispatchException: function(exception) {
  29274. if (this.done) {
  29275. throw exception;
  29276. }
  29277. var context = this;
  29278. function handle(loc, caught) {
  29279. record.type = "throw";
  29280. record.arg = exception;
  29281. context.next = loc;
  29282. if (caught) {
  29283. // If the dispatched exception was caught by a catch block,
  29284. // then let that catch block handle the exception normally.
  29285. context.method = "next";
  29286. context.arg = undefined;
  29287. }
  29288. return !! caught;
  29289. }
  29290. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  29291. var entry = this.tryEntries[i];
  29292. var record = entry.completion;
  29293. if (entry.tryLoc === "root") {
  29294. // Exception thrown outside of any try block that could handle
  29295. // it, so set the completion value of the entire function to
  29296. // throw the exception.
  29297. return handle("end");
  29298. }
  29299. if (entry.tryLoc <= this.prev) {
  29300. var hasCatch = hasOwn.call(entry, "catchLoc");
  29301. var hasFinally = hasOwn.call(entry, "finallyLoc");
  29302. if (hasCatch && hasFinally) {
  29303. if (this.prev < entry.catchLoc) {
  29304. return handle(entry.catchLoc, true);
  29305. } else if (this.prev < entry.finallyLoc) {
  29306. return handle(entry.finallyLoc);
  29307. }
  29308. } else if (hasCatch) {
  29309. if (this.prev < entry.catchLoc) {
  29310. return handle(entry.catchLoc, true);
  29311. }
  29312. } else if (hasFinally) {
  29313. if (this.prev < entry.finallyLoc) {
  29314. return handle(entry.finallyLoc);
  29315. }
  29316. } else {
  29317. throw new Error("try statement without catch or finally");
  29318. }
  29319. }
  29320. }
  29321. },
  29322. abrupt: function(type, arg) {
  29323. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  29324. var entry = this.tryEntries[i];
  29325. if (entry.tryLoc <= this.prev &&
  29326. hasOwn.call(entry, "finallyLoc") &&
  29327. this.prev < entry.finallyLoc) {
  29328. var finallyEntry = entry;
  29329. break;
  29330. }
  29331. }
  29332. if (finallyEntry &&
  29333. (type === "break" ||
  29334. type === "continue") &&
  29335. finallyEntry.tryLoc <= arg &&
  29336. arg <= finallyEntry.finallyLoc) {
  29337. // Ignore the finally entry if control is not jumping to a
  29338. // location outside the try/catch block.
  29339. finallyEntry = null;
  29340. }
  29341. var record = finallyEntry ? finallyEntry.completion : {};
  29342. record.type = type;
  29343. record.arg = arg;
  29344. if (finallyEntry) {
  29345. this.method = "next";
  29346. this.next = finallyEntry.finallyLoc;
  29347. return ContinueSentinel;
  29348. }
  29349. return this.complete(record);
  29350. },
  29351. complete: function(record, afterLoc) {
  29352. if (record.type === "throw") {
  29353. throw record.arg;
  29354. }
  29355. if (record.type === "break" ||
  29356. record.type === "continue") {
  29357. this.next = record.arg;
  29358. } else if (record.type === "return") {
  29359. this.rval = this.arg = record.arg;
  29360. this.method = "return";
  29361. this.next = "end";
  29362. } else if (record.type === "normal" && afterLoc) {
  29363. this.next = afterLoc;
  29364. }
  29365. return ContinueSentinel;
  29366. },
  29367. finish: function(finallyLoc) {
  29368. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  29369. var entry = this.tryEntries[i];
  29370. if (entry.finallyLoc === finallyLoc) {
  29371. this.complete(entry.completion, entry.afterLoc);
  29372. resetTryEntry(entry);
  29373. return ContinueSentinel;
  29374. }
  29375. }
  29376. },
  29377. "catch": function(tryLoc) {
  29378. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  29379. var entry = this.tryEntries[i];
  29380. if (entry.tryLoc === tryLoc) {
  29381. var record = entry.completion;
  29382. if (record.type === "throw") {
  29383. var thrown = record.arg;
  29384. resetTryEntry(entry);
  29385. }
  29386. return thrown;
  29387. }
  29388. }
  29389. // The context.catch method must only be called with a location
  29390. // argument that corresponds to a known catch block.
  29391. throw new Error("illegal catch attempt");
  29392. },
  29393. delegateYield: function(iterable, resultName, nextLoc) {
  29394. this.delegate = {
  29395. iterator: values(iterable),
  29396. resultName: resultName,
  29397. nextLoc: nextLoc
  29398. };
  29399. if (this.method === "next") {
  29400. // Deliberately forget the last sent value so that we don't
  29401. // accidentally pass it on to the delegate.
  29402. this.arg = undefined;
  29403. }
  29404. return ContinueSentinel;
  29405. }
  29406. };
  29407. // Regardless of whether this script is executing as a CommonJS module
  29408. // or not, return the runtime object so that we can declare the variable
  29409. // regeneratorRuntime in the outer scope, which allows this module to be
  29410. // injected easily by `bin/regenerator --include-runtime script.js`.
  29411. return exports;
  29412. }(
  29413. // If this script is executing as a CommonJS module, use module.exports
  29414. // as the regeneratorRuntime namespace. Otherwise create a new empty
  29415. // object. Either way, the resulting object will be used to initialize
  29416. // the regeneratorRuntime variable at the top of this file.
  29417. typeof module === "object" ? module.exports : {}
  29418. ));
  29419. try {
  29420. regeneratorRuntime = runtime;
  29421. } catch (accidentalStrictMode) {
  29422. // This module should not be running in strict mode, so the above
  29423. // assignment should always work unless something is misconfigured. Just
  29424. // in case runtime.js accidentally runs in strict mode, we can escape
  29425. // strict mode using a global Function call. This could conceivably fail
  29426. // if a Content Security Policy forbids using Function, but in that case
  29427. // the proper solution is to fix the accidental strict mode problem. If
  29428. // you've misconfigured your bundler to force strict mode and applied a
  29429. // CSP to forbid Function, and you're not willing to fix either of those
  29430. // problems, please detail your unique predicament in a GitHub issue.
  29431. Function("r", "regeneratorRuntime = r")(runtime);
  29432. }
  29433. },{}],333:[function(require,module,exports){
  29434. /* eslint-disable node/no-deprecated-api */
  29435. var buffer = require('buffer')
  29436. var Buffer = buffer.Buffer
  29437. // alternative to using Object.keys for old browsers
  29438. function copyProps (src, dst) {
  29439. for (var key in src) {
  29440. dst[key] = src[key]
  29441. }
  29442. }
  29443. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  29444. module.exports = buffer
  29445. } else {
  29446. // Copy properties from require('buffer')
  29447. copyProps(buffer, exports)
  29448. exports.Buffer = SafeBuffer
  29449. }
  29450. function SafeBuffer (arg, encodingOrOffset, length) {
  29451. return Buffer(arg, encodingOrOffset, length)
  29452. }
  29453. SafeBuffer.prototype = Object.create(Buffer.prototype)
  29454. // Copy static methods from Buffer
  29455. copyProps(Buffer, SafeBuffer)
  29456. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  29457. if (typeof arg === 'number') {
  29458. throw new TypeError('Argument must not be a number')
  29459. }
  29460. return Buffer(arg, encodingOrOffset, length)
  29461. }
  29462. SafeBuffer.alloc = function (size, fill, encoding) {
  29463. if (typeof size !== 'number') {
  29464. throw new TypeError('Argument must be a number')
  29465. }
  29466. var buf = Buffer(size)
  29467. if (fill !== undefined) {
  29468. if (typeof encoding === 'string') {
  29469. buf.fill(fill, encoding)
  29470. } else {
  29471. buf.fill(fill)
  29472. }
  29473. } else {
  29474. buf.fill(0)
  29475. }
  29476. return buf
  29477. }
  29478. SafeBuffer.allocUnsafe = function (size) {
  29479. if (typeof size !== 'number') {
  29480. throw new TypeError('Argument must be a number')
  29481. }
  29482. return Buffer(size)
  29483. }
  29484. SafeBuffer.allocUnsafeSlow = function (size) {
  29485. if (typeof size !== 'number') {
  29486. throw new TypeError('Argument must be a number')
  29487. }
  29488. return buffer.SlowBuffer(size)
  29489. }
  29490. },{"buffer":47}],334:[function(require,module,exports){
  29491. // Copyright Joyent, Inc. and other Node contributors.
  29492. //
  29493. // Permission is hereby granted, free of charge, to any person obtaining a
  29494. // copy of this software and associated documentation files (the
  29495. // "Software"), to deal in the Software without restriction, including
  29496. // without limitation the rights to use, copy, modify, merge, publish,
  29497. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29498. // persons to whom the Software is furnished to do so, subject to the
  29499. // following conditions:
  29500. //
  29501. // The above copyright notice and this permission notice shall be included
  29502. // in all copies or substantial portions of the Software.
  29503. //
  29504. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29505. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29506. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29507. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29508. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29509. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29510. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29511. module.exports = Stream;
  29512. var EE = require('events').EventEmitter;
  29513. var inherits = require('inherits');
  29514. inherits(Stream, EE);
  29515. Stream.Readable = require('readable-stream/readable.js');
  29516. Stream.Writable = require('readable-stream/writable.js');
  29517. Stream.Duplex = require('readable-stream/duplex.js');
  29518. Stream.Transform = require('readable-stream/transform.js');
  29519. Stream.PassThrough = require('readable-stream/passthrough.js');
  29520. // Backwards-compat with node 0.4.x
  29521. Stream.Stream = Stream;
  29522. // old-style streams. Note that the pipe method (the only relevant
  29523. // part of this class) is overridden in the Readable class.
  29524. function Stream() {
  29525. EE.call(this);
  29526. }
  29527. Stream.prototype.pipe = function(dest, options) {
  29528. var source = this;
  29529. function ondata(chunk) {
  29530. if (dest.writable) {
  29531. if (false === dest.write(chunk) && source.pause) {
  29532. source.pause();
  29533. }
  29534. }
  29535. }
  29536. source.on('data', ondata);
  29537. function ondrain() {
  29538. if (source.readable && source.resume) {
  29539. source.resume();
  29540. }
  29541. }
  29542. dest.on('drain', ondrain);
  29543. // If the 'end' option is not supplied, dest.end() will be called when
  29544. // source gets the 'end' or 'close' events. Only dest.end() once.
  29545. if (!dest._isStdio && (!options || options.end !== false)) {
  29546. source.on('end', onend);
  29547. source.on('close', onclose);
  29548. }
  29549. var didOnEnd = false;
  29550. function onend() {
  29551. if (didOnEnd) return;
  29552. didOnEnd = true;
  29553. dest.end();
  29554. }
  29555. function onclose() {
  29556. if (didOnEnd) return;
  29557. didOnEnd = true;
  29558. if (typeof dest.destroy === 'function') dest.destroy();
  29559. }
  29560. // don't leave dangling pipes when there are errors.
  29561. function onerror(er) {
  29562. cleanup();
  29563. if (EE.listenerCount(this, 'error') === 0) {
  29564. throw er; // Unhandled stream error in pipe.
  29565. }
  29566. }
  29567. source.on('error', onerror);
  29568. dest.on('error', onerror);
  29569. // remove all the event listeners that were added.
  29570. function cleanup() {
  29571. source.removeListener('data', ondata);
  29572. dest.removeListener('drain', ondrain);
  29573. source.removeListener('end', onend);
  29574. source.removeListener('close', onclose);
  29575. source.removeListener('error', onerror);
  29576. dest.removeListener('error', onerror);
  29577. source.removeListener('end', cleanup);
  29578. source.removeListener('close', cleanup);
  29579. dest.removeListener('close', cleanup);
  29580. }
  29581. source.on('end', cleanup);
  29582. source.on('close', cleanup);
  29583. dest.on('close', cleanup);
  29584. dest.emit('pipe', source);
  29585. // Allow for unix-like usage: A.pipe(B).pipe(C)
  29586. return dest;
  29587. };
  29588. },{"events":239,"inherits":254,"readable-stream/duplex.js":317,"readable-stream/passthrough.js":328,"readable-stream/readable.js":329,"readable-stream/transform.js":330,"readable-stream/writable.js":331}],335:[function(require,module,exports){
  29589. (function (global){
  29590. var ClientRequest = require('./lib/request')
  29591. var response = require('./lib/response')
  29592. var extend = require('xtend')
  29593. var statusCodes = require('builtin-status-codes')
  29594. var url = require('url')
  29595. var http = exports
  29596. http.request = function (opts, cb) {
  29597. if (typeof opts === 'string')
  29598. opts = url.parse(opts)
  29599. else
  29600. opts = extend(opts)
  29601. // Normally, the page is loaded from http or https, so not specifying a protocol
  29602. // will result in a (valid) protocol-relative url. However, this won't work if
  29603. // the protocol is something else, like 'file:'
  29604. var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
  29605. var protocol = opts.protocol || defaultProtocol
  29606. var host = opts.hostname || opts.host
  29607. var port = opts.port
  29608. var path = opts.path || '/'
  29609. // Necessary for IPv6 addresses
  29610. if (host && host.indexOf(':') !== -1)
  29611. host = '[' + host + ']'
  29612. // This may be a relative url. The browser should always be able to interpret it correctly.
  29613. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
  29614. opts.method = (opts.method || 'GET').toUpperCase()
  29615. opts.headers = opts.headers || {}
  29616. // Also valid opts.auth, opts.mode
  29617. var req = new ClientRequest(opts)
  29618. if (cb)
  29619. req.on('response', cb)
  29620. return req
  29621. }
  29622. http.get = function get (opts, cb) {
  29623. var req = http.request(opts, cb)
  29624. req.end()
  29625. return req
  29626. }
  29627. http.ClientRequest = ClientRequest
  29628. http.IncomingMessage = response.IncomingMessage
  29629. http.Agent = function () {}
  29630. http.Agent.defaultMaxSockets = 4
  29631. http.globalAgent = new http.Agent()
  29632. http.STATUS_CODES = statusCodes
  29633. http.METHODS = [
  29634. 'CHECKOUT',
  29635. 'CONNECT',
  29636. 'COPY',
  29637. 'DELETE',
  29638. 'GET',
  29639. 'HEAD',
  29640. 'LOCK',
  29641. 'M-SEARCH',
  29642. 'MERGE',
  29643. 'MKACTIVITY',
  29644. 'MKCOL',
  29645. 'MOVE',
  29646. 'NOTIFY',
  29647. 'OPTIONS',
  29648. 'PATCH',
  29649. 'POST',
  29650. 'PROPFIND',
  29651. 'PROPPATCH',
  29652. 'PURGE',
  29653. 'PUT',
  29654. 'REPORT',
  29655. 'SEARCH',
  29656. 'SUBSCRIBE',
  29657. 'TRACE',
  29658. 'UNLOCK',
  29659. 'UNSUBSCRIBE'
  29660. ]
  29661. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29662. },{"./lib/request":337,"./lib/response":338,"builtin-status-codes":49,"url":359,"xtend":368}],336:[function(require,module,exports){
  29663. (function (global){
  29664. exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
  29665. exports.writableStream = isFunction(global.WritableStream)
  29666. exports.abortController = isFunction(global.AbortController)
  29667. // The xhr request to example.com may violate some restrictive CSP configurations,
  29668. // so if we're running in a browser that supports `fetch`, avoid calling getXHR()
  29669. // and assume support for certain features below.
  29670. var xhr
  29671. function getXHR () {
  29672. // Cache the xhr value
  29673. if (xhr !== undefined) return xhr
  29674. if (global.XMLHttpRequest) {
  29675. xhr = new global.XMLHttpRequest()
  29676. // If XDomainRequest is available (ie only, where xhr might not work
  29677. // cross domain), use the page location. Otherwise use example.com
  29678. // Note: this doesn't actually make an http request.
  29679. try {
  29680. xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
  29681. } catch(e) {
  29682. xhr = null
  29683. }
  29684. } else {
  29685. // Service workers don't have XHR
  29686. xhr = null
  29687. }
  29688. return xhr
  29689. }
  29690. function checkTypeSupport (type) {
  29691. var xhr = getXHR()
  29692. if (!xhr) return false
  29693. try {
  29694. xhr.responseType = type
  29695. return xhr.responseType === type
  29696. } catch (e) {}
  29697. return false
  29698. }
  29699. // If fetch is supported, then arraybuffer will be supported too. Skip calling
  29700. // checkTypeSupport(), since that calls getXHR().
  29701. exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
  29702. // These next two tests unavoidably show warnings in Chrome. Since fetch will always
  29703. // be used if it's available, just return false for these to avoid the warnings.
  29704. exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
  29705. exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
  29706. // If fetch is supported, then overrideMimeType will be supported too. Skip calling
  29707. // getXHR().
  29708. exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
  29709. function isFunction (value) {
  29710. return typeof value === 'function'
  29711. }
  29712. xhr = null // Help gc
  29713. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29714. },{}],337:[function(require,module,exports){
  29715. (function (process,global,Buffer){
  29716. var capability = require('./capability')
  29717. var inherits = require('inherits')
  29718. var response = require('./response')
  29719. var stream = require('readable-stream')
  29720. var IncomingMessage = response.IncomingMessage
  29721. var rStates = response.readyStates
  29722. function decideMode (preferBinary, useFetch) {
  29723. if (capability.fetch && useFetch) {
  29724. return 'fetch'
  29725. } else if (capability.mozchunkedarraybuffer) {
  29726. return 'moz-chunked-arraybuffer'
  29727. } else if (capability.msstream) {
  29728. return 'ms-stream'
  29729. } else if (capability.arraybuffer && preferBinary) {
  29730. return 'arraybuffer'
  29731. } else {
  29732. return 'text'
  29733. }
  29734. }
  29735. var ClientRequest = module.exports = function (opts) {
  29736. var self = this
  29737. stream.Writable.call(self)
  29738. self._opts = opts
  29739. self._body = []
  29740. self._headers = {}
  29741. if (opts.auth)
  29742. self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
  29743. Object.keys(opts.headers).forEach(function (name) {
  29744. self.setHeader(name, opts.headers[name])
  29745. })
  29746. var preferBinary
  29747. var useFetch = true
  29748. if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
  29749. // If the use of XHR should be preferred. Not typically needed.
  29750. useFetch = false
  29751. preferBinary = true
  29752. } else if (opts.mode === 'prefer-streaming') {
  29753. // If streaming is a high priority but binary compatibility and
  29754. // the accuracy of the 'content-type' header aren't
  29755. preferBinary = false
  29756. } else if (opts.mode === 'allow-wrong-content-type') {
  29757. // If streaming is more important than preserving the 'content-type' header
  29758. preferBinary = !capability.overrideMimeType
  29759. } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
  29760. // Use binary if text streaming may corrupt data or the content-type header, or for speed
  29761. preferBinary = true
  29762. } else {
  29763. throw new Error('Invalid value for opts.mode')
  29764. }
  29765. self._mode = decideMode(preferBinary, useFetch)
  29766. self._fetchTimer = null
  29767. self.on('finish', function () {
  29768. self._onFinish()
  29769. })
  29770. }
  29771. inherits(ClientRequest, stream.Writable)
  29772. ClientRequest.prototype.setHeader = function (name, value) {
  29773. var self = this
  29774. var lowerName = name.toLowerCase()
  29775. // This check is not necessary, but it prevents warnings from browsers about setting unsafe
  29776. // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
  29777. // http-browserify did it, so I will too.
  29778. if (unsafeHeaders.indexOf(lowerName) !== -1)
  29779. return
  29780. self._headers[lowerName] = {
  29781. name: name,
  29782. value: value
  29783. }
  29784. }
  29785. ClientRequest.prototype.getHeader = function (name) {
  29786. var header = this._headers[name.toLowerCase()]
  29787. if (header)
  29788. return header.value
  29789. return null
  29790. }
  29791. ClientRequest.prototype.removeHeader = function (name) {
  29792. var self = this
  29793. delete self._headers[name.toLowerCase()]
  29794. }
  29795. ClientRequest.prototype._onFinish = function () {
  29796. var self = this
  29797. if (self._destroyed)
  29798. return
  29799. var opts = self._opts
  29800. var headersObj = self._headers
  29801. var body = null
  29802. if (opts.method !== 'GET' && opts.method !== 'HEAD') {
  29803. body = new Blob(self._body, {
  29804. type: (headersObj['content-type'] || {}).value || ''
  29805. });
  29806. }
  29807. // create flattened list of headers
  29808. var headersList = []
  29809. Object.keys(headersObj).forEach(function (keyName) {
  29810. var name = headersObj[keyName].name
  29811. var value = headersObj[keyName].value
  29812. if (Array.isArray(value)) {
  29813. value.forEach(function (v) {
  29814. headersList.push([name, v])
  29815. })
  29816. } else {
  29817. headersList.push([name, value])
  29818. }
  29819. })
  29820. if (self._mode === 'fetch') {
  29821. var signal = null
  29822. var fetchTimer = null
  29823. if (capability.abortController) {
  29824. var controller = new AbortController()
  29825. signal = controller.signal
  29826. self._fetchAbortController = controller
  29827. if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
  29828. self._fetchTimer = global.setTimeout(function () {
  29829. self.emit('requestTimeout')
  29830. if (self._fetchAbortController)
  29831. self._fetchAbortController.abort()
  29832. }, opts.requestTimeout)
  29833. }
  29834. }
  29835. global.fetch(self._opts.url, {
  29836. method: self._opts.method,
  29837. headers: headersList,
  29838. body: body || undefined,
  29839. mode: 'cors',
  29840. credentials: opts.withCredentials ? 'include' : 'same-origin',
  29841. signal: signal
  29842. }).then(function (response) {
  29843. self._fetchResponse = response
  29844. self._connect()
  29845. }, function (reason) {
  29846. global.clearTimeout(self._fetchTimer)
  29847. if (!self._destroyed)
  29848. self.emit('error', reason)
  29849. })
  29850. } else {
  29851. var xhr = self._xhr = new global.XMLHttpRequest()
  29852. try {
  29853. xhr.open(self._opts.method, self._opts.url, true)
  29854. } catch (err) {
  29855. process.nextTick(function () {
  29856. self.emit('error', err)
  29857. })
  29858. return
  29859. }
  29860. // Can't set responseType on really old browsers
  29861. if ('responseType' in xhr)
  29862. xhr.responseType = self._mode
  29863. if ('withCredentials' in xhr)
  29864. xhr.withCredentials = !!opts.withCredentials
  29865. if (self._mode === 'text' && 'overrideMimeType' in xhr)
  29866. xhr.overrideMimeType('text/plain; charset=x-user-defined')
  29867. if ('requestTimeout' in opts) {
  29868. xhr.timeout = opts.requestTimeout
  29869. xhr.ontimeout = function () {
  29870. self.emit('requestTimeout')
  29871. }
  29872. }
  29873. headersList.forEach(function (header) {
  29874. xhr.setRequestHeader(header[0], header[1])
  29875. })
  29876. self._response = null
  29877. xhr.onreadystatechange = function () {
  29878. switch (xhr.readyState) {
  29879. case rStates.LOADING:
  29880. case rStates.DONE:
  29881. self._onXHRProgress()
  29882. break
  29883. }
  29884. }
  29885. // Necessary for streaming in Firefox, since xhr.response is ONLY defined
  29886. // in onprogress, not in onreadystatechange with xhr.readyState = 3
  29887. if (self._mode === 'moz-chunked-arraybuffer') {
  29888. xhr.onprogress = function () {
  29889. self._onXHRProgress()
  29890. }
  29891. }
  29892. xhr.onerror = function () {
  29893. if (self._destroyed)
  29894. return
  29895. self.emit('error', new Error('XHR error'))
  29896. }
  29897. try {
  29898. xhr.send(body)
  29899. } catch (err) {
  29900. process.nextTick(function () {
  29901. self.emit('error', err)
  29902. })
  29903. return
  29904. }
  29905. }
  29906. }
  29907. /**
  29908. * Checks if xhr.status is readable and non-zero, indicating no error.
  29909. * Even though the spec says it should be available in readyState 3,
  29910. * accessing it throws an exception in IE8
  29911. */
  29912. function statusValid (xhr) {
  29913. try {
  29914. var status = xhr.status
  29915. return (status !== null && status !== 0)
  29916. } catch (e) {
  29917. return false
  29918. }
  29919. }
  29920. ClientRequest.prototype._onXHRProgress = function () {
  29921. var self = this
  29922. if (!statusValid(self._xhr) || self._destroyed)
  29923. return
  29924. if (!self._response)
  29925. self._connect()
  29926. self._response._onXHRProgress()
  29927. }
  29928. ClientRequest.prototype._connect = function () {
  29929. var self = this
  29930. if (self._destroyed)
  29931. return
  29932. self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
  29933. self._response.on('error', function(err) {
  29934. self.emit('error', err)
  29935. })
  29936. self.emit('response', self._response)
  29937. }
  29938. ClientRequest.prototype._write = function (chunk, encoding, cb) {
  29939. var self = this
  29940. self._body.push(chunk)
  29941. cb()
  29942. }
  29943. ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
  29944. var self = this
  29945. self._destroyed = true
  29946. global.clearTimeout(self._fetchTimer)
  29947. if (self._response)
  29948. self._response._destroyed = true
  29949. if (self._xhr)
  29950. self._xhr.abort()
  29951. else if (self._fetchAbortController)
  29952. self._fetchAbortController.abort()
  29953. }
  29954. ClientRequest.prototype.end = function (data, encoding, cb) {
  29955. var self = this
  29956. if (typeof data === 'function') {
  29957. cb = data
  29958. data = undefined
  29959. }
  29960. stream.Writable.prototype.end.call(self, data, encoding, cb)
  29961. }
  29962. ClientRequest.prototype.flushHeaders = function () {}
  29963. ClientRequest.prototype.setTimeout = function () {}
  29964. ClientRequest.prototype.setNoDelay = function () {}
  29965. ClientRequest.prototype.setSocketKeepAlive = function () {}
  29966. // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
  29967. var unsafeHeaders = [
  29968. 'accept-charset',
  29969. 'accept-encoding',
  29970. 'access-control-request-headers',
  29971. 'access-control-request-method',
  29972. 'connection',
  29973. 'content-length',
  29974. 'cookie',
  29975. 'cookie2',
  29976. 'date',
  29977. 'dnt',
  29978. 'expect',
  29979. 'host',
  29980. 'keep-alive',
  29981. 'origin',
  29982. 'referer',
  29983. 'te',
  29984. 'trailer',
  29985. 'transfer-encoding',
  29986. 'upgrade',
  29987. 'via'
  29988. ]
  29989. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  29990. },{"./capability":336,"./response":338,"_process":312,"buffer":47,"inherits":254,"readable-stream":353}],338:[function(require,module,exports){
  29991. (function (process,global,Buffer){
  29992. var capability = require('./capability')
  29993. var inherits = require('inherits')
  29994. var stream = require('readable-stream')
  29995. var rStates = exports.readyStates = {
  29996. UNSENT: 0,
  29997. OPENED: 1,
  29998. HEADERS_RECEIVED: 2,
  29999. LOADING: 3,
  30000. DONE: 4
  30001. }
  30002. var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
  30003. var self = this
  30004. stream.Readable.call(self)
  30005. self._mode = mode
  30006. self.headers = {}
  30007. self.rawHeaders = []
  30008. self.trailers = {}
  30009. self.rawTrailers = []
  30010. // Fake the 'close' event, but only once 'end' fires
  30011. self.on('end', function () {
  30012. // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
  30013. process.nextTick(function () {
  30014. self.emit('close')
  30015. })
  30016. })
  30017. if (mode === 'fetch') {
  30018. self._fetchResponse = response
  30019. self.url = response.url
  30020. self.statusCode = response.status
  30021. self.statusMessage = response.statusText
  30022. response.headers.forEach(function (header, key){
  30023. self.headers[key.toLowerCase()] = header
  30024. self.rawHeaders.push(key, header)
  30025. })
  30026. if (capability.writableStream) {
  30027. var writable = new WritableStream({
  30028. write: function (chunk) {
  30029. return new Promise(function (resolve, reject) {
  30030. if (self._destroyed) {
  30031. reject()
  30032. } else if(self.push(Buffer.from(chunk))) {
  30033. resolve()
  30034. } else {
  30035. self._resumeFetch = resolve
  30036. }
  30037. })
  30038. },
  30039. close: function () {
  30040. global.clearTimeout(fetchTimer)
  30041. if (!self._destroyed)
  30042. self.push(null)
  30043. },
  30044. abort: function (err) {
  30045. if (!self._destroyed)
  30046. self.emit('error', err)
  30047. }
  30048. })
  30049. try {
  30050. response.body.pipeTo(writable).catch(function (err) {
  30051. global.clearTimeout(fetchTimer)
  30052. if (!self._destroyed)
  30053. self.emit('error', err)
  30054. })
  30055. return
  30056. } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
  30057. }
  30058. // fallback for when writableStream or pipeTo aren't available
  30059. var reader = response.body.getReader()
  30060. function read () {
  30061. reader.read().then(function (result) {
  30062. if (self._destroyed)
  30063. return
  30064. if (result.done) {
  30065. global.clearTimeout(fetchTimer)
  30066. self.push(null)
  30067. return
  30068. }
  30069. self.push(Buffer.from(result.value))
  30070. read()
  30071. }).catch(function (err) {
  30072. global.clearTimeout(fetchTimer)
  30073. if (!self._destroyed)
  30074. self.emit('error', err)
  30075. })
  30076. }
  30077. read()
  30078. } else {
  30079. self._xhr = xhr
  30080. self._pos = 0
  30081. self.url = xhr.responseURL
  30082. self.statusCode = xhr.status
  30083. self.statusMessage = xhr.statusText
  30084. var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
  30085. headers.forEach(function (header) {
  30086. var matches = header.match(/^([^:]+):\s*(.*)/)
  30087. if (matches) {
  30088. var key = matches[1].toLowerCase()
  30089. if (key === 'set-cookie') {
  30090. if (self.headers[key] === undefined) {
  30091. self.headers[key] = []
  30092. }
  30093. self.headers[key].push(matches[2])
  30094. } else if (self.headers[key] !== undefined) {
  30095. self.headers[key] += ', ' + matches[2]
  30096. } else {
  30097. self.headers[key] = matches[2]
  30098. }
  30099. self.rawHeaders.push(matches[1], matches[2])
  30100. }
  30101. })
  30102. self._charset = 'x-user-defined'
  30103. if (!capability.overrideMimeType) {
  30104. var mimeType = self.rawHeaders['mime-type']
  30105. if (mimeType) {
  30106. var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
  30107. if (charsetMatch) {
  30108. self._charset = charsetMatch[1].toLowerCase()
  30109. }
  30110. }
  30111. if (!self._charset)
  30112. self._charset = 'utf-8' // best guess
  30113. }
  30114. }
  30115. }
  30116. inherits(IncomingMessage, stream.Readable)
  30117. IncomingMessage.prototype._read = function () {
  30118. var self = this
  30119. var resolve = self._resumeFetch
  30120. if (resolve) {
  30121. self._resumeFetch = null
  30122. resolve()
  30123. }
  30124. }
  30125. IncomingMessage.prototype._onXHRProgress = function () {
  30126. var self = this
  30127. var xhr = self._xhr
  30128. var response = null
  30129. switch (self._mode) {
  30130. case 'text':
  30131. response = xhr.responseText
  30132. if (response.length > self._pos) {
  30133. var newData = response.substr(self._pos)
  30134. if (self._charset === 'x-user-defined') {
  30135. var buffer = Buffer.alloc(newData.length)
  30136. for (var i = 0; i < newData.length; i++)
  30137. buffer[i] = newData.charCodeAt(i) & 0xff
  30138. self.push(buffer)
  30139. } else {
  30140. self.push(newData, self._charset)
  30141. }
  30142. self._pos = response.length
  30143. }
  30144. break
  30145. case 'arraybuffer':
  30146. if (xhr.readyState !== rStates.DONE || !xhr.response)
  30147. break
  30148. response = xhr.response
  30149. self.push(Buffer.from(new Uint8Array(response)))
  30150. break
  30151. case 'moz-chunked-arraybuffer': // take whole
  30152. response = xhr.response
  30153. if (xhr.readyState !== rStates.LOADING || !response)
  30154. break
  30155. self.push(Buffer.from(new Uint8Array(response)))
  30156. break
  30157. case 'ms-stream':
  30158. response = xhr.response
  30159. if (xhr.readyState !== rStates.LOADING)
  30160. break
  30161. var reader = new global.MSStreamReader()
  30162. reader.onprogress = function () {
  30163. if (reader.result.byteLength > self._pos) {
  30164. self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
  30165. self._pos = reader.result.byteLength
  30166. }
  30167. }
  30168. reader.onload = function () {
  30169. self.push(null)
  30170. }
  30171. // reader.onerror = ??? // TODO: this
  30172. reader.readAsArrayBuffer(response)
  30173. break
  30174. }
  30175. // The ms-stream case handles end separately in reader.onload()
  30176. if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
  30177. self.push(null)
  30178. }
  30179. }
  30180. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  30181. },{"./capability":336,"_process":312,"buffer":47,"inherits":254,"readable-stream":353}],339:[function(require,module,exports){
  30182. 'use strict';
  30183. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  30184. var codes = {};
  30185. function createErrorType(code, message, Base) {
  30186. if (!Base) {
  30187. Base = Error;
  30188. }
  30189. function getMessage(arg1, arg2, arg3) {
  30190. if (typeof message === 'string') {
  30191. return message;
  30192. } else {
  30193. return message(arg1, arg2, arg3);
  30194. }
  30195. }
  30196. var NodeError =
  30197. /*#__PURE__*/
  30198. function (_Base) {
  30199. _inheritsLoose(NodeError, _Base);
  30200. function NodeError(arg1, arg2, arg3) {
  30201. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  30202. }
  30203. return NodeError;
  30204. }(Base);
  30205. NodeError.prototype.name = Base.name;
  30206. NodeError.prototype.code = code;
  30207. codes[code] = NodeError;
  30208. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  30209. function oneOf(expected, thing) {
  30210. if (Array.isArray(expected)) {
  30211. var len = expected.length;
  30212. expected = expected.map(function (i) {
  30213. return String(i);
  30214. });
  30215. if (len > 2) {
  30216. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  30217. } else if (len === 2) {
  30218. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  30219. } else {
  30220. return "of ".concat(thing, " ").concat(expected[0]);
  30221. }
  30222. } else {
  30223. return "of ".concat(thing, " ").concat(String(expected));
  30224. }
  30225. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  30226. function startsWith(str, search, pos) {
  30227. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  30228. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  30229. function endsWith(str, search, this_len) {
  30230. if (this_len === undefined || this_len > str.length) {
  30231. this_len = str.length;
  30232. }
  30233. return str.substring(this_len - search.length, this_len) === search;
  30234. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  30235. function includes(str, search, start) {
  30236. if (typeof start !== 'number') {
  30237. start = 0;
  30238. }
  30239. if (start + search.length > str.length) {
  30240. return false;
  30241. } else {
  30242. return str.indexOf(search, start) !== -1;
  30243. }
  30244. }
  30245. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  30246. return 'The value "' + value + '" is invalid for option "' + name + '"';
  30247. }, TypeError);
  30248. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  30249. // determiner: 'must be' or 'must not be'
  30250. var determiner;
  30251. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  30252. determiner = 'must not be';
  30253. expected = expected.replace(/^not /, '');
  30254. } else {
  30255. determiner = 'must be';
  30256. }
  30257. var msg;
  30258. if (endsWith(name, ' argument')) {
  30259. // For cases like 'first argument'
  30260. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  30261. } else {
  30262. var type = includes(name, '.') ? 'property' : 'argument';
  30263. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  30264. }
  30265. msg += ". Received type ".concat(typeof actual);
  30266. return msg;
  30267. }, TypeError);
  30268. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  30269. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  30270. return 'The ' + name + ' method is not implemented';
  30271. });
  30272. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  30273. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  30274. return 'Cannot call ' + name + ' after a stream was destroyed';
  30275. });
  30276. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  30277. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  30278. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  30279. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  30280. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  30281. return 'Unknown encoding: ' + arg;
  30282. }, TypeError);
  30283. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  30284. module.exports.codes = codes;
  30285. },{}],340:[function(require,module,exports){
  30286. (function (process){
  30287. 'use strict'
  30288. var experimentalWarnings = new Set();
  30289. function emitExperimentalWarning(feature) {
  30290. if (experimentalWarnings.has(feature)) return;
  30291. var msg = feature + ' is an experimental feature. This feature could ' +
  30292. 'change at any time';
  30293. experimentalWarnings.add(feature);
  30294. process.emitWarning(msg, 'ExperimentalWarning');
  30295. }
  30296. function noop() {}
  30297. module.exports.emitExperimentalWarning = process.emitWarning
  30298. ? emitExperimentalWarning
  30299. : noop;
  30300. }).call(this,require('_process'))
  30301. },{"_process":312}],341:[function(require,module,exports){
  30302. (function (process){
  30303. // Copyright Joyent, Inc. and other Node contributors.
  30304. //
  30305. // Permission is hereby granted, free of charge, to any person obtaining a
  30306. // copy of this software and associated documentation files (the
  30307. // "Software"), to deal in the Software without restriction, including
  30308. // without limitation the rights to use, copy, modify, merge, publish,
  30309. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30310. // persons to whom the Software is furnished to do so, subject to the
  30311. // following conditions:
  30312. //
  30313. // The above copyright notice and this permission notice shall be included
  30314. // in all copies or substantial portions of the Software.
  30315. //
  30316. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30317. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30318. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30319. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30320. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30321. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30322. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30323. // a duplex stream is just a stream that is both readable and writable.
  30324. // Since JS doesn't have multiple prototypal inheritance, this class
  30325. // prototypally inherits from Readable, and then parasitically from
  30326. // Writable.
  30327. 'use strict';
  30328. /*<replacement>*/
  30329. var objectKeys = Object.keys || function (obj) {
  30330. var keys = [];
  30331. for (var key in obj) {
  30332. keys.push(key);
  30333. }
  30334. return keys;
  30335. };
  30336. /*</replacement>*/
  30337. module.exports = Duplex;
  30338. var Readable = require('./_stream_readable');
  30339. var Writable = require('./_stream_writable');
  30340. require('inherits')(Duplex, Readable);
  30341. {
  30342. // Allow the keys array to be GC'ed.
  30343. var keys = objectKeys(Writable.prototype);
  30344. for (var v = 0; v < keys.length; v++) {
  30345. var method = keys[v];
  30346. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  30347. }
  30348. }
  30349. function Duplex(options) {
  30350. if (!(this instanceof Duplex)) return new Duplex(options);
  30351. Readable.call(this, options);
  30352. Writable.call(this, options);
  30353. this.allowHalfOpen = true;
  30354. if (options) {
  30355. if (options.readable === false) this.readable = false;
  30356. if (options.writable === false) this.writable = false;
  30357. if (options.allowHalfOpen === false) {
  30358. this.allowHalfOpen = false;
  30359. this.once('end', onend);
  30360. }
  30361. }
  30362. }
  30363. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  30364. // making it explicit this property is not enumerable
  30365. // because otherwise some prototype manipulation in
  30366. // userland will fail
  30367. enumerable: false,
  30368. get: function get() {
  30369. return this._writableState.highWaterMark;
  30370. }
  30371. });
  30372. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  30373. // making it explicit this property is not enumerable
  30374. // because otherwise some prototype manipulation in
  30375. // userland will fail
  30376. enumerable: false,
  30377. get: function get() {
  30378. return this._writableState && this._writableState.getBuffer();
  30379. }
  30380. });
  30381. Object.defineProperty(Duplex.prototype, 'writableLength', {
  30382. // making it explicit this property is not enumerable
  30383. // because otherwise some prototype manipulation in
  30384. // userland will fail
  30385. enumerable: false,
  30386. get: function get() {
  30387. return this._writableState.length;
  30388. }
  30389. }); // the no-half-open enforcer
  30390. function onend() {
  30391. // If the writable side ended, then we're ok.
  30392. if (this._writableState.ended) return; // no more data can be written.
  30393. // But allow more writes to happen in this tick.
  30394. process.nextTick(onEndNT, this);
  30395. }
  30396. function onEndNT(self) {
  30397. self.end();
  30398. }
  30399. Object.defineProperty(Duplex.prototype, 'destroyed', {
  30400. // making it explicit this property is not enumerable
  30401. // because otherwise some prototype manipulation in
  30402. // userland will fail
  30403. enumerable: false,
  30404. get: function get() {
  30405. if (this._readableState === undefined || this._writableState === undefined) {
  30406. return false;
  30407. }
  30408. return this._readableState.destroyed && this._writableState.destroyed;
  30409. },
  30410. set: function set(value) {
  30411. // we ignore the value if the stream
  30412. // has not been initialized yet
  30413. if (this._readableState === undefined || this._writableState === undefined) {
  30414. return;
  30415. } // backward compatibility, the user is explicitly
  30416. // managing destroyed
  30417. this._readableState.destroyed = value;
  30418. this._writableState.destroyed = value;
  30419. }
  30420. });
  30421. }).call(this,require('_process'))
  30422. },{"./_stream_readable":343,"./_stream_writable":345,"_process":312,"inherits":254}],342:[function(require,module,exports){
  30423. // Copyright Joyent, Inc. and other Node contributors.
  30424. //
  30425. // Permission is hereby granted, free of charge, to any person obtaining a
  30426. // copy of this software and associated documentation files (the
  30427. // "Software"), to deal in the Software without restriction, including
  30428. // without limitation the rights to use, copy, modify, merge, publish,
  30429. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30430. // persons to whom the Software is furnished to do so, subject to the
  30431. // following conditions:
  30432. //
  30433. // The above copyright notice and this permission notice shall be included
  30434. // in all copies or substantial portions of the Software.
  30435. //
  30436. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30437. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30438. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30439. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30440. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30441. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30442. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30443. // a passthrough stream.
  30444. // basically just the most minimal sort of Transform stream.
  30445. // Every written chunk gets output as-is.
  30446. 'use strict';
  30447. module.exports = PassThrough;
  30448. var Transform = require('./_stream_transform');
  30449. require('inherits')(PassThrough, Transform);
  30450. function PassThrough(options) {
  30451. if (!(this instanceof PassThrough)) return new PassThrough(options);
  30452. Transform.call(this, options);
  30453. }
  30454. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  30455. cb(null, chunk);
  30456. };
  30457. },{"./_stream_transform":344,"inherits":254}],343:[function(require,module,exports){
  30458. (function (process,global){
  30459. // Copyright Joyent, Inc. and other Node contributors.
  30460. //
  30461. // Permission is hereby granted, free of charge, to any person obtaining a
  30462. // copy of this software and associated documentation files (the
  30463. // "Software"), to deal in the Software without restriction, including
  30464. // without limitation the rights to use, copy, modify, merge, publish,
  30465. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30466. // persons to whom the Software is furnished to do so, subject to the
  30467. // following conditions:
  30468. //
  30469. // The above copyright notice and this permission notice shall be included
  30470. // in all copies or substantial portions of the Software.
  30471. //
  30472. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30473. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30474. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30475. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30476. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30477. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30478. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30479. 'use strict';
  30480. module.exports = Readable;
  30481. /*<replacement>*/
  30482. var Duplex;
  30483. /*</replacement>*/
  30484. Readable.ReadableState = ReadableState;
  30485. /*<replacement>*/
  30486. var EE = require('events').EventEmitter;
  30487. var EElistenerCount = function EElistenerCount(emitter, type) {
  30488. return emitter.listeners(type).length;
  30489. };
  30490. /*</replacement>*/
  30491. /*<replacement>*/
  30492. var Stream = require('./internal/streams/stream');
  30493. /*</replacement>*/
  30494. var Buffer = require('buffer').Buffer;
  30495. var OurUint8Array = global.Uint8Array || function () {};
  30496. function _uint8ArrayToBuffer(chunk) {
  30497. return Buffer.from(chunk);
  30498. }
  30499. function _isUint8Array(obj) {
  30500. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  30501. }
  30502. /*<replacement>*/
  30503. var debugUtil = require('util');
  30504. var debug;
  30505. if (debugUtil && debugUtil.debuglog) {
  30506. debug = debugUtil.debuglog('stream');
  30507. } else {
  30508. debug = function debug() {};
  30509. }
  30510. /*</replacement>*/
  30511. var BufferList = require('./internal/streams/buffer_list');
  30512. var destroyImpl = require('./internal/streams/destroy');
  30513. var _require = require('./internal/streams/state'),
  30514. getHighWaterMark = _require.getHighWaterMark;
  30515. var _require$codes = require('../errors').codes,
  30516. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  30517. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  30518. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  30519. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
  30520. var _require2 = require('../experimentalWarning'),
  30521. emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
  30522. var StringDecoder;
  30523. var createReadableStreamAsyncIterator;
  30524. require('inherits')(Readable, Stream);
  30525. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  30526. function prependListener(emitter, event, fn) {
  30527. // Sadly this is not cacheable as some libraries bundle their own
  30528. // event emitter implementation with them.
  30529. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  30530. // userland ones. NEVER DO THIS. This is here only because this code needs
  30531. // to continue to work with older versions of Node.js that do not include
  30532. // the prependListener() method. The goal is to eventually remove this hack.
  30533. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  30534. }
  30535. function ReadableState(options, stream, isDuplex) {
  30536. Duplex = Duplex || require('./_stream_duplex');
  30537. options = options || {}; // Duplex streams are both readable and writable, but share
  30538. // the same options object.
  30539. // However, some cases require setting options to different
  30540. // values for the readable and the writable sides of the duplex stream.
  30541. // These options can be provided separately as readableXXX and writableXXX.
  30542. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  30543. // make all the buffer merging and length checks go away
  30544. this.objectMode = !!options.objectMode;
  30545. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  30546. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  30547. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  30548. // linked list can remove elements from the beginning faster than
  30549. // array.shift()
  30550. this.buffer = new BufferList();
  30551. this.length = 0;
  30552. this.pipes = null;
  30553. this.pipesCount = 0;
  30554. this.flowing = null;
  30555. this.ended = false;
  30556. this.endEmitted = false;
  30557. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  30558. // immediately, or on a later tick. We set this to true at first, because
  30559. // any actions that shouldn't happen until "later" should generally also
  30560. // not happen before the first read call.
  30561. this.sync = true; // whenever we return null, then we set a flag to say
  30562. // that we're awaiting a 'readable' event emission.
  30563. this.needReadable = false;
  30564. this.emittedReadable = false;
  30565. this.readableListening = false;
  30566. this.resumeScheduled = false;
  30567. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  30568. this.emitClose = options.emitClose !== false; // has it been destroyed
  30569. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  30570. // encoding is 'binary' so we have to make this configurable.
  30571. // Everything else in the universe uses 'utf8', though.
  30572. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  30573. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  30574. this.readingMore = false;
  30575. this.decoder = null;
  30576. this.encoding = null;
  30577. if (options.encoding) {
  30578. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  30579. this.decoder = new StringDecoder(options.encoding);
  30580. this.encoding = options.encoding;
  30581. }
  30582. }
  30583. function Readable(options) {
  30584. Duplex = Duplex || require('./_stream_duplex');
  30585. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  30586. // the ReadableState constructor, at least with V8 6.5
  30587. var isDuplex = this instanceof Duplex;
  30588. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  30589. this.readable = true;
  30590. if (options) {
  30591. if (typeof options.read === 'function') this._read = options.read;
  30592. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  30593. }
  30594. Stream.call(this);
  30595. }
  30596. Object.defineProperty(Readable.prototype, 'destroyed', {
  30597. // making it explicit this property is not enumerable
  30598. // because otherwise some prototype manipulation in
  30599. // userland will fail
  30600. enumerable: false,
  30601. get: function get() {
  30602. if (this._readableState === undefined) {
  30603. return false;
  30604. }
  30605. return this._readableState.destroyed;
  30606. },
  30607. set: function set(value) {
  30608. // we ignore the value if the stream
  30609. // has not been initialized yet
  30610. if (!this._readableState) {
  30611. return;
  30612. } // backward compatibility, the user is explicitly
  30613. // managing destroyed
  30614. this._readableState.destroyed = value;
  30615. }
  30616. });
  30617. Readable.prototype.destroy = destroyImpl.destroy;
  30618. Readable.prototype._undestroy = destroyImpl.undestroy;
  30619. Readable.prototype._destroy = function (err, cb) {
  30620. cb(err);
  30621. }; // Manually shove something into the read() buffer.
  30622. // This returns true if the highWaterMark has not been hit yet,
  30623. // similar to how Writable.write() returns true if you should
  30624. // write() some more.
  30625. Readable.prototype.push = function (chunk, encoding) {
  30626. var state = this._readableState;
  30627. var skipChunkCheck;
  30628. if (!state.objectMode) {
  30629. if (typeof chunk === 'string') {
  30630. encoding = encoding || state.defaultEncoding;
  30631. if (encoding !== state.encoding) {
  30632. chunk = Buffer.from(chunk, encoding);
  30633. encoding = '';
  30634. }
  30635. skipChunkCheck = true;
  30636. }
  30637. } else {
  30638. skipChunkCheck = true;
  30639. }
  30640. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  30641. }; // Unshift should *always* be something directly out of read()
  30642. Readable.prototype.unshift = function (chunk) {
  30643. return readableAddChunk(this, chunk, null, true, false);
  30644. };
  30645. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  30646. debug('readableAddChunk', chunk);
  30647. var state = stream._readableState;
  30648. if (chunk === null) {
  30649. state.reading = false;
  30650. onEofChunk(stream, state);
  30651. } else {
  30652. var er;
  30653. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  30654. if (er) {
  30655. stream.emit('error', er);
  30656. } else if (state.objectMode || chunk && chunk.length > 0) {
  30657. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  30658. chunk = _uint8ArrayToBuffer(chunk);
  30659. }
  30660. if (addToFront) {
  30661. if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  30662. } else if (state.ended) {
  30663. stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
  30664. } else if (state.destroyed) {
  30665. return false;
  30666. } else {
  30667. state.reading = false;
  30668. if (state.decoder && !encoding) {
  30669. chunk = state.decoder.write(chunk);
  30670. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  30671. } else {
  30672. addChunk(stream, state, chunk, false);
  30673. }
  30674. }
  30675. } else if (!addToFront) {
  30676. state.reading = false;
  30677. maybeReadMore(stream, state);
  30678. }
  30679. } // We can push more data if we are below the highWaterMark.
  30680. // Also, if we have no data yet, we can stand some more bytes.
  30681. // This is to work around cases where hwm=0, such as the repl.
  30682. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  30683. }
  30684. function addChunk(stream, state, chunk, addToFront) {
  30685. if (state.flowing && state.length === 0 && !state.sync) {
  30686. state.awaitDrain = 0;
  30687. stream.emit('data', chunk);
  30688. } else {
  30689. // update the buffer info.
  30690. state.length += state.objectMode ? 1 : chunk.length;
  30691. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  30692. if (state.needReadable) emitReadable(stream);
  30693. }
  30694. maybeReadMore(stream, state);
  30695. }
  30696. function chunkInvalid(state, chunk) {
  30697. var er;
  30698. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  30699. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  30700. }
  30701. return er;
  30702. }
  30703. Readable.prototype.isPaused = function () {
  30704. return this._readableState.flowing === false;
  30705. }; // backwards compatibility.
  30706. Readable.prototype.setEncoding = function (enc) {
  30707. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  30708. this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
  30709. this._readableState.encoding = this._readableState.decoder.encoding;
  30710. return this;
  30711. }; // Don't raise the hwm > 8MB
  30712. var MAX_HWM = 0x800000;
  30713. function computeNewHighWaterMark(n) {
  30714. if (n >= MAX_HWM) {
  30715. n = MAX_HWM;
  30716. } else {
  30717. // Get the next highest power of 2 to prevent increasing hwm excessively in
  30718. // tiny amounts
  30719. n--;
  30720. n |= n >>> 1;
  30721. n |= n >>> 2;
  30722. n |= n >>> 4;
  30723. n |= n >>> 8;
  30724. n |= n >>> 16;
  30725. n++;
  30726. }
  30727. return n;
  30728. } // This function is designed to be inlinable, so please take care when making
  30729. // changes to the function body.
  30730. function howMuchToRead(n, state) {
  30731. if (n <= 0 || state.length === 0 && state.ended) return 0;
  30732. if (state.objectMode) return 1;
  30733. if (n !== n) {
  30734. // Only flow one buffer at a time
  30735. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  30736. } // If we're asking for more than the current hwm, then raise the hwm.
  30737. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  30738. if (n <= state.length) return n; // Don't have enough
  30739. if (!state.ended) {
  30740. state.needReadable = true;
  30741. return 0;
  30742. }
  30743. return state.length;
  30744. } // you can override either this method, or the async _read(n) below.
  30745. Readable.prototype.read = function (n) {
  30746. debug('read', n);
  30747. n = parseInt(n, 10);
  30748. var state = this._readableState;
  30749. var nOrig = n;
  30750. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  30751. // already have a bunch of data in the buffer, then just trigger
  30752. // the 'readable' event and move on.
  30753. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  30754. debug('read: emitReadable', state.length, state.ended);
  30755. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  30756. return null;
  30757. }
  30758. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  30759. if (n === 0 && state.ended) {
  30760. if (state.length === 0) endReadable(this);
  30761. return null;
  30762. } // All the actual chunk generation logic needs to be
  30763. // *below* the call to _read. The reason is that in certain
  30764. // synthetic stream cases, such as passthrough streams, _read
  30765. // may be a completely synchronous operation which may change
  30766. // the state of the read buffer, providing enough data when
  30767. // before there was *not* enough.
  30768. //
  30769. // So, the steps are:
  30770. // 1. Figure out what the state of things will be after we do
  30771. // a read from the buffer.
  30772. //
  30773. // 2. If that resulting state will trigger a _read, then call _read.
  30774. // Note that this may be asynchronous, or synchronous. Yes, it is
  30775. // deeply ugly to write APIs this way, but that still doesn't mean
  30776. // that the Readable class should behave improperly, as streams are
  30777. // designed to be sync/async agnostic.
  30778. // Take note if the _read call is sync or async (ie, if the read call
  30779. // has returned yet), so that we know whether or not it's safe to emit
  30780. // 'readable' etc.
  30781. //
  30782. // 3. Actually pull the requested chunks out of the buffer and return.
  30783. // if we need a readable event, then we need to do some reading.
  30784. var doRead = state.needReadable;
  30785. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  30786. if (state.length === 0 || state.length - n < state.highWaterMark) {
  30787. doRead = true;
  30788. debug('length less than watermark', doRead);
  30789. } // however, if we've ended, then there's no point, and if we're already
  30790. // reading, then it's unnecessary.
  30791. if (state.ended || state.reading) {
  30792. doRead = false;
  30793. debug('reading or ended', doRead);
  30794. } else if (doRead) {
  30795. debug('do read');
  30796. state.reading = true;
  30797. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  30798. if (state.length === 0) state.needReadable = true; // call internal read method
  30799. this._read(state.highWaterMark);
  30800. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  30801. // and we need to re-evaluate how much data we can return to the user.
  30802. if (!state.reading) n = howMuchToRead(nOrig, state);
  30803. }
  30804. var ret;
  30805. if (n > 0) ret = fromList(n, state);else ret = null;
  30806. if (ret === null) {
  30807. state.needReadable = true;
  30808. n = 0;
  30809. } else {
  30810. state.length -= n;
  30811. state.awaitDrain = 0;
  30812. }
  30813. if (state.length === 0) {
  30814. // If we have nothing in the buffer, then we want to know
  30815. // as soon as we *do* get something into the buffer.
  30816. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  30817. if (nOrig !== n && state.ended) endReadable(this);
  30818. }
  30819. if (ret !== null) this.emit('data', ret);
  30820. return ret;
  30821. };
  30822. function onEofChunk(stream, state) {
  30823. if (state.ended) return;
  30824. if (state.decoder) {
  30825. var chunk = state.decoder.end();
  30826. if (chunk && chunk.length) {
  30827. state.buffer.push(chunk);
  30828. state.length += state.objectMode ? 1 : chunk.length;
  30829. }
  30830. }
  30831. state.ended = true;
  30832. if (state.sync) {
  30833. // if we are sync, wait until next tick to emit the data.
  30834. // Otherwise we risk emitting data in the flow()
  30835. // the readable code triggers during a read() call
  30836. emitReadable(stream);
  30837. } else {
  30838. // emit 'readable' now to make sure it gets picked up.
  30839. state.needReadable = false;
  30840. if (!state.emittedReadable) {
  30841. state.emittedReadable = true;
  30842. emitReadable_(stream);
  30843. }
  30844. }
  30845. } // Don't emit readable right away in sync mode, because this can trigger
  30846. // another read() call => stack overflow. This way, it might trigger
  30847. // a nextTick recursion warning, but that's not so bad.
  30848. function emitReadable(stream) {
  30849. var state = stream._readableState;
  30850. state.needReadable = false;
  30851. if (!state.emittedReadable) {
  30852. debug('emitReadable', state.flowing);
  30853. state.emittedReadable = true;
  30854. process.nextTick(emitReadable_, stream);
  30855. }
  30856. }
  30857. function emitReadable_(stream) {
  30858. var state = stream._readableState;
  30859. debug('emitReadable_', state.destroyed, state.length, state.ended);
  30860. if (!state.destroyed && (state.length || state.ended)) {
  30861. stream.emit('readable');
  30862. } // The stream needs another readable event if
  30863. // 1. It is not flowing, as the flow mechanism will take
  30864. // care of it.
  30865. // 2. It is not ended.
  30866. // 3. It is below the highWaterMark, so we can schedule
  30867. // another readable later.
  30868. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  30869. flow(stream);
  30870. } // at this point, the user has presumably seen the 'readable' event,
  30871. // and called read() to consume some data. that may have triggered
  30872. // in turn another _read(n) call, in which case reading = true if
  30873. // it's in progress.
  30874. // However, if we're not ended, or reading, and the length < hwm,
  30875. // then go ahead and try to read some more preemptively.
  30876. function maybeReadMore(stream, state) {
  30877. if (!state.readingMore) {
  30878. state.readingMore = true;
  30879. process.nextTick(maybeReadMore_, stream, state);
  30880. }
  30881. }
  30882. function maybeReadMore_(stream, state) {
  30883. // Attempt to read more data if we should.
  30884. //
  30885. // The conditions for reading more data are (one of):
  30886. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  30887. // is responsible for filling the buffer with enough data if such data
  30888. // is available. If highWaterMark is 0 and we are not in the flowing mode
  30889. // we should _not_ attempt to buffer any extra data. We'll get more data
  30890. // when the stream consumer calls read() instead.
  30891. // - No data in the buffer, and the stream is in flowing mode. In this mode
  30892. // the loop below is responsible for ensuring read() is called. Failing to
  30893. // call read here would abort the flow and there's no other mechanism for
  30894. // continuing the flow if the stream consumer has just subscribed to the
  30895. // 'data' event.
  30896. //
  30897. // In addition to the above conditions to keep reading data, the following
  30898. // conditions prevent the data from being read:
  30899. // - The stream has ended (state.ended).
  30900. // - There is already a pending 'read' operation (state.reading). This is a
  30901. // case where the the stream has called the implementation defined _read()
  30902. // method, but they are processing the call asynchronously and have _not_
  30903. // called push() with new data. In this case we skip performing more
  30904. // read()s. The execution ends in this method again after the _read() ends
  30905. // up calling push() with more data.
  30906. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  30907. var len = state.length;
  30908. debug('maybeReadMore read 0');
  30909. stream.read(0);
  30910. if (len === state.length) // didn't get any data, stop spinning.
  30911. break;
  30912. }
  30913. state.readingMore = false;
  30914. } // abstract method. to be overridden in specific implementation classes.
  30915. // call cb(er, data) where data is <= n in length.
  30916. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  30917. // arbitrary, and perhaps not very meaningful.
  30918. Readable.prototype._read = function (n) {
  30919. this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  30920. };
  30921. Readable.prototype.pipe = function (dest, pipeOpts) {
  30922. var src = this;
  30923. var state = this._readableState;
  30924. switch (state.pipesCount) {
  30925. case 0:
  30926. state.pipes = dest;
  30927. break;
  30928. case 1:
  30929. state.pipes = [state.pipes, dest];
  30930. break;
  30931. default:
  30932. state.pipes.push(dest);
  30933. break;
  30934. }
  30935. state.pipesCount += 1;
  30936. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  30937. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  30938. var endFn = doEnd ? onend : unpipe;
  30939. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  30940. dest.on('unpipe', onunpipe);
  30941. function onunpipe(readable, unpipeInfo) {
  30942. debug('onunpipe');
  30943. if (readable === src) {
  30944. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  30945. unpipeInfo.hasUnpiped = true;
  30946. cleanup();
  30947. }
  30948. }
  30949. }
  30950. function onend() {
  30951. debug('onend');
  30952. dest.end();
  30953. } // when the dest drains, it reduces the awaitDrain counter
  30954. // on the source. This would be more elegant with a .once()
  30955. // handler in flow(), but adding and removing repeatedly is
  30956. // too slow.
  30957. var ondrain = pipeOnDrain(src);
  30958. dest.on('drain', ondrain);
  30959. var cleanedUp = false;
  30960. function cleanup() {
  30961. debug('cleanup'); // cleanup event handlers once the pipe is broken
  30962. dest.removeListener('close', onclose);
  30963. dest.removeListener('finish', onfinish);
  30964. dest.removeListener('drain', ondrain);
  30965. dest.removeListener('error', onerror);
  30966. dest.removeListener('unpipe', onunpipe);
  30967. src.removeListener('end', onend);
  30968. src.removeListener('end', unpipe);
  30969. src.removeListener('data', ondata);
  30970. cleanedUp = true; // if the reader is waiting for a drain event from this
  30971. // specific writer, then it would cause it to never start
  30972. // flowing again.
  30973. // So, if this is awaiting a drain, then we just call it now.
  30974. // If we don't know, then assume that we are waiting for one.
  30975. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  30976. }
  30977. src.on('data', ondata);
  30978. function ondata(chunk) {
  30979. debug('ondata');
  30980. var ret = dest.write(chunk);
  30981. debug('dest.write', ret);
  30982. if (ret === false) {
  30983. // If the user unpiped during `dest.write()`, it is possible
  30984. // to get stuck in a permanently paused state if that write
  30985. // also returned false.
  30986. // => Check whether `dest` is still a piping destination.
  30987. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  30988. debug('false write response, pause', state.awaitDrain);
  30989. state.awaitDrain++;
  30990. }
  30991. src.pause();
  30992. }
  30993. } // if the dest has an error, then stop piping into it.
  30994. // however, don't suppress the throwing behavior for this.
  30995. function onerror(er) {
  30996. debug('onerror', er);
  30997. unpipe();
  30998. dest.removeListener('error', onerror);
  30999. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  31000. } // Make sure our error handler is attached before userland ones.
  31001. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  31002. function onclose() {
  31003. dest.removeListener('finish', onfinish);
  31004. unpipe();
  31005. }
  31006. dest.once('close', onclose);
  31007. function onfinish() {
  31008. debug('onfinish');
  31009. dest.removeListener('close', onclose);
  31010. unpipe();
  31011. }
  31012. dest.once('finish', onfinish);
  31013. function unpipe() {
  31014. debug('unpipe');
  31015. src.unpipe(dest);
  31016. } // tell the dest that it's being piped to
  31017. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  31018. if (!state.flowing) {
  31019. debug('pipe resume');
  31020. src.resume();
  31021. }
  31022. return dest;
  31023. };
  31024. function pipeOnDrain(src) {
  31025. return function pipeOnDrainFunctionResult() {
  31026. var state = src._readableState;
  31027. debug('pipeOnDrain', state.awaitDrain);
  31028. if (state.awaitDrain) state.awaitDrain--;
  31029. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  31030. state.flowing = true;
  31031. flow(src);
  31032. }
  31033. };
  31034. }
  31035. Readable.prototype.unpipe = function (dest) {
  31036. var state = this._readableState;
  31037. var unpipeInfo = {
  31038. hasUnpiped: false
  31039. }; // if we're not piping anywhere, then do nothing.
  31040. if (state.pipesCount === 0) return this; // just one destination. most common case.
  31041. if (state.pipesCount === 1) {
  31042. // passed in one, but it's not the right one.
  31043. if (dest && dest !== state.pipes) return this;
  31044. if (!dest) dest = state.pipes; // got a match.
  31045. state.pipes = null;
  31046. state.pipesCount = 0;
  31047. state.flowing = false;
  31048. if (dest) dest.emit('unpipe', this, unpipeInfo);
  31049. return this;
  31050. } // slow case. multiple pipe destinations.
  31051. if (!dest) {
  31052. // remove all.
  31053. var dests = state.pipes;
  31054. var len = state.pipesCount;
  31055. state.pipes = null;
  31056. state.pipesCount = 0;
  31057. state.flowing = false;
  31058. for (var i = 0; i < len; i++) {
  31059. dests[i].emit('unpipe', this, {
  31060. hasUnpiped: false
  31061. });
  31062. }
  31063. return this;
  31064. } // try to find the right one.
  31065. var index = indexOf(state.pipes, dest);
  31066. if (index === -1) return this;
  31067. state.pipes.splice(index, 1);
  31068. state.pipesCount -= 1;
  31069. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  31070. dest.emit('unpipe', this, unpipeInfo);
  31071. return this;
  31072. }; // set up data events if they are asked for
  31073. // Ensure readable listeners eventually get something
  31074. Readable.prototype.on = function (ev, fn) {
  31075. var res = Stream.prototype.on.call(this, ev, fn);
  31076. var state = this._readableState;
  31077. if (ev === 'data') {
  31078. // update readableListening so that resume() may be a no-op
  31079. // a few lines down. This is needed to support once('readable').
  31080. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  31081. if (state.flowing !== false) this.resume();
  31082. } else if (ev === 'readable') {
  31083. if (!state.endEmitted && !state.readableListening) {
  31084. state.readableListening = state.needReadable = true;
  31085. state.flowing = false;
  31086. state.emittedReadable = false;
  31087. debug('on readable', state.length, state.reading);
  31088. if (state.length) {
  31089. emitReadable(this);
  31090. } else if (!state.reading) {
  31091. process.nextTick(nReadingNextTick, this);
  31092. }
  31093. }
  31094. }
  31095. return res;
  31096. };
  31097. Readable.prototype.addListener = Readable.prototype.on;
  31098. Readable.prototype.removeListener = function (ev, fn) {
  31099. var res = Stream.prototype.removeListener.call(this, ev, fn);
  31100. if (ev === 'readable') {
  31101. // We need to check if there is someone still listening to
  31102. // readable and reset the state. However this needs to happen
  31103. // after readable has been emitted but before I/O (nextTick) to
  31104. // support once('readable', fn) cycles. This means that calling
  31105. // resume within the same tick will have no
  31106. // effect.
  31107. process.nextTick(updateReadableListening, this);
  31108. }
  31109. return res;
  31110. };
  31111. Readable.prototype.removeAllListeners = function (ev) {
  31112. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  31113. if (ev === 'readable' || ev === undefined) {
  31114. // We need to check if there is someone still listening to
  31115. // readable and reset the state. However this needs to happen
  31116. // after readable has been emitted but before I/O (nextTick) to
  31117. // support once('readable', fn) cycles. This means that calling
  31118. // resume within the same tick will have no
  31119. // effect.
  31120. process.nextTick(updateReadableListening, this);
  31121. }
  31122. return res;
  31123. };
  31124. function updateReadableListening(self) {
  31125. var state = self._readableState;
  31126. state.readableListening = self.listenerCount('readable') > 0;
  31127. if (state.resumeScheduled && !state.paused) {
  31128. // flowing needs to be set to true now, otherwise
  31129. // the upcoming resume will not flow.
  31130. state.flowing = true; // crude way to check if we should resume
  31131. } else if (self.listenerCount('data') > 0) {
  31132. self.resume();
  31133. }
  31134. }
  31135. function nReadingNextTick(self) {
  31136. debug('readable nexttick read 0');
  31137. self.read(0);
  31138. } // pause() and resume() are remnants of the legacy readable stream API
  31139. // If the user uses them, then switch into old mode.
  31140. Readable.prototype.resume = function () {
  31141. var state = this._readableState;
  31142. if (!state.flowing) {
  31143. debug('resume'); // we flow only if there is no one listening
  31144. // for readable, but we still have to call
  31145. // resume()
  31146. state.flowing = !state.readableListening;
  31147. resume(this, state);
  31148. }
  31149. state.paused = false;
  31150. return this;
  31151. };
  31152. function resume(stream, state) {
  31153. if (!state.resumeScheduled) {
  31154. state.resumeScheduled = true;
  31155. process.nextTick(resume_, stream, state);
  31156. }
  31157. }
  31158. function resume_(stream, state) {
  31159. debug('resume', state.reading);
  31160. if (!state.reading) {
  31161. stream.read(0);
  31162. }
  31163. state.resumeScheduled = false;
  31164. stream.emit('resume');
  31165. flow(stream);
  31166. if (state.flowing && !state.reading) stream.read(0);
  31167. }
  31168. Readable.prototype.pause = function () {
  31169. debug('call pause flowing=%j', this._readableState.flowing);
  31170. if (this._readableState.flowing !== false) {
  31171. debug('pause');
  31172. this._readableState.flowing = false;
  31173. this.emit('pause');
  31174. }
  31175. this._readableState.paused = true;
  31176. return this;
  31177. };
  31178. function flow(stream) {
  31179. var state = stream._readableState;
  31180. debug('flow', state.flowing);
  31181. while (state.flowing && stream.read() !== null) {
  31182. ;
  31183. }
  31184. } // wrap an old-style stream as the async data source.
  31185. // This is *not* part of the readable stream interface.
  31186. // It is an ugly unfortunate mess of history.
  31187. Readable.prototype.wrap = function (stream) {
  31188. var _this = this;
  31189. var state = this._readableState;
  31190. var paused = false;
  31191. stream.on('end', function () {
  31192. debug('wrapped end');
  31193. if (state.decoder && !state.ended) {
  31194. var chunk = state.decoder.end();
  31195. if (chunk && chunk.length) _this.push(chunk);
  31196. }
  31197. _this.push(null);
  31198. });
  31199. stream.on('data', function (chunk) {
  31200. debug('wrapped data');
  31201. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  31202. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  31203. var ret = _this.push(chunk);
  31204. if (!ret) {
  31205. paused = true;
  31206. stream.pause();
  31207. }
  31208. }); // proxy all the other methods.
  31209. // important when wrapping filters and duplexes.
  31210. for (var i in stream) {
  31211. if (this[i] === undefined && typeof stream[i] === 'function') {
  31212. this[i] = function methodWrap(method) {
  31213. return function methodWrapReturnFunction() {
  31214. return stream[method].apply(stream, arguments);
  31215. };
  31216. }(i);
  31217. }
  31218. } // proxy certain important events.
  31219. for (var n = 0; n < kProxyEvents.length; n++) {
  31220. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  31221. } // when we try to consume some more bytes, simply unpause the
  31222. // underlying stream.
  31223. this._read = function (n) {
  31224. debug('wrapped _read', n);
  31225. if (paused) {
  31226. paused = false;
  31227. stream.resume();
  31228. }
  31229. };
  31230. return this;
  31231. };
  31232. if (typeof Symbol === 'function') {
  31233. Readable.prototype[Symbol.asyncIterator] = function () {
  31234. emitExperimentalWarning('Readable[Symbol.asyncIterator]');
  31235. if (createReadableStreamAsyncIterator === undefined) {
  31236. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  31237. }
  31238. return createReadableStreamAsyncIterator(this);
  31239. };
  31240. }
  31241. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  31242. // making it explicit this property is not enumerable
  31243. // because otherwise some prototype manipulation in
  31244. // userland will fail
  31245. enumerable: false,
  31246. get: function get() {
  31247. return this._readableState.highWaterMark;
  31248. }
  31249. });
  31250. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  31251. // making it explicit this property is not enumerable
  31252. // because otherwise some prototype manipulation in
  31253. // userland will fail
  31254. enumerable: false,
  31255. get: function get() {
  31256. return this._readableState && this._readableState.buffer;
  31257. }
  31258. });
  31259. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  31260. // making it explicit this property is not enumerable
  31261. // because otherwise some prototype manipulation in
  31262. // userland will fail
  31263. enumerable: false,
  31264. get: function get() {
  31265. return this._readableState.flowing;
  31266. },
  31267. set: function set(state) {
  31268. if (this._readableState) {
  31269. this._readableState.flowing = state;
  31270. }
  31271. }
  31272. }); // exposed for testing purposes only.
  31273. Readable._fromList = fromList;
  31274. Object.defineProperty(Readable.prototype, 'readableLength', {
  31275. // making it explicit this property is not enumerable
  31276. // because otherwise some prototype manipulation in
  31277. // userland will fail
  31278. enumerable: false,
  31279. get: function get() {
  31280. return this._readableState.length;
  31281. }
  31282. }); // Pluck off n bytes from an array of buffers.
  31283. // Length is the combined lengths of all the buffers in the list.
  31284. // This function is designed to be inlinable, so please take care when making
  31285. // changes to the function body.
  31286. function fromList(n, state) {
  31287. // nothing buffered
  31288. if (state.length === 0) return null;
  31289. var ret;
  31290. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  31291. // read it all, truncate the list
  31292. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  31293. state.buffer.clear();
  31294. } else {
  31295. // read part of list
  31296. ret = state.buffer.consume(n, state.decoder);
  31297. }
  31298. return ret;
  31299. }
  31300. function endReadable(stream) {
  31301. var state = stream._readableState;
  31302. debug('endReadable', state.endEmitted);
  31303. if (!state.endEmitted) {
  31304. state.ended = true;
  31305. process.nextTick(endReadableNT, state, stream);
  31306. }
  31307. }
  31308. function endReadableNT(state, stream) {
  31309. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  31310. if (!state.endEmitted && state.length === 0) {
  31311. state.endEmitted = true;
  31312. stream.readable = false;
  31313. stream.emit('end');
  31314. }
  31315. }
  31316. function indexOf(xs, x) {
  31317. for (var i = 0, l = xs.length; i < l; i++) {
  31318. if (xs[i] === x) return i;
  31319. }
  31320. return -1;
  31321. }
  31322. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31323. },{"../errors":339,"../experimentalWarning":340,"./_stream_duplex":341,"./internal/streams/async_iterator":346,"./internal/streams/buffer_list":347,"./internal/streams/destroy":348,"./internal/streams/state":351,"./internal/streams/stream":352,"_process":312,"buffer":47,"events":239,"inherits":254,"string_decoder/":354,"util":32}],344:[function(require,module,exports){
  31324. // Copyright Joyent, Inc. and other Node contributors.
  31325. //
  31326. // Permission is hereby granted, free of charge, to any person obtaining a
  31327. // copy of this software and associated documentation files (the
  31328. // "Software"), to deal in the Software without restriction, including
  31329. // without limitation the rights to use, copy, modify, merge, publish,
  31330. // distribute, sublicense, and/or sell copies of the Software, and to permit
  31331. // persons to whom the Software is furnished to do so, subject to the
  31332. // following conditions:
  31333. //
  31334. // The above copyright notice and this permission notice shall be included
  31335. // in all copies or substantial portions of the Software.
  31336. //
  31337. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  31338. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31339. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  31340. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  31341. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  31342. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  31343. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  31344. // a transform stream is a readable/writable stream where you do
  31345. // something with the data. Sometimes it's called a "filter",
  31346. // but that's not a great name for it, since that implies a thing where
  31347. // some bits pass through, and others are simply ignored. (That would
  31348. // be a valid example of a transform, of course.)
  31349. //
  31350. // While the output is causally related to the input, it's not a
  31351. // necessarily symmetric or synchronous transformation. For example,
  31352. // a zlib stream might take multiple plain-text writes(), and then
  31353. // emit a single compressed chunk some time in the future.
  31354. //
  31355. // Here's how this works:
  31356. //
  31357. // The Transform stream has all the aspects of the readable and writable
  31358. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  31359. // internally, and returns false if there's a lot of pending writes
  31360. // buffered up. When you call read(), that calls _read(n) until
  31361. // there's enough pending readable data buffered up.
  31362. //
  31363. // In a transform stream, the written data is placed in a buffer. When
  31364. // _read(n) is called, it transforms the queued up data, calling the
  31365. // buffered _write cb's as it consumes chunks. If consuming a single
  31366. // written chunk would result in multiple output chunks, then the first
  31367. // outputted bit calls the readcb, and subsequent chunks just go into
  31368. // the read buffer, and will cause it to emit 'readable' if necessary.
  31369. //
  31370. // This way, back-pressure is actually determined by the reading side,
  31371. // since _read has to be called to start processing a new chunk. However,
  31372. // a pathological inflate type of transform can cause excessive buffering
  31373. // here. For example, imagine a stream where every byte of input is
  31374. // interpreted as an integer from 0-255, and then results in that many
  31375. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  31376. // 1kb of data being output. In this case, you could write a very small
  31377. // amount of input, and end up with a very large amount of output. In
  31378. // such a pathological inflating mechanism, there'd be no way to tell
  31379. // the system to stop doing the transform. A single 4MB write could
  31380. // cause the system to run out of memory.
  31381. //
  31382. // However, even in such a pathological case, only a single written chunk
  31383. // would be consumed, and then the rest would wait (un-transformed) until
  31384. // the results of the previous transformed chunk were consumed.
  31385. 'use strict';
  31386. module.exports = Transform;
  31387. var _require$codes = require('../errors').codes,
  31388. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  31389. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  31390. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  31391. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  31392. var Duplex = require('./_stream_duplex');
  31393. require('inherits')(Transform, Duplex);
  31394. function afterTransform(er, data) {
  31395. var ts = this._transformState;
  31396. ts.transforming = false;
  31397. var cb = ts.writecb;
  31398. if (cb === null) {
  31399. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  31400. }
  31401. ts.writechunk = null;
  31402. ts.writecb = null;
  31403. if (data != null) // single equals check for both `null` and `undefined`
  31404. this.push(data);
  31405. cb(er);
  31406. var rs = this._readableState;
  31407. rs.reading = false;
  31408. if (rs.needReadable || rs.length < rs.highWaterMark) {
  31409. this._read(rs.highWaterMark);
  31410. }
  31411. }
  31412. function Transform(options) {
  31413. if (!(this instanceof Transform)) return new Transform(options);
  31414. Duplex.call(this, options);
  31415. this._transformState = {
  31416. afterTransform: afterTransform.bind(this),
  31417. needTransform: false,
  31418. transforming: false,
  31419. writecb: null,
  31420. writechunk: null,
  31421. writeencoding: null
  31422. }; // start out asking for a readable event once data is transformed.
  31423. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  31424. // that Readable wants before the first _read call, so unset the
  31425. // sync guard flag.
  31426. this._readableState.sync = false;
  31427. if (options) {
  31428. if (typeof options.transform === 'function') this._transform = options.transform;
  31429. if (typeof options.flush === 'function') this._flush = options.flush;
  31430. } // When the writable side finishes, then flush out anything remaining.
  31431. this.on('prefinish', prefinish);
  31432. }
  31433. function prefinish() {
  31434. var _this = this;
  31435. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  31436. this._flush(function (er, data) {
  31437. done(_this, er, data);
  31438. });
  31439. } else {
  31440. done(this, null, null);
  31441. }
  31442. }
  31443. Transform.prototype.push = function (chunk, encoding) {
  31444. this._transformState.needTransform = false;
  31445. return Duplex.prototype.push.call(this, chunk, encoding);
  31446. }; // This is the part where you do stuff!
  31447. // override this function in implementation classes.
  31448. // 'chunk' is an input chunk.
  31449. //
  31450. // Call `push(newChunk)` to pass along transformed output
  31451. // to the readable side. You may call 'push' zero or more times.
  31452. //
  31453. // Call `cb(err)` when you are done with this chunk. If you pass
  31454. // an error, then that'll put the hurt on the whole operation. If you
  31455. // never call cb(), then you'll never get another chunk.
  31456. Transform.prototype._transform = function (chunk, encoding, cb) {
  31457. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  31458. };
  31459. Transform.prototype._write = function (chunk, encoding, cb) {
  31460. var ts = this._transformState;
  31461. ts.writecb = cb;
  31462. ts.writechunk = chunk;
  31463. ts.writeencoding = encoding;
  31464. if (!ts.transforming) {
  31465. var rs = this._readableState;
  31466. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  31467. }
  31468. }; // Doesn't matter what the args are here.
  31469. // _transform does all the work.
  31470. // That we got here means that the readable side wants more data.
  31471. Transform.prototype._read = function (n) {
  31472. var ts = this._transformState;
  31473. if (ts.writechunk !== null && !ts.transforming) {
  31474. ts.transforming = true;
  31475. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  31476. } else {
  31477. // mark that we need a transform, so that any data that comes in
  31478. // will get processed, now that we've asked for it.
  31479. ts.needTransform = true;
  31480. }
  31481. };
  31482. Transform.prototype._destroy = function (err, cb) {
  31483. Duplex.prototype._destroy.call(this, err, function (err2) {
  31484. cb(err2);
  31485. });
  31486. };
  31487. function done(stream, er, data) {
  31488. if (er) return stream.emit('error', er);
  31489. if (data != null) // single equals check for both `null` and `undefined`
  31490. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  31491. // if there's nothing in the write buffer, then that means
  31492. // that nothing more will ever be provided
  31493. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  31494. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  31495. return stream.push(null);
  31496. }
  31497. },{"../errors":339,"./_stream_duplex":341,"inherits":254}],345:[function(require,module,exports){
  31498. (function (process,global){
  31499. // Copyright Joyent, Inc. and other Node contributors.
  31500. //
  31501. // Permission is hereby granted, free of charge, to any person obtaining a
  31502. // copy of this software and associated documentation files (the
  31503. // "Software"), to deal in the Software without restriction, including
  31504. // without limitation the rights to use, copy, modify, merge, publish,
  31505. // distribute, sublicense, and/or sell copies of the Software, and to permit
  31506. // persons to whom the Software is furnished to do so, subject to the
  31507. // following conditions:
  31508. //
  31509. // The above copyright notice and this permission notice shall be included
  31510. // in all copies or substantial portions of the Software.
  31511. //
  31512. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  31513. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31514. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  31515. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  31516. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  31517. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  31518. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  31519. // A bit simpler than readable streams.
  31520. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  31521. // the drain event emission and buffering.
  31522. 'use strict';
  31523. module.exports = Writable;
  31524. /* <replacement> */
  31525. function WriteReq(chunk, encoding, cb) {
  31526. this.chunk = chunk;
  31527. this.encoding = encoding;
  31528. this.callback = cb;
  31529. this.next = null;
  31530. } // It seems a linked list but it is not
  31531. // there will be only 2 of these for each stream
  31532. function CorkedRequest(state) {
  31533. var _this = this;
  31534. this.next = null;
  31535. this.entry = null;
  31536. this.finish = function () {
  31537. onCorkedFinish(_this, state);
  31538. };
  31539. }
  31540. /* </replacement> */
  31541. /*<replacement>*/
  31542. var Duplex;
  31543. /*</replacement>*/
  31544. Writable.WritableState = WritableState;
  31545. /*<replacement>*/
  31546. var internalUtil = {
  31547. deprecate: require('util-deprecate')
  31548. };
  31549. /*</replacement>*/
  31550. /*<replacement>*/
  31551. var Stream = require('./internal/streams/stream');
  31552. /*</replacement>*/
  31553. var Buffer = require('buffer').Buffer;
  31554. var OurUint8Array = global.Uint8Array || function () {};
  31555. function _uint8ArrayToBuffer(chunk) {
  31556. return Buffer.from(chunk);
  31557. }
  31558. function _isUint8Array(obj) {
  31559. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  31560. }
  31561. var destroyImpl = require('./internal/streams/destroy');
  31562. var _require = require('./internal/streams/state'),
  31563. getHighWaterMark = _require.getHighWaterMark;
  31564. var _require$codes = require('../errors').codes,
  31565. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  31566. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  31567. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  31568. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  31569. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  31570. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  31571. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  31572. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  31573. require('inherits')(Writable, Stream);
  31574. function nop() {}
  31575. function WritableState(options, stream, isDuplex) {
  31576. Duplex = Duplex || require('./_stream_duplex');
  31577. options = options || {}; // Duplex streams are both readable and writable, but share
  31578. // the same options object.
  31579. // However, some cases require setting options to different
  31580. // values for the readable and the writable sides of the duplex stream,
  31581. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  31582. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  31583. // contains buffers or objects.
  31584. this.objectMode = !!options.objectMode;
  31585. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  31586. // Note: 0 is a valid value, means that we always return false if
  31587. // the entire buffer is not flushed immediately on write()
  31588. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  31589. this.finalCalled = false; // drain event flag.
  31590. this.needDrain = false; // at the start of calling end()
  31591. this.ending = false; // when end() has been called, and returned
  31592. this.ended = false; // when 'finish' is emitted
  31593. this.finished = false; // has it been destroyed
  31594. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  31595. // this is here so that some node-core streams can optimize string
  31596. // handling at a lower level.
  31597. var noDecode = options.decodeStrings === false;
  31598. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  31599. // encoding is 'binary' so we have to make this configurable.
  31600. // Everything else in the universe uses 'utf8', though.
  31601. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  31602. // of how much we're waiting to get pushed to some underlying
  31603. // socket or file.
  31604. this.length = 0; // a flag to see when we're in the middle of a write.
  31605. this.writing = false; // when true all writes will be buffered until .uncork() call
  31606. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  31607. // or on a later tick. We set this to true at first, because any
  31608. // actions that shouldn't happen until "later" should generally also
  31609. // not happen before the first write call.
  31610. this.sync = true; // a flag to know if we're processing previously buffered items, which
  31611. // may call the _write() callback in the same tick, so that we don't
  31612. // end up in an overlapped onwrite situation.
  31613. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  31614. this.onwrite = function (er) {
  31615. onwrite(stream, er);
  31616. }; // the callback that the user supplies to write(chunk,encoding,cb)
  31617. this.writecb = null; // the amount that is being written when _write is called.
  31618. this.writelen = 0;
  31619. this.bufferedRequest = null;
  31620. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  31621. // this must be 0 before 'finish' can be emitted
  31622. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  31623. // This is relevant for synchronous Transform streams
  31624. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  31625. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  31626. this.emitClose = options.emitClose !== false; // count buffered requests
  31627. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  31628. // one allocated and free to use, and we maintain at most two
  31629. this.corkedRequestsFree = new CorkedRequest(this);
  31630. }
  31631. WritableState.prototype.getBuffer = function getBuffer() {
  31632. var current = this.bufferedRequest;
  31633. var out = [];
  31634. while (current) {
  31635. out.push(current);
  31636. current = current.next;
  31637. }
  31638. return out;
  31639. };
  31640. (function () {
  31641. try {
  31642. Object.defineProperty(WritableState.prototype, 'buffer', {
  31643. get: internalUtil.deprecate(function writableStateBufferGetter() {
  31644. return this.getBuffer();
  31645. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  31646. });
  31647. } catch (_) {}
  31648. })(); // Test _writableState for inheritance to account for Duplex streams,
  31649. // whose prototype chain only points to Readable.
  31650. var realHasInstance;
  31651. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  31652. realHasInstance = Function.prototype[Symbol.hasInstance];
  31653. Object.defineProperty(Writable, Symbol.hasInstance, {
  31654. value: function value(object) {
  31655. if (realHasInstance.call(this, object)) return true;
  31656. if (this !== Writable) return false;
  31657. return object && object._writableState instanceof WritableState;
  31658. }
  31659. });
  31660. } else {
  31661. realHasInstance = function realHasInstance(object) {
  31662. return object instanceof this;
  31663. };
  31664. }
  31665. function Writable(options) {
  31666. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  31667. // `realHasInstance` is necessary because using plain `instanceof`
  31668. // would return false, as no `_writableState` property is attached.
  31669. // Trying to use the custom `instanceof` for Writable here will also break the
  31670. // Node.js LazyTransform implementation, which has a non-trivial getter for
  31671. // `_writableState` that would lead to infinite recursion.
  31672. // Checking for a Stream.Duplex instance is faster here instead of inside
  31673. // the WritableState constructor, at least with V8 6.5
  31674. var isDuplex = this instanceof Duplex;
  31675. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  31676. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  31677. this.writable = true;
  31678. if (options) {
  31679. if (typeof options.write === 'function') this._write = options.write;
  31680. if (typeof options.writev === 'function') this._writev = options.writev;
  31681. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  31682. if (typeof options.final === 'function') this._final = options.final;
  31683. }
  31684. Stream.call(this);
  31685. } // Otherwise people can pipe Writable streams, which is just wrong.
  31686. Writable.prototype.pipe = function () {
  31687. this.emit('error', new ERR_STREAM_CANNOT_PIPE());
  31688. };
  31689. function writeAfterEnd(stream, cb) {
  31690. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  31691. stream.emit('error', er);
  31692. process.nextTick(cb, er);
  31693. } // Checks that a user-supplied chunk is valid, especially for the particular
  31694. // mode the stream is in. Currently this means that `null` is never accepted
  31695. // and undefined/non-string values are only allowed in object mode.
  31696. function validChunk(stream, state, chunk, cb) {
  31697. var er;
  31698. if (chunk === null) {
  31699. er = new ERR_STREAM_NULL_VALUES();
  31700. } else if (typeof chunk !== 'string' && !state.objectMode) {
  31701. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  31702. }
  31703. if (er) {
  31704. stream.emit('error', er);
  31705. process.nextTick(cb, er);
  31706. return false;
  31707. }
  31708. return true;
  31709. }
  31710. Writable.prototype.write = function (chunk, encoding, cb) {
  31711. var state = this._writableState;
  31712. var ret = false;
  31713. var isBuf = !state.objectMode && _isUint8Array(chunk);
  31714. if (isBuf && !Buffer.isBuffer(chunk)) {
  31715. chunk = _uint8ArrayToBuffer(chunk);
  31716. }
  31717. if (typeof encoding === 'function') {
  31718. cb = encoding;
  31719. encoding = null;
  31720. }
  31721. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  31722. if (typeof cb !== 'function') cb = nop;
  31723. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  31724. state.pendingcb++;
  31725. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  31726. }
  31727. return ret;
  31728. };
  31729. Writable.prototype.cork = function () {
  31730. this._writableState.corked++;
  31731. };
  31732. Writable.prototype.uncork = function () {
  31733. var state = this._writableState;
  31734. if (state.corked) {
  31735. state.corked--;
  31736. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  31737. }
  31738. };
  31739. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  31740. // node::ParseEncoding() requires lower case.
  31741. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  31742. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  31743. this._writableState.defaultEncoding = encoding;
  31744. return this;
  31745. };
  31746. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  31747. // making it explicit this property is not enumerable
  31748. // because otherwise some prototype manipulation in
  31749. // userland will fail
  31750. enumerable: false,
  31751. get: function get() {
  31752. return this._writableState && this._writableState.getBuffer();
  31753. }
  31754. });
  31755. function decodeChunk(state, chunk, encoding) {
  31756. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  31757. chunk = Buffer.from(chunk, encoding);
  31758. }
  31759. return chunk;
  31760. }
  31761. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  31762. // making it explicit this property is not enumerable
  31763. // because otherwise some prototype manipulation in
  31764. // userland will fail
  31765. enumerable: false,
  31766. get: function get() {
  31767. return this._writableState.highWaterMark;
  31768. }
  31769. }); // if we're already writing something, then just put this
  31770. // in the queue, and wait our turn. Otherwise, call _write
  31771. // If we return false, then we need a drain event, so set that flag.
  31772. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  31773. if (!isBuf) {
  31774. var newChunk = decodeChunk(state, chunk, encoding);
  31775. if (chunk !== newChunk) {
  31776. isBuf = true;
  31777. encoding = 'buffer';
  31778. chunk = newChunk;
  31779. }
  31780. }
  31781. var len = state.objectMode ? 1 : chunk.length;
  31782. state.length += len;
  31783. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  31784. if (!ret) state.needDrain = true;
  31785. if (state.writing || state.corked) {
  31786. var last = state.lastBufferedRequest;
  31787. state.lastBufferedRequest = {
  31788. chunk: chunk,
  31789. encoding: encoding,
  31790. isBuf: isBuf,
  31791. callback: cb,
  31792. next: null
  31793. };
  31794. if (last) {
  31795. last.next = state.lastBufferedRequest;
  31796. } else {
  31797. state.bufferedRequest = state.lastBufferedRequest;
  31798. }
  31799. state.bufferedRequestCount += 1;
  31800. } else {
  31801. doWrite(stream, state, false, len, chunk, encoding, cb);
  31802. }
  31803. return ret;
  31804. }
  31805. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  31806. state.writelen = len;
  31807. state.writecb = cb;
  31808. state.writing = true;
  31809. state.sync = true;
  31810. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  31811. state.sync = false;
  31812. }
  31813. function onwriteError(stream, state, sync, er, cb) {
  31814. --state.pendingcb;
  31815. if (sync) {
  31816. // defer the callback if we are being called synchronously
  31817. // to avoid piling up things on the stack
  31818. process.nextTick(cb, er); // this can emit finish, and it will always happen
  31819. // after error
  31820. process.nextTick(finishMaybe, stream, state);
  31821. stream._writableState.errorEmitted = true;
  31822. stream.emit('error', er);
  31823. } else {
  31824. // the caller expect this to happen before if
  31825. // it is async
  31826. cb(er);
  31827. stream._writableState.errorEmitted = true;
  31828. stream.emit('error', er); // this can emit finish, but finish must
  31829. // always follow error
  31830. finishMaybe(stream, state);
  31831. }
  31832. }
  31833. function onwriteStateUpdate(state) {
  31834. state.writing = false;
  31835. state.writecb = null;
  31836. state.length -= state.writelen;
  31837. state.writelen = 0;
  31838. }
  31839. function onwrite(stream, er) {
  31840. var state = stream._writableState;
  31841. var sync = state.sync;
  31842. var cb = state.writecb;
  31843. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  31844. onwriteStateUpdate(state);
  31845. if (er) onwriteError(stream, state, sync, er, cb);else {
  31846. // Check if we're actually ready to finish, but don't emit yet
  31847. var finished = needFinish(state) || stream.destroyed;
  31848. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  31849. clearBuffer(stream, state);
  31850. }
  31851. if (sync) {
  31852. process.nextTick(afterWrite, stream, state, finished, cb);
  31853. } else {
  31854. afterWrite(stream, state, finished, cb);
  31855. }
  31856. }
  31857. }
  31858. function afterWrite(stream, state, finished, cb) {
  31859. if (!finished) onwriteDrain(stream, state);
  31860. state.pendingcb--;
  31861. cb();
  31862. finishMaybe(stream, state);
  31863. } // Must force callback to be called on nextTick, so that we don't
  31864. // emit 'drain' before the write() consumer gets the 'false' return
  31865. // value, and has a chance to attach a 'drain' listener.
  31866. function onwriteDrain(stream, state) {
  31867. if (state.length === 0 && state.needDrain) {
  31868. state.needDrain = false;
  31869. stream.emit('drain');
  31870. }
  31871. } // if there's something in the buffer waiting, then process it
  31872. function clearBuffer(stream, state) {
  31873. state.bufferProcessing = true;
  31874. var entry = state.bufferedRequest;
  31875. if (stream._writev && entry && entry.next) {
  31876. // Fast case, write everything using _writev()
  31877. var l = state.bufferedRequestCount;
  31878. var buffer = new Array(l);
  31879. var holder = state.corkedRequestsFree;
  31880. holder.entry = entry;
  31881. var count = 0;
  31882. var allBuffers = true;
  31883. while (entry) {
  31884. buffer[count] = entry;
  31885. if (!entry.isBuf) allBuffers = false;
  31886. entry = entry.next;
  31887. count += 1;
  31888. }
  31889. buffer.allBuffers = allBuffers;
  31890. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  31891. // as the hot path ends with doWrite
  31892. state.pendingcb++;
  31893. state.lastBufferedRequest = null;
  31894. if (holder.next) {
  31895. state.corkedRequestsFree = holder.next;
  31896. holder.next = null;
  31897. } else {
  31898. state.corkedRequestsFree = new CorkedRequest(state);
  31899. }
  31900. state.bufferedRequestCount = 0;
  31901. } else {
  31902. // Slow case, write chunks one-by-one
  31903. while (entry) {
  31904. var chunk = entry.chunk;
  31905. var encoding = entry.encoding;
  31906. var cb = entry.callback;
  31907. var len = state.objectMode ? 1 : chunk.length;
  31908. doWrite(stream, state, false, len, chunk, encoding, cb);
  31909. entry = entry.next;
  31910. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  31911. // it means that we need to wait until it does.
  31912. // also, that means that the chunk and cb are currently
  31913. // being processed, so move the buffer counter past them.
  31914. if (state.writing) {
  31915. break;
  31916. }
  31917. }
  31918. if (entry === null) state.lastBufferedRequest = null;
  31919. }
  31920. state.bufferedRequest = entry;
  31921. state.bufferProcessing = false;
  31922. }
  31923. Writable.prototype._write = function (chunk, encoding, cb) {
  31924. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  31925. };
  31926. Writable.prototype._writev = null;
  31927. Writable.prototype.end = function (chunk, encoding, cb) {
  31928. var state = this._writableState;
  31929. if (typeof chunk === 'function') {
  31930. cb = chunk;
  31931. chunk = null;
  31932. encoding = null;
  31933. } else if (typeof encoding === 'function') {
  31934. cb = encoding;
  31935. encoding = null;
  31936. }
  31937. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  31938. if (state.corked) {
  31939. state.corked = 1;
  31940. this.uncork();
  31941. } // ignore unnecessary end() calls.
  31942. if (!state.ending) endWritable(this, state, cb);
  31943. return this;
  31944. };
  31945. Object.defineProperty(Writable.prototype, 'writableLength', {
  31946. // making it explicit this property is not enumerable
  31947. // because otherwise some prototype manipulation in
  31948. // userland will fail
  31949. enumerable: false,
  31950. get: function get() {
  31951. return this._writableState.length;
  31952. }
  31953. });
  31954. function needFinish(state) {
  31955. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  31956. }
  31957. function callFinal(stream, state) {
  31958. stream._final(function (err) {
  31959. state.pendingcb--;
  31960. if (err) {
  31961. stream.emit('error', err);
  31962. }
  31963. state.prefinished = true;
  31964. stream.emit('prefinish');
  31965. finishMaybe(stream, state);
  31966. });
  31967. }
  31968. function prefinish(stream, state) {
  31969. if (!state.prefinished && !state.finalCalled) {
  31970. if (typeof stream._final === 'function' && !state.destroyed) {
  31971. state.pendingcb++;
  31972. state.finalCalled = true;
  31973. process.nextTick(callFinal, stream, state);
  31974. } else {
  31975. state.prefinished = true;
  31976. stream.emit('prefinish');
  31977. }
  31978. }
  31979. }
  31980. function finishMaybe(stream, state) {
  31981. var need = needFinish(state);
  31982. if (need) {
  31983. prefinish(stream, state);
  31984. if (state.pendingcb === 0) {
  31985. state.finished = true;
  31986. stream.emit('finish');
  31987. }
  31988. }
  31989. return need;
  31990. }
  31991. function endWritable(stream, state, cb) {
  31992. state.ending = true;
  31993. finishMaybe(stream, state);
  31994. if (cb) {
  31995. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  31996. }
  31997. state.ended = true;
  31998. stream.writable = false;
  31999. }
  32000. function onCorkedFinish(corkReq, state, err) {
  32001. var entry = corkReq.entry;
  32002. corkReq.entry = null;
  32003. while (entry) {
  32004. var cb = entry.callback;
  32005. state.pendingcb--;
  32006. cb(err);
  32007. entry = entry.next;
  32008. } // reuse the free corkReq.
  32009. state.corkedRequestsFree.next = corkReq;
  32010. }
  32011. Object.defineProperty(Writable.prototype, 'destroyed', {
  32012. // making it explicit this property is not enumerable
  32013. // because otherwise some prototype manipulation in
  32014. // userland will fail
  32015. enumerable: false,
  32016. get: function get() {
  32017. if (this._writableState === undefined) {
  32018. return false;
  32019. }
  32020. return this._writableState.destroyed;
  32021. },
  32022. set: function set(value) {
  32023. // we ignore the value if the stream
  32024. // has not been initialized yet
  32025. if (!this._writableState) {
  32026. return;
  32027. } // backward compatibility, the user is explicitly
  32028. // managing destroyed
  32029. this._writableState.destroyed = value;
  32030. }
  32031. });
  32032. Writable.prototype.destroy = destroyImpl.destroy;
  32033. Writable.prototype._undestroy = destroyImpl.undestroy;
  32034. Writable.prototype._destroy = function (err, cb) {
  32035. cb(err);
  32036. };
  32037. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32038. },{"../errors":339,"./_stream_duplex":341,"./internal/streams/destroy":348,"./internal/streams/state":351,"./internal/streams/stream":352,"_process":312,"buffer":47,"inherits":254,"util-deprecate":362}],346:[function(require,module,exports){
  32039. (function (process){
  32040. 'use strict';
  32041. var _Object$setPrototypeO;
  32042. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  32043. var finished = require('./end-of-stream');
  32044. var kLastResolve = Symbol('lastResolve');
  32045. var kLastReject = Symbol('lastReject');
  32046. var kError = Symbol('error');
  32047. var kEnded = Symbol('ended');
  32048. var kLastPromise = Symbol('lastPromise');
  32049. var kHandlePromise = Symbol('handlePromise');
  32050. var kStream = Symbol('stream');
  32051. function createIterResult(value, done) {
  32052. return {
  32053. value: value,
  32054. done: done
  32055. };
  32056. }
  32057. function readAndResolve(iter) {
  32058. var resolve = iter[kLastResolve];
  32059. if (resolve !== null) {
  32060. var data = iter[kStream].read(); // we defer if data is null
  32061. // we can be expecting either 'end' or
  32062. // 'error'
  32063. if (data !== null) {
  32064. iter[kLastPromise] = null;
  32065. iter[kLastResolve] = null;
  32066. iter[kLastReject] = null;
  32067. resolve(createIterResult(data, false));
  32068. }
  32069. }
  32070. }
  32071. function onReadable(iter) {
  32072. // we wait for the next tick, because it might
  32073. // emit an error with process.nextTick
  32074. process.nextTick(readAndResolve, iter);
  32075. }
  32076. function wrapForNext(lastPromise, iter) {
  32077. return function (resolve, reject) {
  32078. lastPromise.then(function () {
  32079. if (iter[kEnded]) {
  32080. resolve(createIterResult(undefined, true));
  32081. return;
  32082. }
  32083. iter[kHandlePromise](resolve, reject);
  32084. }, reject);
  32085. };
  32086. }
  32087. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  32088. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  32089. get stream() {
  32090. return this[kStream];
  32091. },
  32092. next: function next() {
  32093. var _this = this;
  32094. // if we have detected an error in the meanwhile
  32095. // reject straight away
  32096. var error = this[kError];
  32097. if (error !== null) {
  32098. return Promise.reject(error);
  32099. }
  32100. if (this[kEnded]) {
  32101. return Promise.resolve(createIterResult(undefined, true));
  32102. }
  32103. if (this[kStream].destroyed) {
  32104. // We need to defer via nextTick because if .destroy(err) is
  32105. // called, the error will be emitted via nextTick, and
  32106. // we cannot guarantee that there is no error lingering around
  32107. // waiting to be emitted.
  32108. return new Promise(function (resolve, reject) {
  32109. process.nextTick(function () {
  32110. if (_this[kError]) {
  32111. reject(_this[kError]);
  32112. } else {
  32113. resolve(createIterResult(undefined, true));
  32114. }
  32115. });
  32116. });
  32117. } // if we have multiple next() calls
  32118. // we will wait for the previous Promise to finish
  32119. // this logic is optimized to support for await loops,
  32120. // where next() is only called once at a time
  32121. var lastPromise = this[kLastPromise];
  32122. var promise;
  32123. if (lastPromise) {
  32124. promise = new Promise(wrapForNext(lastPromise, this));
  32125. } else {
  32126. // fast path needed to support multiple this.push()
  32127. // without triggering the next() queue
  32128. var data = this[kStream].read();
  32129. if (data !== null) {
  32130. return Promise.resolve(createIterResult(data, false));
  32131. }
  32132. promise = new Promise(this[kHandlePromise]);
  32133. }
  32134. this[kLastPromise] = promise;
  32135. return promise;
  32136. }
  32137. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  32138. return this;
  32139. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  32140. var _this2 = this;
  32141. // destroy(err, cb) is a private API
  32142. // we can guarantee we have that here, because we control the
  32143. // Readable class this is attached to
  32144. return new Promise(function (resolve, reject) {
  32145. _this2[kStream].destroy(null, function (err) {
  32146. if (err) {
  32147. reject(err);
  32148. return;
  32149. }
  32150. resolve(createIterResult(undefined, true));
  32151. });
  32152. });
  32153. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  32154. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  32155. var _Object$create;
  32156. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  32157. value: stream,
  32158. writable: true
  32159. }), _defineProperty(_Object$create, kLastResolve, {
  32160. value: null,
  32161. writable: true
  32162. }), _defineProperty(_Object$create, kLastReject, {
  32163. value: null,
  32164. writable: true
  32165. }), _defineProperty(_Object$create, kError, {
  32166. value: null,
  32167. writable: true
  32168. }), _defineProperty(_Object$create, kEnded, {
  32169. value: stream._readableState.endEmitted,
  32170. writable: true
  32171. }), _defineProperty(_Object$create, kHandlePromise, {
  32172. value: function value(resolve, reject) {
  32173. var data = iterator[kStream].read();
  32174. if (data) {
  32175. iterator[kLastPromise] = null;
  32176. iterator[kLastResolve] = null;
  32177. iterator[kLastReject] = null;
  32178. resolve(createIterResult(data, false));
  32179. } else {
  32180. iterator[kLastResolve] = resolve;
  32181. iterator[kLastReject] = reject;
  32182. }
  32183. },
  32184. writable: true
  32185. }), _Object$create));
  32186. iterator[kLastPromise] = null;
  32187. finished(stream, function (err) {
  32188. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  32189. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  32190. // returned by next() and store the error
  32191. if (reject !== null) {
  32192. iterator[kLastPromise] = null;
  32193. iterator[kLastResolve] = null;
  32194. iterator[kLastReject] = null;
  32195. reject(err);
  32196. }
  32197. iterator[kError] = err;
  32198. return;
  32199. }
  32200. var resolve = iterator[kLastResolve];
  32201. if (resolve !== null) {
  32202. iterator[kLastPromise] = null;
  32203. iterator[kLastResolve] = null;
  32204. iterator[kLastReject] = null;
  32205. resolve(createIterResult(undefined, true));
  32206. }
  32207. iterator[kEnded] = true;
  32208. });
  32209. stream.on('readable', onReadable.bind(null, iterator));
  32210. return iterator;
  32211. };
  32212. module.exports = createReadableStreamAsyncIterator;
  32213. }).call(this,require('_process'))
  32214. },{"./end-of-stream":349,"_process":312}],347:[function(require,module,exports){
  32215. 'use strict';
  32216. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
  32217. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  32218. var _require = require('buffer'),
  32219. Buffer = _require.Buffer;
  32220. var _require2 = require('util'),
  32221. inspect = _require2.inspect;
  32222. var custom = inspect && inspect.custom || 'inspect';
  32223. function copyBuffer(src, target, offset) {
  32224. Buffer.prototype.copy.call(src, target, offset);
  32225. }
  32226. module.exports =
  32227. /*#__PURE__*/
  32228. function () {
  32229. function BufferList() {
  32230. this.head = null;
  32231. this.tail = null;
  32232. this.length = 0;
  32233. }
  32234. var _proto = BufferList.prototype;
  32235. _proto.push = function push(v) {
  32236. var entry = {
  32237. data: v,
  32238. next: null
  32239. };
  32240. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  32241. this.tail = entry;
  32242. ++this.length;
  32243. };
  32244. _proto.unshift = function unshift(v) {
  32245. var entry = {
  32246. data: v,
  32247. next: this.head
  32248. };
  32249. if (this.length === 0) this.tail = entry;
  32250. this.head = entry;
  32251. ++this.length;
  32252. };
  32253. _proto.shift = function shift() {
  32254. if (this.length === 0) return;
  32255. var ret = this.head.data;
  32256. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  32257. --this.length;
  32258. return ret;
  32259. };
  32260. _proto.clear = function clear() {
  32261. this.head = this.tail = null;
  32262. this.length = 0;
  32263. };
  32264. _proto.join = function join(s) {
  32265. if (this.length === 0) return '';
  32266. var p = this.head;
  32267. var ret = '' + p.data;
  32268. while (p = p.next) {
  32269. ret += s + p.data;
  32270. }
  32271. return ret;
  32272. };
  32273. _proto.concat = function concat(n) {
  32274. if (this.length === 0) return Buffer.alloc(0);
  32275. var ret = Buffer.allocUnsafe(n >>> 0);
  32276. var p = this.head;
  32277. var i = 0;
  32278. while (p) {
  32279. copyBuffer(p.data, ret, i);
  32280. i += p.data.length;
  32281. p = p.next;
  32282. }
  32283. return ret;
  32284. } // Consumes a specified amount of bytes or characters from the buffered data.
  32285. ;
  32286. _proto.consume = function consume(n, hasStrings) {
  32287. var ret;
  32288. if (n < this.head.data.length) {
  32289. // `slice` is the same for buffers and strings.
  32290. ret = this.head.data.slice(0, n);
  32291. this.head.data = this.head.data.slice(n);
  32292. } else if (n === this.head.data.length) {
  32293. // First chunk is a perfect match.
  32294. ret = this.shift();
  32295. } else {
  32296. // Result spans more than one buffer.
  32297. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  32298. }
  32299. return ret;
  32300. };
  32301. _proto.first = function first() {
  32302. return this.head.data;
  32303. } // Consumes a specified amount of characters from the buffered data.
  32304. ;
  32305. _proto._getString = function _getString(n) {
  32306. var p = this.head;
  32307. var c = 1;
  32308. var ret = p.data;
  32309. n -= ret.length;
  32310. while (p = p.next) {
  32311. var str = p.data;
  32312. var nb = n > str.length ? str.length : n;
  32313. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  32314. n -= nb;
  32315. if (n === 0) {
  32316. if (nb === str.length) {
  32317. ++c;
  32318. if (p.next) this.head = p.next;else this.head = this.tail = null;
  32319. } else {
  32320. this.head = p;
  32321. p.data = str.slice(nb);
  32322. }
  32323. break;
  32324. }
  32325. ++c;
  32326. }
  32327. this.length -= c;
  32328. return ret;
  32329. } // Consumes a specified amount of bytes from the buffered data.
  32330. ;
  32331. _proto._getBuffer = function _getBuffer(n) {
  32332. var ret = Buffer.allocUnsafe(n);
  32333. var p = this.head;
  32334. var c = 1;
  32335. p.data.copy(ret);
  32336. n -= p.data.length;
  32337. while (p = p.next) {
  32338. var buf = p.data;
  32339. var nb = n > buf.length ? buf.length : n;
  32340. buf.copy(ret, ret.length - n, 0, nb);
  32341. n -= nb;
  32342. if (n === 0) {
  32343. if (nb === buf.length) {
  32344. ++c;
  32345. if (p.next) this.head = p.next;else this.head = this.tail = null;
  32346. } else {
  32347. this.head = p;
  32348. p.data = buf.slice(nb);
  32349. }
  32350. break;
  32351. }
  32352. ++c;
  32353. }
  32354. this.length -= c;
  32355. return ret;
  32356. } // Make sure the linked list only shows the minimal necessary information.
  32357. ;
  32358. _proto[custom] = function (_, options) {
  32359. return inspect(this, _objectSpread({}, options, {
  32360. // Only inspect one level.
  32361. depth: 0,
  32362. // It should not recurse.
  32363. customInspect: false
  32364. }));
  32365. };
  32366. return BufferList;
  32367. }();
  32368. },{"buffer":47,"util":32}],348:[function(require,module,exports){
  32369. (function (process){
  32370. 'use strict'; // undocumented cb() API, needed for core, not for public API
  32371. function destroy(err, cb) {
  32372. var _this = this;
  32373. var readableDestroyed = this._readableState && this._readableState.destroyed;
  32374. var writableDestroyed = this._writableState && this._writableState.destroyed;
  32375. if (readableDestroyed || writableDestroyed) {
  32376. if (cb) {
  32377. cb(err);
  32378. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  32379. process.nextTick(emitErrorNT, this, err);
  32380. }
  32381. return this;
  32382. } // we set destroyed to true before firing error callbacks in order
  32383. // to make it re-entrance safe in case destroy() is called within callbacks
  32384. if (this._readableState) {
  32385. this._readableState.destroyed = true;
  32386. } // if this is a duplex stream mark the writable part as destroyed as well
  32387. if (this._writableState) {
  32388. this._writableState.destroyed = true;
  32389. }
  32390. this._destroy(err || null, function (err) {
  32391. if (!cb && err) {
  32392. process.nextTick(emitErrorAndCloseNT, _this, err);
  32393. if (_this._writableState) {
  32394. _this._writableState.errorEmitted = true;
  32395. }
  32396. } else if (cb) {
  32397. process.nextTick(emitCloseNT, _this);
  32398. cb(err);
  32399. } else {
  32400. process.nextTick(emitCloseNT, _this);
  32401. }
  32402. });
  32403. return this;
  32404. }
  32405. function emitErrorAndCloseNT(self, err) {
  32406. emitErrorNT(self, err);
  32407. emitCloseNT(self);
  32408. }
  32409. function emitCloseNT(self) {
  32410. if (self._writableState && !self._writableState.emitClose) return;
  32411. if (self._readableState && !self._readableState.emitClose) return;
  32412. self.emit('close');
  32413. }
  32414. function undestroy() {
  32415. if (this._readableState) {
  32416. this._readableState.destroyed = false;
  32417. this._readableState.reading = false;
  32418. this._readableState.ended = false;
  32419. this._readableState.endEmitted = false;
  32420. }
  32421. if (this._writableState) {
  32422. this._writableState.destroyed = false;
  32423. this._writableState.ended = false;
  32424. this._writableState.ending = false;
  32425. this._writableState.finalCalled = false;
  32426. this._writableState.prefinished = false;
  32427. this._writableState.finished = false;
  32428. this._writableState.errorEmitted = false;
  32429. }
  32430. }
  32431. function emitErrorNT(self, err) {
  32432. self.emit('error', err);
  32433. }
  32434. module.exports = {
  32435. destroy: destroy,
  32436. undestroy: undestroy
  32437. };
  32438. }).call(this,require('_process'))
  32439. },{"_process":312}],349:[function(require,module,exports){
  32440. // Ported from https://github.com/mafintosh/end-of-stream with
  32441. // permission from the author, Mathias Buus (@mafintosh).
  32442. 'use strict';
  32443. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  32444. function once(callback) {
  32445. var called = false;
  32446. return function () {
  32447. if (called) return;
  32448. called = true;
  32449. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  32450. args[_key] = arguments[_key];
  32451. }
  32452. callback.apply(this, args);
  32453. };
  32454. }
  32455. function noop() {}
  32456. function isRequest(stream) {
  32457. return stream.setHeader && typeof stream.abort === 'function';
  32458. }
  32459. function eos(stream, opts, callback) {
  32460. if (typeof opts === 'function') return eos(stream, null, opts);
  32461. if (!opts) opts = {};
  32462. callback = once(callback || noop);
  32463. var readable = opts.readable || opts.readable !== false && stream.readable;
  32464. var writable = opts.writable || opts.writable !== false && stream.writable;
  32465. var onlegacyfinish = function onlegacyfinish() {
  32466. if (!stream.writable) onfinish();
  32467. };
  32468. var writableEnded = stream._writableState && stream._writableState.finished;
  32469. var onfinish = function onfinish() {
  32470. writable = false;
  32471. writableEnded = true;
  32472. if (!readable) callback.call(stream);
  32473. };
  32474. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  32475. var onend = function onend() {
  32476. readable = false;
  32477. readableEnded = true;
  32478. if (!writable) callback.call(stream);
  32479. };
  32480. var onerror = function onerror(err) {
  32481. callback.call(stream, err);
  32482. };
  32483. var onclose = function onclose() {
  32484. var err;
  32485. if (readable && !readableEnded) {
  32486. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  32487. return callback.call(stream, err);
  32488. }
  32489. if (writable && !writableEnded) {
  32490. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  32491. return callback.call(stream, err);
  32492. }
  32493. };
  32494. var onrequest = function onrequest() {
  32495. stream.req.on('finish', onfinish);
  32496. };
  32497. if (isRequest(stream)) {
  32498. stream.on('complete', onfinish);
  32499. stream.on('abort', onclose);
  32500. if (stream.req) onrequest();else stream.on('request', onrequest);
  32501. } else if (writable && !stream._writableState) {
  32502. // legacy streams
  32503. stream.on('end', onlegacyfinish);
  32504. stream.on('close', onlegacyfinish);
  32505. }
  32506. stream.on('end', onend);
  32507. stream.on('finish', onfinish);
  32508. if (opts.error !== false) stream.on('error', onerror);
  32509. stream.on('close', onclose);
  32510. return function () {
  32511. stream.removeListener('complete', onfinish);
  32512. stream.removeListener('abort', onclose);
  32513. stream.removeListener('request', onrequest);
  32514. if (stream.req) stream.req.removeListener('finish', onfinish);
  32515. stream.removeListener('end', onlegacyfinish);
  32516. stream.removeListener('close', onlegacyfinish);
  32517. stream.removeListener('finish', onfinish);
  32518. stream.removeListener('end', onend);
  32519. stream.removeListener('error', onerror);
  32520. stream.removeListener('close', onclose);
  32521. };
  32522. }
  32523. module.exports = eos;
  32524. },{"../../../errors":339}],350:[function(require,module,exports){
  32525. // Ported from https://github.com/mafintosh/pump with
  32526. // permission from the author, Mathias Buus (@mafintosh).
  32527. 'use strict';
  32528. var eos;
  32529. function once(callback) {
  32530. var called = false;
  32531. return function () {
  32532. if (called) return;
  32533. called = true;
  32534. callback.apply(void 0, arguments);
  32535. };
  32536. }
  32537. var _require$codes = require('../../../errors').codes,
  32538. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  32539. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  32540. function noop(err) {
  32541. // Rethrow the error if it exists to avoid swallowing it
  32542. if (err) throw err;
  32543. }
  32544. function isRequest(stream) {
  32545. return stream.setHeader && typeof stream.abort === 'function';
  32546. }
  32547. function destroyer(stream, reading, writing, callback) {
  32548. callback = once(callback);
  32549. var closed = false;
  32550. stream.on('close', function () {
  32551. closed = true;
  32552. });
  32553. if (eos === undefined) eos = require('./end-of-stream');
  32554. eos(stream, {
  32555. readable: reading,
  32556. writable: writing
  32557. }, function (err) {
  32558. if (err) return callback(err);
  32559. closed = true;
  32560. callback();
  32561. });
  32562. var destroyed = false;
  32563. return function (err) {
  32564. if (closed) return;
  32565. if (destroyed) return;
  32566. destroyed = true; // request.destroy just do .end - .abort is what we want
  32567. if (isRequest(stream)) return stream.abort();
  32568. if (typeof stream.destroy === 'function') return stream.destroy();
  32569. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  32570. };
  32571. }
  32572. function call(fn) {
  32573. fn();
  32574. }
  32575. function pipe(from, to) {
  32576. return from.pipe(to);
  32577. }
  32578. function popCallback(streams) {
  32579. if (!streams.length) return noop;
  32580. if (typeof streams[streams.length - 1] !== 'function') return noop;
  32581. return streams.pop();
  32582. }
  32583. function pipeline() {
  32584. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  32585. streams[_key] = arguments[_key];
  32586. }
  32587. var callback = popCallback(streams);
  32588. if (Array.isArray(streams[0])) streams = streams[0];
  32589. if (streams.length < 2) {
  32590. throw new ERR_MISSING_ARGS('streams');
  32591. }
  32592. var error;
  32593. var destroys = streams.map(function (stream, i) {
  32594. var reading = i < streams.length - 1;
  32595. var writing = i > 0;
  32596. return destroyer(stream, reading, writing, function (err) {
  32597. if (!error) error = err;
  32598. if (err) destroys.forEach(call);
  32599. if (reading) return;
  32600. destroys.forEach(call);
  32601. callback(error);
  32602. });
  32603. });
  32604. return streams.reduce(pipe);
  32605. }
  32606. module.exports = pipeline;
  32607. },{"../../../errors":339,"./end-of-stream":349}],351:[function(require,module,exports){
  32608. 'use strict';
  32609. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  32610. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  32611. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  32612. }
  32613. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  32614. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  32615. if (hwm != null) {
  32616. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  32617. var name = isDuplex ? duplexKey : 'highWaterMark';
  32618. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  32619. }
  32620. return Math.floor(hwm);
  32621. } // Default value
  32622. return state.objectMode ? 16 : 16 * 1024;
  32623. }
  32624. module.exports = {
  32625. getHighWaterMark: getHighWaterMark
  32626. };
  32627. },{"../../../errors":339}],352:[function(require,module,exports){
  32628. arguments[4][325][0].apply(exports,arguments)
  32629. },{"dup":325,"events":239}],353:[function(require,module,exports){
  32630. exports = module.exports = require('./lib/_stream_readable.js');
  32631. exports.Stream = exports;
  32632. exports.Readable = exports;
  32633. exports.Writable = require('./lib/_stream_writable.js');
  32634. exports.Duplex = require('./lib/_stream_duplex.js');
  32635. exports.Transform = require('./lib/_stream_transform.js');
  32636. exports.PassThrough = require('./lib/_stream_passthrough.js');
  32637. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  32638. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  32639. },{"./lib/_stream_duplex.js":341,"./lib/_stream_passthrough.js":342,"./lib/_stream_readable.js":343,"./lib/_stream_transform.js":344,"./lib/_stream_writable.js":345,"./lib/internal/streams/end-of-stream.js":349,"./lib/internal/streams/pipeline.js":350}],354:[function(require,module,exports){
  32640. arguments[4][327][0].apply(exports,arguments)
  32641. },{"dup":327,"safe-buffer":333}],355:[function(require,module,exports){
  32642. (function (setImmediate,clearImmediate){
  32643. var nextTick = require('process/browser.js').nextTick;
  32644. var apply = Function.prototype.apply;
  32645. var slice = Array.prototype.slice;
  32646. var immediateIds = {};
  32647. var nextImmediateId = 0;
  32648. // DOM APIs, for completeness
  32649. exports.setTimeout = function() {
  32650. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  32651. };
  32652. exports.setInterval = function() {
  32653. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  32654. };
  32655. exports.clearTimeout =
  32656. exports.clearInterval = function(timeout) { timeout.close(); };
  32657. function Timeout(id, clearFn) {
  32658. this._id = id;
  32659. this._clearFn = clearFn;
  32660. }
  32661. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  32662. Timeout.prototype.close = function() {
  32663. this._clearFn.call(window, this._id);
  32664. };
  32665. // Does not start the time, just sets up the members needed.
  32666. exports.enroll = function(item, msecs) {
  32667. clearTimeout(item._idleTimeoutId);
  32668. item._idleTimeout = msecs;
  32669. };
  32670. exports.unenroll = function(item) {
  32671. clearTimeout(item._idleTimeoutId);
  32672. item._idleTimeout = -1;
  32673. };
  32674. exports._unrefActive = exports.active = function(item) {
  32675. clearTimeout(item._idleTimeoutId);
  32676. var msecs = item._idleTimeout;
  32677. if (msecs >= 0) {
  32678. item._idleTimeoutId = setTimeout(function onTimeout() {
  32679. if (item._onTimeout)
  32680. item._onTimeout();
  32681. }, msecs);
  32682. }
  32683. };
  32684. // That's not how node.js implements it but the exposed api is the same.
  32685. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  32686. var id = nextImmediateId++;
  32687. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  32688. immediateIds[id] = true;
  32689. nextTick(function onNextTick() {
  32690. if (immediateIds[id]) {
  32691. // fn.call() is faster so we optimize for the common use-case
  32692. // @see http://jsperf.com/call-apply-segu
  32693. if (args) {
  32694. fn.apply(null, args);
  32695. } else {
  32696. fn.call(null);
  32697. }
  32698. // Prevent ids from leaking
  32699. exports.clearImmediate(id);
  32700. }
  32701. });
  32702. return id;
  32703. };
  32704. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  32705. delete immediateIds[id];
  32706. };
  32707. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  32708. },{"process/browser.js":312,"timers":355}],356:[function(require,module,exports){
  32709. (function (process){
  32710. 'use strict';
  32711. Object.defineProperty(exports, "__esModule", {
  32712. value: true
  32713. });
  32714. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  32715. exports.clone = clone;
  32716. exports.addLast = addLast;
  32717. exports.addFirst = addFirst;
  32718. exports.removeLast = removeLast;
  32719. exports.removeFirst = removeFirst;
  32720. exports.insert = insert;
  32721. exports.removeAt = removeAt;
  32722. exports.replaceAt = replaceAt;
  32723. exports.getIn = getIn;
  32724. exports.set = set;
  32725. exports.setIn = setIn;
  32726. exports.update = update;
  32727. exports.updateIn = updateIn;
  32728. exports.merge = merge;
  32729. exports.mergeDeep = mergeDeep;
  32730. exports.mergeIn = mergeIn;
  32731. exports.omit = omit;
  32732. exports.addDefaults = addDefaults;
  32733. /*!
  32734. * Timm
  32735. *
  32736. * Immutability helpers with fast reads and acceptable writes.
  32737. *
  32738. * @copyright Guillermo Grau Panea 2016
  32739. * @license MIT
  32740. */
  32741. var INVALID_ARGS = 'INVALID_ARGS';
  32742. // ===============================================
  32743. // ### Helpers
  32744. // ===============================================
  32745. function throwStr(msg) {
  32746. throw new Error(msg);
  32747. }
  32748. function getKeysAndSymbols(obj) {
  32749. var keys = Object.keys(obj);
  32750. if (Object.getOwnPropertySymbols) {
  32751. return keys.concat(Object.getOwnPropertySymbols(obj));
  32752. }
  32753. return keys;
  32754. }
  32755. var hasOwnProperty = {}.hasOwnProperty;
  32756. function clone(obj) {
  32757. if (Array.isArray(obj)) return obj.slice();
  32758. var keys = getKeysAndSymbols(obj);
  32759. var out = {};
  32760. for (var i = 0; i < keys.length; i++) {
  32761. var key = keys[i];
  32762. out[key] = obj[key];
  32763. }
  32764. return out;
  32765. }
  32766. function doMerge(fAddDefaults, fDeep, first) {
  32767. var out = first;
  32768. !(out != null) && throwStr(process.env.NODE_ENV !== 'production' ? 'At least one object should be provided to merge()' : INVALID_ARGS);
  32769. var fChanged = false;
  32770. for (var _len = arguments.length, rest = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  32771. rest[_key - 3] = arguments[_key];
  32772. }
  32773. for (var idx = 0; idx < rest.length; idx++) {
  32774. var obj = rest[idx];
  32775. if (obj == null) continue;
  32776. var keys = getKeysAndSymbols(obj);
  32777. if (!keys.length) continue;
  32778. for (var j = 0; j <= keys.length; j++) {
  32779. var key = keys[j];
  32780. if (fAddDefaults && out[key] !== undefined) continue;
  32781. var nextVal = obj[key];
  32782. if (fDeep && isObject(out[key]) && isObject(nextVal)) {
  32783. nextVal = doMerge(fAddDefaults, fDeep, out[key], nextVal);
  32784. }
  32785. if (nextVal === undefined || nextVal === out[key]) continue;
  32786. if (!fChanged) {
  32787. fChanged = true;
  32788. out = clone(out);
  32789. }
  32790. out[key] = nextVal;
  32791. }
  32792. }
  32793. return out;
  32794. }
  32795. function isObject(o) {
  32796. var type = typeof o === 'undefined' ? 'undefined' : _typeof(o);
  32797. return o != null && type === 'object';
  32798. }
  32799. // _deepFreeze = (obj) ->
  32800. // Object.freeze obj
  32801. // for key in Object.getOwnPropertyNames obj
  32802. // val = obj[key]
  32803. // if isObject(val) and not Object.isFrozen val
  32804. // _deepFreeze val
  32805. // obj
  32806. // ===============================================
  32807. // -- ### Arrays
  32808. // ===============================================
  32809. // -- #### addLast()
  32810. // -- Returns a new array with an appended item or items.
  32811. // --
  32812. // -- Usage: `addLast<T>(array: Array<T>, val: Array<T>|T): Array<T>`
  32813. // --
  32814. // -- ```js
  32815. // -- arr = ['a', 'b']
  32816. // -- arr2 = addLast(arr, 'c')
  32817. // -- // ['a', 'b', 'c']
  32818. // -- arr2 === arr
  32819. // -- // false
  32820. // -- arr3 = addLast(arr, ['c', 'd'])
  32821. // -- // ['a', 'b', 'c', 'd']
  32822. // -- ```
  32823. // `array.concat(val)` also handles the scalar case,
  32824. // but is apparently very slow
  32825. function addLast(array, val) {
  32826. if (Array.isArray(val)) return array.concat(val);
  32827. return array.concat([val]);
  32828. }
  32829. // -- #### addFirst()
  32830. // -- Returns a new array with a prepended item or items.
  32831. // --
  32832. // -- Usage: `addFirst<T>(array: Array<T>, val: Array<T>|T): Array<T>`
  32833. // --
  32834. // -- ```js
  32835. // -- arr = ['a', 'b']
  32836. // -- arr2 = addFirst(arr, 'c')
  32837. // -- // ['c', 'a', 'b']
  32838. // -- arr2 === arr
  32839. // -- // false
  32840. // -- arr3 = addFirst(arr, ['c', 'd'])
  32841. // -- // ['c', 'd', 'a', 'b']
  32842. // -- ```
  32843. function addFirst(array, val) {
  32844. if (Array.isArray(val)) return val.concat(array);
  32845. return [val].concat(array);
  32846. }
  32847. // -- #### removeLast()
  32848. // -- Returns a new array removing the last item.
  32849. // --
  32850. // -- Usage: `removeLast<T>(array: Array<T>): Array<T>`
  32851. // --
  32852. // -- ```js
  32853. // -- arr = ['a', 'b']
  32854. // -- arr2 = removeLast(arr)
  32855. // -- // ['a']
  32856. // -- arr2 === arr
  32857. // -- // false
  32858. // --
  32859. // -- // The same array is returned if there are no changes:
  32860. // -- arr3 = []
  32861. // -- removeLast(arr3) === arr3
  32862. // -- // true
  32863. // -- ```
  32864. function removeLast(array) {
  32865. if (!array.length) return array;
  32866. return array.slice(0, array.length - 1);
  32867. }
  32868. // -- #### removeFirst()
  32869. // -- Returns a new array removing the first item.
  32870. // --
  32871. // -- Usage: `removeFirst<T>(array: Array<T>): Array<T>`
  32872. // --
  32873. // -- ```js
  32874. // -- arr = ['a', 'b']
  32875. // -- arr2 = removeFirst(arr)
  32876. // -- // ['b']
  32877. // -- arr2 === arr
  32878. // -- // false
  32879. // --
  32880. // -- // The same array is returned if there are no changes:
  32881. // -- arr3 = []
  32882. // -- removeFirst(arr3) === arr3
  32883. // -- // true
  32884. // -- ```
  32885. function removeFirst(array) {
  32886. if (!array.length) return array;
  32887. return array.slice(1);
  32888. }
  32889. // -- #### insert()
  32890. // -- Returns a new array obtained by inserting an item or items
  32891. // -- at a specified index.
  32892. // --
  32893. // -- Usage: `insert<T>(array: Array<T>, idx: number, val: Array<T>|T): Array<T>`
  32894. // --
  32895. // -- ```js
  32896. // -- arr = ['a', 'b', 'c']
  32897. // -- arr2 = insert(arr, 1, 'd')
  32898. // -- // ['a', 'd', 'b', 'c']
  32899. // -- arr2 === arr
  32900. // -- // false
  32901. // -- insert(arr, 1, ['d', 'e'])
  32902. // -- // ['a', 'd', 'e', 'b', 'c']
  32903. // -- ```
  32904. function insert(array, idx, val) {
  32905. return array.slice(0, idx).concat(Array.isArray(val) ? val : [val]).concat(array.slice(idx));
  32906. }
  32907. // -- #### removeAt()
  32908. // -- Returns a new array obtained by removing an item at
  32909. // -- a specified index.
  32910. // --
  32911. // -- Usage: `removeAt<T>(array: Array<T>, idx: number): Array<T>`
  32912. // --
  32913. // -- ```js
  32914. // -- arr = ['a', 'b', 'c']
  32915. // -- arr2 = removeAt(arr, 1)
  32916. // -- // ['a', 'c']
  32917. // -- arr2 === arr
  32918. // -- // false
  32919. // --
  32920. // -- // The same array is returned if there are no changes:
  32921. // -- removeAt(arr, 4) === arr
  32922. // -- // true
  32923. // -- ```
  32924. function removeAt(array, idx) {
  32925. if (idx >= array.length || idx < 0) return array;
  32926. return array.slice(0, idx).concat(array.slice(idx + 1));
  32927. }
  32928. // -- #### replaceAt()
  32929. // -- Returns a new array obtained by replacing an item at
  32930. // -- a specified index. If the provided item is the same as
  32931. // -- (*referentially equal to*) the previous item at that position,
  32932. // -- the original array is returned.
  32933. // --
  32934. // -- Usage: `replaceAt<T>(array: Array<T>, idx: number, newItem: T): Array<T>`
  32935. // --
  32936. // -- ```js
  32937. // -- arr = ['a', 'b', 'c']
  32938. // -- arr2 = replaceAt(arr, 1, 'd')
  32939. // -- // ['a', 'd', 'c']
  32940. // -- arr2 === arr
  32941. // -- // false
  32942. // --
  32943. // -- // The same object is returned if there are no changes:
  32944. // -- replaceAt(arr, 1, 'b') === arr
  32945. // -- // true
  32946. // -- ```
  32947. function replaceAt(array, idx, newItem) {
  32948. if (array[idx] === newItem) return array;
  32949. var len = array.length;
  32950. var result = Array(len);
  32951. for (var i = 0; i < len; i++) {
  32952. result[i] = array[i];
  32953. }
  32954. result[idx] = newItem;
  32955. return result;
  32956. }
  32957. // ===============================================
  32958. // -- ### Collections (objects and arrays)
  32959. // ===============================================
  32960. // -- The following types are used throughout this section
  32961. // -- ```js
  32962. // -- type ArrayOrObject = Array<any>|Object;
  32963. // -- type Key = number|string;
  32964. // -- ```
  32965. // -- #### getIn()
  32966. // -- Returns a value from an object at a given path. Works with
  32967. // -- nested arrays and objects. If the path does not exist, it returns
  32968. // -- `undefined`.
  32969. // --
  32970. // -- Usage: `getIn(obj: ?ArrayOrObject, path: Array<Key>): any`
  32971. // --
  32972. // -- ```js
  32973. // -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] }
  32974. // -- getIn(obj, ['d', 'd1'])
  32975. // -- // 3
  32976. // -- getIn(obj, ['e', 1])
  32977. // -- // 'b'
  32978. // -- ```
  32979. function getIn(obj, path) {
  32980. !Array.isArray(path) && throwStr(process.env.NODE_ENV !== 'production' ? 'A path array should be provided when calling getIn()' : INVALID_ARGS);
  32981. if (obj == null) return undefined;
  32982. var ptr = obj;
  32983. for (var i = 0; i < path.length; i++) {
  32984. var key = path[i];
  32985. ptr = ptr != null ? ptr[key] : undefined;
  32986. if (ptr === undefined) return ptr;
  32987. }
  32988. return ptr;
  32989. }
  32990. // -- #### set()
  32991. // -- Returns a new object with a modified attribute.
  32992. // -- If the provided value is the same as (*referentially equal to*)
  32993. // -- the previous value, the original object is returned.
  32994. // --
  32995. // -- Usage: `set<T>(obj: ?T, key: Key, val: any): T`
  32996. // --
  32997. // -- ```js
  32998. // -- obj = { a: 1, b: 2, c: 3 }
  32999. // -- obj2 = set(obj, 'b', 5)
  33000. // -- // { a: 1, b: 5, c: 3 }
  33001. // -- obj2 === obj
  33002. // -- // false
  33003. // --
  33004. // -- // The same object is returned if there are no changes:
  33005. // -- set(obj, 'b', 2) === obj
  33006. // -- // true
  33007. // -- ```
  33008. function set(obj, key, val) {
  33009. var fallback = typeof key === 'number' ? [] : {};
  33010. var finalObj = obj == null ? fallback : obj;
  33011. if (finalObj[key] === val) return finalObj;
  33012. var obj2 = clone(finalObj);
  33013. obj2[key] = val;
  33014. return obj2;
  33015. }
  33016. // -- #### setIn()
  33017. // -- Returns a new object with a modified **nested** attribute.
  33018. // --
  33019. // -- Notes:
  33020. // --
  33021. // -- * If the provided value is the same as (*referentially equal to*)
  33022. // -- the previous value, the original object is returned.
  33023. // -- * If the path does not exist, it will be created before setting
  33024. // -- the new value.
  33025. // --
  33026. // -- Usage: `setIn<T: ArrayOrObject>(obj: T, path: Array<Key>, val: any): T`
  33027. // --
  33028. // -- ```js
  33029. // -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
  33030. // -- obj2 = setIn(obj, ['d', 'd1'], 4)
  33031. // -- // { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
  33032. // -- obj2 === obj
  33033. // -- // false
  33034. // -- obj2.d === obj.d
  33035. // -- // false
  33036. // -- obj2.e === obj.e
  33037. // -- // true
  33038. // --
  33039. // -- // The same object is returned if there are no changes:
  33040. // -- obj3 = setIn(obj, ['d', 'd1'], 3)
  33041. // -- // { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
  33042. // -- obj3 === obj
  33043. // -- // true
  33044. // -- obj3.d === obj.d
  33045. // -- // true
  33046. // -- obj3.e === obj.e
  33047. // -- // true
  33048. // --
  33049. // -- // ... unknown paths create intermediate keys. Numeric segments are treated as array indices:
  33050. // -- setIn({ a: 3 }, ['unknown', 0, 'path'], 4)
  33051. // -- // { a: 3, unknown: [{ path: 4 }] }
  33052. // -- ```
  33053. function doSetIn(obj, path, val, idx) {
  33054. var newValue = void 0;
  33055. var key = path[idx];
  33056. if (idx === path.length - 1) {
  33057. newValue = val;
  33058. } else {
  33059. var nestedObj = isObject(obj) && isObject(obj[key]) ? obj[key] : typeof path[idx + 1] === 'number' ? [] : {};
  33060. newValue = doSetIn(nestedObj, path, val, idx + 1);
  33061. }
  33062. return set(obj, key, newValue);
  33063. }
  33064. function setIn(obj, path, val) {
  33065. if (!path.length) return val;
  33066. return doSetIn(obj, path, val, 0);
  33067. }
  33068. // -- #### update()
  33069. // -- Returns a new object with a modified attribute,
  33070. // -- calculated via a user-provided callback based on the current value.
  33071. // -- If the calculated value is the same as (*referentially equal to*)
  33072. // -- the previous value, the original object is returned.
  33073. // --
  33074. // -- Usage: `update<T: ArrayOrObject>(obj: T, key: Key,
  33075. // -- fnUpdate: (prevValue: any) => any): T`
  33076. // --
  33077. // -- ```js
  33078. // -- obj = { a: 1, b: 2, c: 3 }
  33079. // -- obj2 = update(obj, 'b', (val) => val + 1)
  33080. // -- // { a: 1, b: 3, c: 3 }
  33081. // -- obj2 === obj
  33082. // -- // false
  33083. // --
  33084. // -- // The same object is returned if there are no changes:
  33085. // -- update(obj, 'b', (val) => val) === obj
  33086. // -- // true
  33087. // -- ```
  33088. function update(obj, key, fnUpdate) {
  33089. var prevVal = obj == null ? undefined : obj[key];
  33090. var nextVal = fnUpdate(prevVal);
  33091. return set(obj, key, nextVal);
  33092. }
  33093. // -- #### updateIn()
  33094. // -- Returns a new object with a modified **nested** attribute,
  33095. // -- calculated via a user-provided callback based on the current value.
  33096. // -- If the calculated value is the same as (*referentially equal to*)
  33097. // -- the previous value, the original object is returned.
  33098. // --
  33099. // -- Usage: `updateIn<T: ArrayOrObject>(obj: T, path: Array<Key>,
  33100. // -- fnUpdate: (prevValue: any) => any): T`
  33101. // --
  33102. // -- ```js
  33103. // -- obj = { a: 1, d: { d1: 3, d2: 4 } }
  33104. // -- obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1)
  33105. // -- // { a: 1, d: { d1: 4, d2: 4 } }
  33106. // -- obj2 === obj
  33107. // -- // false
  33108. // --
  33109. // -- // The same object is returned if there are no changes:
  33110. // -- obj3 = updateIn(obj, ['d', 'd1'], (val) => val)
  33111. // -- // { a: 1, d: { d1: 3, d2: 4 } }
  33112. // -- obj3 === obj
  33113. // -- // true
  33114. // -- ```
  33115. function updateIn(obj, path, fnUpdate) {
  33116. var prevVal = getIn(obj, path);
  33117. var nextVal = fnUpdate(prevVal);
  33118. return setIn(obj, path, nextVal);
  33119. }
  33120. // -- #### merge()
  33121. // -- Returns a new object built as follows: the overlapping keys from the
  33122. // -- second one overwrite the corresponding entries from the first one.
  33123. // -- Similar to `Object.assign()`, but immutable.
  33124. // --
  33125. // -- Usage:
  33126. // --
  33127. // -- * `merge(obj1: Object, obj2: ?Object): Object`
  33128. // -- * `merge(obj1: Object, ...objects: Array<?Object>): Object`
  33129. // --
  33130. // -- The unmodified `obj1` is returned if `obj2` does not *provide something
  33131. // -- new to* `obj1`, i.e. if either of the following
  33132. // -- conditions are true:
  33133. // --
  33134. // -- * `obj2` is `null` or `undefined`
  33135. // -- * `obj2` is an object, but it is empty
  33136. // -- * All attributes of `obj2` are `undefined`
  33137. // -- * All attributes of `obj2` are referentially equal to the
  33138. // -- corresponding attributes of `obj1`
  33139. // --
  33140. // -- Note that `undefined` attributes in `obj2` do not modify the
  33141. // -- corresponding attributes in `obj1`.
  33142. // --
  33143. // -- ```js
  33144. // -- obj1 = { a: 1, b: 2, c: 3 }
  33145. // -- obj2 = { c: 4, d: 5 }
  33146. // -- obj3 = merge(obj1, obj2)
  33147. // -- // { a: 1, b: 2, c: 4, d: 5 }
  33148. // -- obj3 === obj1
  33149. // -- // false
  33150. // --
  33151. // -- // The same object is returned if there are no changes:
  33152. // -- merge(obj1, { c: 3 }) === obj1
  33153. // -- // true
  33154. // -- ```
  33155. function merge(a, b, c, d, e, f) {
  33156. for (var _len2 = arguments.length, rest = Array(_len2 > 6 ? _len2 - 6 : 0), _key2 = 6; _key2 < _len2; _key2++) {
  33157. rest[_key2 - 6] = arguments[_key2];
  33158. }
  33159. return rest.length ? doMerge.call.apply(doMerge, [null, false, false, a, b, c, d, e, f].concat(rest)) : doMerge(false, false, a, b, c, d, e, f);
  33160. }
  33161. // -- #### mergeDeep()
  33162. // -- Returns a new object built as follows: the overlapping keys from the
  33163. // -- second one overwrite the corresponding entries from the first one.
  33164. // -- If both the first and second entries are objects they are merged recursively.
  33165. // -- Similar to `Object.assign()`, but immutable, and deeply merging.
  33166. // --
  33167. // -- Usage:
  33168. // --
  33169. // -- * `mergeDeep(obj1: Object, obj2: ?Object): Object`
  33170. // -- * `mergeDeep(obj1: Object, ...objects: Array<?Object>): Object`
  33171. // --
  33172. // -- The unmodified `obj1` is returned if `obj2` does not *provide something
  33173. // -- new to* `obj1`, i.e. if either of the following
  33174. // -- conditions are true:
  33175. // --
  33176. // -- * `obj2` is `null` or `undefined`
  33177. // -- * `obj2` is an object, but it is empty
  33178. // -- * All attributes of `obj2` are `undefined`
  33179. // -- * All attributes of `obj2` are referentially equal to the
  33180. // -- corresponding attributes of `obj1`
  33181. // --
  33182. // -- Note that `undefined` attributes in `obj2` do not modify the
  33183. // -- corresponding attributes in `obj1`.
  33184. // --
  33185. // -- ```js
  33186. // -- obj1 = { a: 1, b: 2, c: { a: 1 } }
  33187. // -- obj2 = { b: 3, c: { b: 2 } }
  33188. // -- obj3 = mergeDeep(obj1, obj2)
  33189. // -- // { a: 1, b: 3, c: { a: 1, b: 2 } }
  33190. // -- obj3 === obj1
  33191. // -- // false
  33192. // --
  33193. // -- // The same object is returned if there are no changes:
  33194. // -- mergeDeep(obj1, { c: { a: 1 } }) === obj1
  33195. // -- // true
  33196. // -- ```
  33197. function mergeDeep(a, b, c, d, e, f) {
  33198. for (var _len3 = arguments.length, rest = Array(_len3 > 6 ? _len3 - 6 : 0), _key3 = 6; _key3 < _len3; _key3++) {
  33199. rest[_key3 - 6] = arguments[_key3];
  33200. }
  33201. return rest.length ? doMerge.call.apply(doMerge, [null, false, true, a, b, c, d, e, f].concat(rest)) : doMerge(false, true, a, b, c, d, e, f);
  33202. }
  33203. // -- #### mergeIn()
  33204. // -- Similar to `merge()`, but merging the value at a given nested path.
  33205. // -- Note that the returned type is the same as that of the first argument.
  33206. // --
  33207. // -- Usage:
  33208. // --
  33209. // -- * `mergeIn<T: ArrayOrObject>(obj1: T, path: Array<Key>, obj2: ?Object): T`
  33210. // -- * `mergeIn<T: ArrayOrObject>(obj1: T, path: Array<Key>,
  33211. // -- ...objects: Array<?Object>): T`
  33212. // --
  33213. // -- ```js
  33214. // -- obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } }
  33215. // -- obj2 = { d3: 5 }
  33216. // -- obj3 = mergeIn(obj1, ['d', 'b'], obj2)
  33217. // -- // { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } }
  33218. // -- obj3 === obj1
  33219. // -- // false
  33220. // --
  33221. // -- // The same object is returned if there are no changes:
  33222. // -- mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1
  33223. // -- // true
  33224. // -- ```
  33225. function mergeIn(a, path, b, c, d, e, f) {
  33226. var prevVal = getIn(a, path);
  33227. if (prevVal == null) prevVal = {};
  33228. var nextVal = void 0;
  33229. for (var _len4 = arguments.length, rest = Array(_len4 > 7 ? _len4 - 7 : 0), _key4 = 7; _key4 < _len4; _key4++) {
  33230. rest[_key4 - 7] = arguments[_key4];
  33231. }
  33232. if (rest.length) {
  33233. nextVal = doMerge.call.apply(doMerge, [null, false, false, prevVal, b, c, d, e, f].concat(rest));
  33234. } else {
  33235. nextVal = doMerge(false, false, prevVal, b, c, d, e, f);
  33236. }
  33237. return setIn(a, path, nextVal);
  33238. }
  33239. // -- #### omit()
  33240. // -- Returns an object excluding one or several attributes.
  33241. // --
  33242. // -- Usage: `omit(obj: Object, attrs: Array<string>|string): Object`
  33243. //
  33244. // -- ```js
  33245. // -- obj = { a: 1, b: 2, c: 3, d: 4 }
  33246. // -- omit(obj, 'a')
  33247. // -- // { b: 2, c: 3, d: 4 }
  33248. // -- omit(obj, ['b', 'c'])
  33249. // -- // { a: 1, d: 4 }
  33250. // --
  33251. // -- // The same object is returned if there are no changes:
  33252. // -- omit(obj, 'z') === obj1
  33253. // -- // true
  33254. // -- ```
  33255. function omit(obj, attrs) {
  33256. var omitList = Array.isArray(attrs) ? attrs : [attrs];
  33257. var fDoSomething = false;
  33258. for (var i = 0; i < omitList.length; i++) {
  33259. if (hasOwnProperty.call(obj, omitList[i])) {
  33260. fDoSomething = true;
  33261. break;
  33262. }
  33263. }
  33264. if (!fDoSomething) return obj;
  33265. var out = {};
  33266. var keys = getKeysAndSymbols(obj);
  33267. for (var _i = 0; _i < keys.length; _i++) {
  33268. var key = keys[_i];
  33269. if (omitList.indexOf(key) >= 0) continue;
  33270. out[key] = obj[key];
  33271. }
  33272. return out;
  33273. }
  33274. // -- #### addDefaults()
  33275. // -- Returns a new object built as follows: `undefined` keys in the first one
  33276. // -- are filled in with the corresponding values from the second one
  33277. // -- (even if they are `null`).
  33278. // --
  33279. // -- Usage:
  33280. // --
  33281. // -- * `addDefaults(obj: Object, defaults: Object): Object`
  33282. // -- * `addDefaults(obj: Object, ...defaultObjects: Array<?Object>): Object`
  33283. // --
  33284. // -- ```js
  33285. // -- obj1 = { a: 1, b: 2, c: 3 }
  33286. // -- obj2 = { c: 4, d: 5, e: null }
  33287. // -- obj3 = addDefaults(obj1, obj2)
  33288. // -- // { a: 1, b: 2, c: 3, d: 5, e: null }
  33289. // -- obj3 === obj1
  33290. // -- // false
  33291. // --
  33292. // -- // The same object is returned if there are no changes:
  33293. // -- addDefaults(obj1, { c: 4 }) === obj1
  33294. // -- // true
  33295. // -- ```
  33296. function addDefaults(a, b, c, d, e, f) {
  33297. for (var _len5 = arguments.length, rest = Array(_len5 > 6 ? _len5 - 6 : 0), _key5 = 6; _key5 < _len5; _key5++) {
  33298. rest[_key5 - 6] = arguments[_key5];
  33299. }
  33300. return rest.length ? doMerge.call.apply(doMerge, [null, true, false, a, b, c, d, e, f].concat(rest)) : doMerge(true, false, a, b, c, d, e, f);
  33301. }
  33302. // ===============================================
  33303. // ### Public API
  33304. // ===============================================
  33305. var timm = {
  33306. clone: clone,
  33307. addLast: addLast,
  33308. addFirst: addFirst,
  33309. removeLast: removeLast,
  33310. removeFirst: removeFirst,
  33311. insert: insert,
  33312. removeAt: removeAt,
  33313. replaceAt: replaceAt,
  33314. getIn: getIn,
  33315. // eslint-disable-next-line object-shorthand
  33316. set: set, // so that flow doesn't complain
  33317. setIn: setIn,
  33318. update: update,
  33319. updateIn: updateIn,
  33320. merge: merge,
  33321. mergeDeep: mergeDeep,
  33322. mergeIn: mergeIn,
  33323. omit: omit,
  33324. addDefaults: addDefaults
  33325. };
  33326. exports.default = timm;
  33327. }).call(this,require('_process'))
  33328. },{"_process":312}],357:[function(require,module,exports){
  33329. // TinyColor v1.4.1
  33330. // https://github.com/bgrins/TinyColor
  33331. // Brian Grinstead, MIT License
  33332. (function(Math) {
  33333. var trimLeft = /^\s+/,
  33334. trimRight = /\s+$/,
  33335. tinyCounter = 0,
  33336. mathRound = Math.round,
  33337. mathMin = Math.min,
  33338. mathMax = Math.max,
  33339. mathRandom = Math.random;
  33340. function tinycolor (color, opts) {
  33341. color = (color) ? color : '';
  33342. opts = opts || { };
  33343. // If input is already a tinycolor, return itself
  33344. if (color instanceof tinycolor) {
  33345. return color;
  33346. }
  33347. // If we are called as a function, call using new instead
  33348. if (!(this instanceof tinycolor)) {
  33349. return new tinycolor(color, opts);
  33350. }
  33351. var rgb = inputToRGB(color);
  33352. this._originalInput = color,
  33353. this._r = rgb.r,
  33354. this._g = rgb.g,
  33355. this._b = rgb.b,
  33356. this._a = rgb.a,
  33357. this._roundA = mathRound(100*this._a) / 100,
  33358. this._format = opts.format || rgb.format;
  33359. this._gradientType = opts.gradientType;
  33360. // Don't let the range of [0,255] come back in [0,1].
  33361. // Potentially lose a little bit of precision here, but will fix issues where
  33362. // .5 gets interpreted as half of the total, instead of half of 1
  33363. // If it was supposed to be 128, this was already taken care of by `inputToRgb`
  33364. if (this._r < 1) { this._r = mathRound(this._r); }
  33365. if (this._g < 1) { this._g = mathRound(this._g); }
  33366. if (this._b < 1) { this._b = mathRound(this._b); }
  33367. this._ok = rgb.ok;
  33368. this._tc_id = tinyCounter++;
  33369. }
  33370. tinycolor.prototype = {
  33371. isDark: function() {
  33372. return this.getBrightness() < 128;
  33373. },
  33374. isLight: function() {
  33375. return !this.isDark();
  33376. },
  33377. isValid: function() {
  33378. return this._ok;
  33379. },
  33380. getOriginalInput: function() {
  33381. return this._originalInput;
  33382. },
  33383. getFormat: function() {
  33384. return this._format;
  33385. },
  33386. getAlpha: function() {
  33387. return this._a;
  33388. },
  33389. getBrightness: function() {
  33390. //http://www.w3.org/TR/AERT#color-contrast
  33391. var rgb = this.toRgb();
  33392. return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
  33393. },
  33394. getLuminance: function() {
  33395. //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  33396. var rgb = this.toRgb();
  33397. var RsRGB, GsRGB, BsRGB, R, G, B;
  33398. RsRGB = rgb.r/255;
  33399. GsRGB = rgb.g/255;
  33400. BsRGB = rgb.b/255;
  33401. if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
  33402. if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
  33403. if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
  33404. return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
  33405. },
  33406. setAlpha: function(value) {
  33407. this._a = boundAlpha(value);
  33408. this._roundA = mathRound(100*this._a) / 100;
  33409. return this;
  33410. },
  33411. toHsv: function() {
  33412. var hsv = rgbToHsv(this._r, this._g, this._b);
  33413. return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
  33414. },
  33415. toHsvString: function() {
  33416. var hsv = rgbToHsv(this._r, this._g, this._b);
  33417. var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
  33418. return (this._a == 1) ?
  33419. "hsv(" + h + ", " + s + "%, " + v + "%)" :
  33420. "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
  33421. },
  33422. toHsl: function() {
  33423. var hsl = rgbToHsl(this._r, this._g, this._b);
  33424. return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
  33425. },
  33426. toHslString: function() {
  33427. var hsl = rgbToHsl(this._r, this._g, this._b);
  33428. var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
  33429. return (this._a == 1) ?
  33430. "hsl(" + h + ", " + s + "%, " + l + "%)" :
  33431. "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
  33432. },
  33433. toHex: function(allow3Char) {
  33434. return rgbToHex(this._r, this._g, this._b, allow3Char);
  33435. },
  33436. toHexString: function(allow3Char) {
  33437. return '#' + this.toHex(allow3Char);
  33438. },
  33439. toHex8: function(allow4Char) {
  33440. return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
  33441. },
  33442. toHex8String: function(allow4Char) {
  33443. return '#' + this.toHex8(allow4Char);
  33444. },
  33445. toRgb: function() {
  33446. return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
  33447. },
  33448. toRgbString: function() {
  33449. return (this._a == 1) ?
  33450. "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
  33451. "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
  33452. },
  33453. toPercentageRgb: function() {
  33454. return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
  33455. },
  33456. toPercentageRgbString: function() {
  33457. return (this._a == 1) ?
  33458. "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
  33459. "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
  33460. },
  33461. toName: function() {
  33462. if (this._a === 0) {
  33463. return "transparent";
  33464. }
  33465. if (this._a < 1) {
  33466. return false;
  33467. }
  33468. return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
  33469. },
  33470. toFilter: function(secondColor) {
  33471. var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
  33472. var secondHex8String = hex8String;
  33473. var gradientType = this._gradientType ? "GradientType = 1, " : "";
  33474. if (secondColor) {
  33475. var s = tinycolor(secondColor);
  33476. secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
  33477. }
  33478. return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
  33479. },
  33480. toString: function(format) {
  33481. var formatSet = !!format;
  33482. format = format || this._format;
  33483. var formattedString = false;
  33484. var hasAlpha = this._a < 1 && this._a >= 0;
  33485. var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
  33486. if (needsAlphaFormat) {
  33487. // Special case for "transparent", all other non-alpha formats
  33488. // will return rgba when there is transparency.
  33489. if (format === "name" && this._a === 0) {
  33490. return this.toName();
  33491. }
  33492. return this.toRgbString();
  33493. }
  33494. if (format === "rgb") {
  33495. formattedString = this.toRgbString();
  33496. }
  33497. if (format === "prgb") {
  33498. formattedString = this.toPercentageRgbString();
  33499. }
  33500. if (format === "hex" || format === "hex6") {
  33501. formattedString = this.toHexString();
  33502. }
  33503. if (format === "hex3") {
  33504. formattedString = this.toHexString(true);
  33505. }
  33506. if (format === "hex4") {
  33507. formattedString = this.toHex8String(true);
  33508. }
  33509. if (format === "hex8") {
  33510. formattedString = this.toHex8String();
  33511. }
  33512. if (format === "name") {
  33513. formattedString = this.toName();
  33514. }
  33515. if (format === "hsl") {
  33516. formattedString = this.toHslString();
  33517. }
  33518. if (format === "hsv") {
  33519. formattedString = this.toHsvString();
  33520. }
  33521. return formattedString || this.toHexString();
  33522. },
  33523. clone: function() {
  33524. return tinycolor(this.toString());
  33525. },
  33526. _applyModification: function(fn, args) {
  33527. var color = fn.apply(null, [this].concat([].slice.call(args)));
  33528. this._r = color._r;
  33529. this._g = color._g;
  33530. this._b = color._b;
  33531. this.setAlpha(color._a);
  33532. return this;
  33533. },
  33534. lighten: function() {
  33535. return this._applyModification(lighten, arguments);
  33536. },
  33537. brighten: function() {
  33538. return this._applyModification(brighten, arguments);
  33539. },
  33540. darken: function() {
  33541. return this._applyModification(darken, arguments);
  33542. },
  33543. desaturate: function() {
  33544. return this._applyModification(desaturate, arguments);
  33545. },
  33546. saturate: function() {
  33547. return this._applyModification(saturate, arguments);
  33548. },
  33549. greyscale: function() {
  33550. return this._applyModification(greyscale, arguments);
  33551. },
  33552. spin: function() {
  33553. return this._applyModification(spin, arguments);
  33554. },
  33555. _applyCombination: function(fn, args) {
  33556. return fn.apply(null, [this].concat([].slice.call(args)));
  33557. },
  33558. analogous: function() {
  33559. return this._applyCombination(analogous, arguments);
  33560. },
  33561. complement: function() {
  33562. return this._applyCombination(complement, arguments);
  33563. },
  33564. monochromatic: function() {
  33565. return this._applyCombination(monochromatic, arguments);
  33566. },
  33567. splitcomplement: function() {
  33568. return this._applyCombination(splitcomplement, arguments);
  33569. },
  33570. triad: function() {
  33571. return this._applyCombination(triad, arguments);
  33572. },
  33573. tetrad: function() {
  33574. return this._applyCombination(tetrad, arguments);
  33575. }
  33576. };
  33577. // If input is an object, force 1 into "1.0" to handle ratios properly
  33578. // String input requires "1.0" as input, so 1 will be treated as 1
  33579. tinycolor.fromRatio = function(color, opts) {
  33580. if (typeof color == "object") {
  33581. var newColor = {};
  33582. for (var i in color) {
  33583. if (color.hasOwnProperty(i)) {
  33584. if (i === "a") {
  33585. newColor[i] = color[i];
  33586. }
  33587. else {
  33588. newColor[i] = convertToPercentage(color[i]);
  33589. }
  33590. }
  33591. }
  33592. color = newColor;
  33593. }
  33594. return tinycolor(color, opts);
  33595. };
  33596. // Given a string or object, convert that input to RGB
  33597. // Possible string inputs:
  33598. //
  33599. // "red"
  33600. // "#f00" or "f00"
  33601. // "#ff0000" or "ff0000"
  33602. // "#ff000000" or "ff000000"
  33603. // "rgb 255 0 0" or "rgb (255, 0, 0)"
  33604. // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
  33605. // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
  33606. // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
  33607. // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
  33608. // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
  33609. // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
  33610. //
  33611. function inputToRGB(color) {
  33612. var rgb = { r: 0, g: 0, b: 0 };
  33613. var a = 1;
  33614. var s = null;
  33615. var v = null;
  33616. var l = null;
  33617. var ok = false;
  33618. var format = false;
  33619. if (typeof color == "string") {
  33620. color = stringInputToObject(color);
  33621. }
  33622. if (typeof color == "object") {
  33623. if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
  33624. rgb = rgbToRgb(color.r, color.g, color.b);
  33625. ok = true;
  33626. format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
  33627. }
  33628. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
  33629. s = convertToPercentage(color.s);
  33630. v = convertToPercentage(color.v);
  33631. rgb = hsvToRgb(color.h, s, v);
  33632. ok = true;
  33633. format = "hsv";
  33634. }
  33635. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
  33636. s = convertToPercentage(color.s);
  33637. l = convertToPercentage(color.l);
  33638. rgb = hslToRgb(color.h, s, l);
  33639. ok = true;
  33640. format = "hsl";
  33641. }
  33642. if (color.hasOwnProperty("a")) {
  33643. a = color.a;
  33644. }
  33645. }
  33646. a = boundAlpha(a);
  33647. return {
  33648. ok: ok,
  33649. format: color.format || format,
  33650. r: mathMin(255, mathMax(rgb.r, 0)),
  33651. g: mathMin(255, mathMax(rgb.g, 0)),
  33652. b: mathMin(255, mathMax(rgb.b, 0)),
  33653. a: a
  33654. };
  33655. }
  33656. // Conversion Functions
  33657. // --------------------
  33658. // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
  33659. // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
  33660. // `rgbToRgb`
  33661. // Handle bounds / percentage checking to conform to CSS color spec
  33662. // <http://www.w3.org/TR/css3-color/>
  33663. // *Assumes:* r, g, b in [0, 255] or [0, 1]
  33664. // *Returns:* { r, g, b } in [0, 255]
  33665. function rgbToRgb(r, g, b){
  33666. return {
  33667. r: bound01(r, 255) * 255,
  33668. g: bound01(g, 255) * 255,
  33669. b: bound01(b, 255) * 255
  33670. };
  33671. }
  33672. // `rgbToHsl`
  33673. // Converts an RGB color value to HSL.
  33674. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
  33675. // *Returns:* { h, s, l } in [0,1]
  33676. function rgbToHsl(r, g, b) {
  33677. r = bound01(r, 255);
  33678. g = bound01(g, 255);
  33679. b = bound01(b, 255);
  33680. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  33681. var h, s, l = (max + min) / 2;
  33682. if(max == min) {
  33683. h = s = 0; // achromatic
  33684. }
  33685. else {
  33686. var d = max - min;
  33687. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  33688. switch(max) {
  33689. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  33690. case g: h = (b - r) / d + 2; break;
  33691. case b: h = (r - g) / d + 4; break;
  33692. }
  33693. h /= 6;
  33694. }
  33695. return { h: h, s: s, l: l };
  33696. }
  33697. // `hslToRgb`
  33698. // Converts an HSL color value to RGB.
  33699. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
  33700. // *Returns:* { r, g, b } in the set [0, 255]
  33701. function hslToRgb(h, s, l) {
  33702. var r, g, b;
  33703. h = bound01(h, 360);
  33704. s = bound01(s, 100);
  33705. l = bound01(l, 100);
  33706. function hue2rgb(p, q, t) {
  33707. if(t < 0) t += 1;
  33708. if(t > 1) t -= 1;
  33709. if(t < 1/6) return p + (q - p) * 6 * t;
  33710. if(t < 1/2) return q;
  33711. if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
  33712. return p;
  33713. }
  33714. if(s === 0) {
  33715. r = g = b = l; // achromatic
  33716. }
  33717. else {
  33718. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  33719. var p = 2 * l - q;
  33720. r = hue2rgb(p, q, h + 1/3);
  33721. g = hue2rgb(p, q, h);
  33722. b = hue2rgb(p, q, h - 1/3);
  33723. }
  33724. return { r: r * 255, g: g * 255, b: b * 255 };
  33725. }
  33726. // `rgbToHsv`
  33727. // Converts an RGB color value to HSV
  33728. // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
  33729. // *Returns:* { h, s, v } in [0,1]
  33730. function rgbToHsv(r, g, b) {
  33731. r = bound01(r, 255);
  33732. g = bound01(g, 255);
  33733. b = bound01(b, 255);
  33734. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  33735. var h, s, v = max;
  33736. var d = max - min;
  33737. s = max === 0 ? 0 : d / max;
  33738. if(max == min) {
  33739. h = 0; // achromatic
  33740. }
  33741. else {
  33742. switch(max) {
  33743. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  33744. case g: h = (b - r) / d + 2; break;
  33745. case b: h = (r - g) / d + 4; break;
  33746. }
  33747. h /= 6;
  33748. }
  33749. return { h: h, s: s, v: v };
  33750. }
  33751. // `hsvToRgb`
  33752. // Converts an HSV color value to RGB.
  33753. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
  33754. // *Returns:* { r, g, b } in the set [0, 255]
  33755. function hsvToRgb(h, s, v) {
  33756. h = bound01(h, 360) * 6;
  33757. s = bound01(s, 100);
  33758. v = bound01(v, 100);
  33759. var i = Math.floor(h),
  33760. f = h - i,
  33761. p = v * (1 - s),
  33762. q = v * (1 - f * s),
  33763. t = v * (1 - (1 - f) * s),
  33764. mod = i % 6,
  33765. r = [v, q, p, p, t, v][mod],
  33766. g = [t, v, v, q, p, p][mod],
  33767. b = [p, p, t, v, v, q][mod];
  33768. return { r: r * 255, g: g * 255, b: b * 255 };
  33769. }
  33770. // `rgbToHex`
  33771. // Converts an RGB color to hex
  33772. // Assumes r, g, and b are contained in the set [0, 255]
  33773. // Returns a 3 or 6 character hex
  33774. function rgbToHex(r, g, b, allow3Char) {
  33775. var hex = [
  33776. pad2(mathRound(r).toString(16)),
  33777. pad2(mathRound(g).toString(16)),
  33778. pad2(mathRound(b).toString(16))
  33779. ];
  33780. // Return a 3 character hex if possible
  33781. if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
  33782. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
  33783. }
  33784. return hex.join("");
  33785. }
  33786. // `rgbaToHex`
  33787. // Converts an RGBA color plus alpha transparency to hex
  33788. // Assumes r, g, b are contained in the set [0, 255] and
  33789. // a in [0, 1]. Returns a 4 or 8 character rgba hex
  33790. function rgbaToHex(r, g, b, a, allow4Char) {
  33791. var hex = [
  33792. pad2(mathRound(r).toString(16)),
  33793. pad2(mathRound(g).toString(16)),
  33794. pad2(mathRound(b).toString(16)),
  33795. pad2(convertDecimalToHex(a))
  33796. ];
  33797. // Return a 4 character hex if possible
  33798. if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
  33799. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
  33800. }
  33801. return hex.join("");
  33802. }
  33803. // `rgbaToArgbHex`
  33804. // Converts an RGBA color to an ARGB Hex8 string
  33805. // Rarely used, but required for "toFilter()"
  33806. function rgbaToArgbHex(r, g, b, a) {
  33807. var hex = [
  33808. pad2(convertDecimalToHex(a)),
  33809. pad2(mathRound(r).toString(16)),
  33810. pad2(mathRound(g).toString(16)),
  33811. pad2(mathRound(b).toString(16))
  33812. ];
  33813. return hex.join("");
  33814. }
  33815. // `equals`
  33816. // Can be called with any tinycolor input
  33817. tinycolor.equals = function (color1, color2) {
  33818. if (!color1 || !color2) { return false; }
  33819. return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
  33820. };
  33821. tinycolor.random = function() {
  33822. return tinycolor.fromRatio({
  33823. r: mathRandom(),
  33824. g: mathRandom(),
  33825. b: mathRandom()
  33826. });
  33827. };
  33828. // Modification Functions
  33829. // ----------------------
  33830. // Thanks to less.js for some of the basics here
  33831. // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
  33832. function desaturate(color, amount) {
  33833. amount = (amount === 0) ? 0 : (amount || 10);
  33834. var hsl = tinycolor(color).toHsl();
  33835. hsl.s -= amount / 100;
  33836. hsl.s = clamp01(hsl.s);
  33837. return tinycolor(hsl);
  33838. }
  33839. function saturate(color, amount) {
  33840. amount = (amount === 0) ? 0 : (amount || 10);
  33841. var hsl = tinycolor(color).toHsl();
  33842. hsl.s += amount / 100;
  33843. hsl.s = clamp01(hsl.s);
  33844. return tinycolor(hsl);
  33845. }
  33846. function greyscale(color) {
  33847. return tinycolor(color).desaturate(100);
  33848. }
  33849. function lighten (color, amount) {
  33850. amount = (amount === 0) ? 0 : (amount || 10);
  33851. var hsl = tinycolor(color).toHsl();
  33852. hsl.l += amount / 100;
  33853. hsl.l = clamp01(hsl.l);
  33854. return tinycolor(hsl);
  33855. }
  33856. function brighten(color, amount) {
  33857. amount = (amount === 0) ? 0 : (amount || 10);
  33858. var rgb = tinycolor(color).toRgb();
  33859. rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
  33860. rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
  33861. rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
  33862. return tinycolor(rgb);
  33863. }
  33864. function darken (color, amount) {
  33865. amount = (amount === 0) ? 0 : (amount || 10);
  33866. var hsl = tinycolor(color).toHsl();
  33867. hsl.l -= amount / 100;
  33868. hsl.l = clamp01(hsl.l);
  33869. return tinycolor(hsl);
  33870. }
  33871. // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
  33872. // Values outside of this range will be wrapped into this range.
  33873. function spin(color, amount) {
  33874. var hsl = tinycolor(color).toHsl();
  33875. var hue = (hsl.h + amount) % 360;
  33876. hsl.h = hue < 0 ? 360 + hue : hue;
  33877. return tinycolor(hsl);
  33878. }
  33879. // Combination Functions
  33880. // ---------------------
  33881. // Thanks to jQuery xColor for some of the ideas behind these
  33882. // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
  33883. function complement(color) {
  33884. var hsl = tinycolor(color).toHsl();
  33885. hsl.h = (hsl.h + 180) % 360;
  33886. return tinycolor(hsl);
  33887. }
  33888. function triad(color) {
  33889. var hsl = tinycolor(color).toHsl();
  33890. var h = hsl.h;
  33891. return [
  33892. tinycolor(color),
  33893. tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
  33894. tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
  33895. ];
  33896. }
  33897. function tetrad(color) {
  33898. var hsl = tinycolor(color).toHsl();
  33899. var h = hsl.h;
  33900. return [
  33901. tinycolor(color),
  33902. tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
  33903. tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
  33904. tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
  33905. ];
  33906. }
  33907. function splitcomplement(color) {
  33908. var hsl = tinycolor(color).toHsl();
  33909. var h = hsl.h;
  33910. return [
  33911. tinycolor(color),
  33912. tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
  33913. tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
  33914. ];
  33915. }
  33916. function analogous(color, results, slices) {
  33917. results = results || 6;
  33918. slices = slices || 30;
  33919. var hsl = tinycolor(color).toHsl();
  33920. var part = 360 / slices;
  33921. var ret = [tinycolor(color)];
  33922. for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
  33923. hsl.h = (hsl.h + part) % 360;
  33924. ret.push(tinycolor(hsl));
  33925. }
  33926. return ret;
  33927. }
  33928. function monochromatic(color, results) {
  33929. results = results || 6;
  33930. var hsv = tinycolor(color).toHsv();
  33931. var h = hsv.h, s = hsv.s, v = hsv.v;
  33932. var ret = [];
  33933. var modification = 1 / results;
  33934. while (results--) {
  33935. ret.push(tinycolor({ h: h, s: s, v: v}));
  33936. v = (v + modification) % 1;
  33937. }
  33938. return ret;
  33939. }
  33940. // Utility Functions
  33941. // ---------------------
  33942. tinycolor.mix = function(color1, color2, amount) {
  33943. amount = (amount === 0) ? 0 : (amount || 50);
  33944. var rgb1 = tinycolor(color1).toRgb();
  33945. var rgb2 = tinycolor(color2).toRgb();
  33946. var p = amount / 100;
  33947. var rgba = {
  33948. r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
  33949. g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
  33950. b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
  33951. a: ((rgb2.a - rgb1.a) * p) + rgb1.a
  33952. };
  33953. return tinycolor(rgba);
  33954. };
  33955. // Readability Functions
  33956. // ---------------------
  33957. // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
  33958. // `contrast`
  33959. // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
  33960. tinycolor.readability = function(color1, color2) {
  33961. var c1 = tinycolor(color1);
  33962. var c2 = tinycolor(color2);
  33963. return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
  33964. };
  33965. // `isReadable`
  33966. // Ensure that foreground and background color combinations meet WCAG2 guidelines.
  33967. // The third argument is an optional Object.
  33968. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
  33969. // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
  33970. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
  33971. // *Example*
  33972. // tinycolor.isReadable("#000", "#111") => false
  33973. // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
  33974. tinycolor.isReadable = function(color1, color2, wcag2) {
  33975. var readability = tinycolor.readability(color1, color2);
  33976. var wcag2Parms, out;
  33977. out = false;
  33978. wcag2Parms = validateWCAG2Parms(wcag2);
  33979. switch (wcag2Parms.level + wcag2Parms.size) {
  33980. case "AAsmall":
  33981. case "AAAlarge":
  33982. out = readability >= 4.5;
  33983. break;
  33984. case "AAlarge":
  33985. out = readability >= 3;
  33986. break;
  33987. case "AAAsmall":
  33988. out = readability >= 7;
  33989. break;
  33990. }
  33991. return out;
  33992. };
  33993. // `mostReadable`
  33994. // Given a base color and a list of possible foreground or background
  33995. // colors for that base, returns the most readable color.
  33996. // Optionally returns Black or White if the most readable color is unreadable.
  33997. // *Example*
  33998. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
  33999. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff"
  34000. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
  34001. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
  34002. tinycolor.mostReadable = function(baseColor, colorList, args) {
  34003. var bestColor = null;
  34004. var bestScore = 0;
  34005. var readability;
  34006. var includeFallbackColors, level, size ;
  34007. args = args || {};
  34008. includeFallbackColors = args.includeFallbackColors ;
  34009. level = args.level;
  34010. size = args.size;
  34011. for (var i= 0; i < colorList.length ; i++) {
  34012. readability = tinycolor.readability(baseColor, colorList[i]);
  34013. if (readability > bestScore) {
  34014. bestScore = readability;
  34015. bestColor = tinycolor(colorList[i]);
  34016. }
  34017. }
  34018. if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
  34019. return bestColor;
  34020. }
  34021. else {
  34022. args.includeFallbackColors=false;
  34023. return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
  34024. }
  34025. };
  34026. // Big List of Colors
  34027. // ------------------
  34028. // <http://www.w3.org/TR/css3-color/#svg-color>
  34029. var names = tinycolor.names = {
  34030. aliceblue: "f0f8ff",
  34031. antiquewhite: "faebd7",
  34032. aqua: "0ff",
  34033. aquamarine: "7fffd4",
  34034. azure: "f0ffff",
  34035. beige: "f5f5dc",
  34036. bisque: "ffe4c4",
  34037. black: "000",
  34038. blanchedalmond: "ffebcd",
  34039. blue: "00f",
  34040. blueviolet: "8a2be2",
  34041. brown: "a52a2a",
  34042. burlywood: "deb887",
  34043. burntsienna: "ea7e5d",
  34044. cadetblue: "5f9ea0",
  34045. chartreuse: "7fff00",
  34046. chocolate: "d2691e",
  34047. coral: "ff7f50",
  34048. cornflowerblue: "6495ed",
  34049. cornsilk: "fff8dc",
  34050. crimson: "dc143c",
  34051. cyan: "0ff",
  34052. darkblue: "00008b",
  34053. darkcyan: "008b8b",
  34054. darkgoldenrod: "b8860b",
  34055. darkgray: "a9a9a9",
  34056. darkgreen: "006400",
  34057. darkgrey: "a9a9a9",
  34058. darkkhaki: "bdb76b",
  34059. darkmagenta: "8b008b",
  34060. darkolivegreen: "556b2f",
  34061. darkorange: "ff8c00",
  34062. darkorchid: "9932cc",
  34063. darkred: "8b0000",
  34064. darksalmon: "e9967a",
  34065. darkseagreen: "8fbc8f",
  34066. darkslateblue: "483d8b",
  34067. darkslategray: "2f4f4f",
  34068. darkslategrey: "2f4f4f",
  34069. darkturquoise: "00ced1",
  34070. darkviolet: "9400d3",
  34071. deeppink: "ff1493",
  34072. deepskyblue: "00bfff",
  34073. dimgray: "696969",
  34074. dimgrey: "696969",
  34075. dodgerblue: "1e90ff",
  34076. firebrick: "b22222",
  34077. floralwhite: "fffaf0",
  34078. forestgreen: "228b22",
  34079. fuchsia: "f0f",
  34080. gainsboro: "dcdcdc",
  34081. ghostwhite: "f8f8ff",
  34082. gold: "ffd700",
  34083. goldenrod: "daa520",
  34084. gray: "808080",
  34085. green: "008000",
  34086. greenyellow: "adff2f",
  34087. grey: "808080",
  34088. honeydew: "f0fff0",
  34089. hotpink: "ff69b4",
  34090. indianred: "cd5c5c",
  34091. indigo: "4b0082",
  34092. ivory: "fffff0",
  34093. khaki: "f0e68c",
  34094. lavender: "e6e6fa",
  34095. lavenderblush: "fff0f5",
  34096. lawngreen: "7cfc00",
  34097. lemonchiffon: "fffacd",
  34098. lightblue: "add8e6",
  34099. lightcoral: "f08080",
  34100. lightcyan: "e0ffff",
  34101. lightgoldenrodyellow: "fafad2",
  34102. lightgray: "d3d3d3",
  34103. lightgreen: "90ee90",
  34104. lightgrey: "d3d3d3",
  34105. lightpink: "ffb6c1",
  34106. lightsalmon: "ffa07a",
  34107. lightseagreen: "20b2aa",
  34108. lightskyblue: "87cefa",
  34109. lightslategray: "789",
  34110. lightslategrey: "789",
  34111. lightsteelblue: "b0c4de",
  34112. lightyellow: "ffffe0",
  34113. lime: "0f0",
  34114. limegreen: "32cd32",
  34115. linen: "faf0e6",
  34116. magenta: "f0f",
  34117. maroon: "800000",
  34118. mediumaquamarine: "66cdaa",
  34119. mediumblue: "0000cd",
  34120. mediumorchid: "ba55d3",
  34121. mediumpurple: "9370db",
  34122. mediumseagreen: "3cb371",
  34123. mediumslateblue: "7b68ee",
  34124. mediumspringgreen: "00fa9a",
  34125. mediumturquoise: "48d1cc",
  34126. mediumvioletred: "c71585",
  34127. midnightblue: "191970",
  34128. mintcream: "f5fffa",
  34129. mistyrose: "ffe4e1",
  34130. moccasin: "ffe4b5",
  34131. navajowhite: "ffdead",
  34132. navy: "000080",
  34133. oldlace: "fdf5e6",
  34134. olive: "808000",
  34135. olivedrab: "6b8e23",
  34136. orange: "ffa500",
  34137. orangered: "ff4500",
  34138. orchid: "da70d6",
  34139. palegoldenrod: "eee8aa",
  34140. palegreen: "98fb98",
  34141. paleturquoise: "afeeee",
  34142. palevioletred: "db7093",
  34143. papayawhip: "ffefd5",
  34144. peachpuff: "ffdab9",
  34145. peru: "cd853f",
  34146. pink: "ffc0cb",
  34147. plum: "dda0dd",
  34148. powderblue: "b0e0e6",
  34149. purple: "800080",
  34150. rebeccapurple: "663399",
  34151. red: "f00",
  34152. rosybrown: "bc8f8f",
  34153. royalblue: "4169e1",
  34154. saddlebrown: "8b4513",
  34155. salmon: "fa8072",
  34156. sandybrown: "f4a460",
  34157. seagreen: "2e8b57",
  34158. seashell: "fff5ee",
  34159. sienna: "a0522d",
  34160. silver: "c0c0c0",
  34161. skyblue: "87ceeb",
  34162. slateblue: "6a5acd",
  34163. slategray: "708090",
  34164. slategrey: "708090",
  34165. snow: "fffafa",
  34166. springgreen: "00ff7f",
  34167. steelblue: "4682b4",
  34168. tan: "d2b48c",
  34169. teal: "008080",
  34170. thistle: "d8bfd8",
  34171. tomato: "ff6347",
  34172. turquoise: "40e0d0",
  34173. violet: "ee82ee",
  34174. wheat: "f5deb3",
  34175. white: "fff",
  34176. whitesmoke: "f5f5f5",
  34177. yellow: "ff0",
  34178. yellowgreen: "9acd32"
  34179. };
  34180. // Make it easy to access colors via `hexNames[hex]`
  34181. var hexNames = tinycolor.hexNames = flip(names);
  34182. // Utilities
  34183. // ---------
  34184. // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
  34185. function flip(o) {
  34186. var flipped = { };
  34187. for (var i in o) {
  34188. if (o.hasOwnProperty(i)) {
  34189. flipped[o[i]] = i;
  34190. }
  34191. }
  34192. return flipped;
  34193. }
  34194. // Return a valid alpha value [0,1] with all invalid values being set to 1
  34195. function boundAlpha(a) {
  34196. a = parseFloat(a);
  34197. if (isNaN(a) || a < 0 || a > 1) {
  34198. a = 1;
  34199. }
  34200. return a;
  34201. }
  34202. // Take input from [0, n] and return it as [0, 1]
  34203. function bound01(n, max) {
  34204. if (isOnePointZero(n)) { n = "100%"; }
  34205. var processPercent = isPercentage(n);
  34206. n = mathMin(max, mathMax(0, parseFloat(n)));
  34207. // Automatically convert percentage into number
  34208. if (processPercent) {
  34209. n = parseInt(n * max, 10) / 100;
  34210. }
  34211. // Handle floating point rounding errors
  34212. if ((Math.abs(n - max) < 0.000001)) {
  34213. return 1;
  34214. }
  34215. // Convert into [0, 1] range if it isn't already
  34216. return (n % max) / parseFloat(max);
  34217. }
  34218. // Force a number between 0 and 1
  34219. function clamp01(val) {
  34220. return mathMin(1, mathMax(0, val));
  34221. }
  34222. // Parse a base-16 hex value into a base-10 integer
  34223. function parseIntFromHex(val) {
  34224. return parseInt(val, 16);
  34225. }
  34226. // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
  34227. // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
  34228. function isOnePointZero(n) {
  34229. return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
  34230. }
  34231. // Check to see if string passed in is a percentage
  34232. function isPercentage(n) {
  34233. return typeof n === "string" && n.indexOf('%') != -1;
  34234. }
  34235. // Force a hex value to have 2 characters
  34236. function pad2(c) {
  34237. return c.length == 1 ? '0' + c : '' + c;
  34238. }
  34239. // Replace a decimal with it's percentage value
  34240. function convertToPercentage(n) {
  34241. if (n <= 1) {
  34242. n = (n * 100) + "%";
  34243. }
  34244. return n;
  34245. }
  34246. // Converts a decimal to a hex value
  34247. function convertDecimalToHex(d) {
  34248. return Math.round(parseFloat(d) * 255).toString(16);
  34249. }
  34250. // Converts a hex value to a decimal
  34251. function convertHexToDecimal(h) {
  34252. return (parseIntFromHex(h) / 255);
  34253. }
  34254. var matchers = (function() {
  34255. // <http://www.w3.org/TR/css3-values/#integers>
  34256. var CSS_INTEGER = "[-\\+]?\\d+%?";
  34257. // <http://www.w3.org/TR/css3-values/#number-value>
  34258. var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
  34259. // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
  34260. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
  34261. // Actual matching.
  34262. // Parentheses and commas are optional, but not required.
  34263. // Whitespace can take the place of commas or opening paren
  34264. var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  34265. var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  34266. return {
  34267. CSS_UNIT: new RegExp(CSS_UNIT),
  34268. rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
  34269. rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
  34270. hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
  34271. hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
  34272. hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
  34273. hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
  34274. hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  34275. hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
  34276. hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  34277. hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
  34278. };
  34279. })();
  34280. // `isValidCSSUnit`
  34281. // Take in a single string / number and check to see if it looks like a CSS unit
  34282. // (see `matchers` above for definition).
  34283. function isValidCSSUnit(color) {
  34284. return !!matchers.CSS_UNIT.exec(color);
  34285. }
  34286. // `stringInputToObject`
  34287. // Permissive string parsing. Take in a number of formats, and output an object
  34288. // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
  34289. function stringInputToObject(color) {
  34290. color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
  34291. var named = false;
  34292. if (names[color]) {
  34293. color = names[color];
  34294. named = true;
  34295. }
  34296. else if (color == 'transparent') {
  34297. return { r: 0, g: 0, b: 0, a: 0, format: "name" };
  34298. }
  34299. // Try to match string input using regular expressions.
  34300. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
  34301. // Just return an object and let the conversion functions handle that.
  34302. // This way the result will be the same whether the tinycolor is initialized with string or object.
  34303. var match;
  34304. if ((match = matchers.rgb.exec(color))) {
  34305. return { r: match[1], g: match[2], b: match[3] };
  34306. }
  34307. if ((match = matchers.rgba.exec(color))) {
  34308. return { r: match[1], g: match[2], b: match[3], a: match[4] };
  34309. }
  34310. if ((match = matchers.hsl.exec(color))) {
  34311. return { h: match[1], s: match[2], l: match[3] };
  34312. }
  34313. if ((match = matchers.hsla.exec(color))) {
  34314. return { h: match[1], s: match[2], l: match[3], a: match[4] };
  34315. }
  34316. if ((match = matchers.hsv.exec(color))) {
  34317. return { h: match[1], s: match[2], v: match[3] };
  34318. }
  34319. if ((match = matchers.hsva.exec(color))) {
  34320. return { h: match[1], s: match[2], v: match[3], a: match[4] };
  34321. }
  34322. if ((match = matchers.hex8.exec(color))) {
  34323. return {
  34324. r: parseIntFromHex(match[1]),
  34325. g: parseIntFromHex(match[2]),
  34326. b: parseIntFromHex(match[3]),
  34327. a: convertHexToDecimal(match[4]),
  34328. format: named ? "name" : "hex8"
  34329. };
  34330. }
  34331. if ((match = matchers.hex6.exec(color))) {
  34332. return {
  34333. r: parseIntFromHex(match[1]),
  34334. g: parseIntFromHex(match[2]),
  34335. b: parseIntFromHex(match[3]),
  34336. format: named ? "name" : "hex"
  34337. };
  34338. }
  34339. if ((match = matchers.hex4.exec(color))) {
  34340. return {
  34341. r: parseIntFromHex(match[1] + '' + match[1]),
  34342. g: parseIntFromHex(match[2] + '' + match[2]),
  34343. b: parseIntFromHex(match[3] + '' + match[3]),
  34344. a: convertHexToDecimal(match[4] + '' + match[4]),
  34345. format: named ? "name" : "hex8"
  34346. };
  34347. }
  34348. if ((match = matchers.hex3.exec(color))) {
  34349. return {
  34350. r: parseIntFromHex(match[1] + '' + match[1]),
  34351. g: parseIntFromHex(match[2] + '' + match[2]),
  34352. b: parseIntFromHex(match[3] + '' + match[3]),
  34353. format: named ? "name" : "hex"
  34354. };
  34355. }
  34356. return false;
  34357. }
  34358. function validateWCAG2Parms(parms) {
  34359. // return valid WCAG2 parms for isReadable.
  34360. // If input parms are invalid, return {"level":"AA", "size":"small"}
  34361. var level, size;
  34362. parms = parms || {"level":"AA", "size":"small"};
  34363. level = (parms.level || "AA").toUpperCase();
  34364. size = (parms.size || "small").toLowerCase();
  34365. if (level !== "AA" && level !== "AAA") {
  34366. level = "AA";
  34367. }
  34368. if (size !== "small" && size !== "large") {
  34369. size = "small";
  34370. }
  34371. return {"level":level, "size":size};
  34372. }
  34373. // Node: Export function
  34374. if (typeof module !== "undefined" && module.exports) {
  34375. module.exports = tinycolor;
  34376. }
  34377. // AMD/requirejs: Define the module
  34378. else if (typeof define === 'function' && define.amd) {
  34379. define(function () {return tinycolor;});
  34380. }
  34381. // Browser: Expose to window
  34382. else {
  34383. window.tinycolor = tinycolor;
  34384. }
  34385. })(Math);
  34386. },{}],358:[function(require,module,exports){
  34387. exports = module.exports = trim;
  34388. function trim(str){
  34389. return str.replace(/^\s*|\s*$/g, '');
  34390. }
  34391. exports.left = function(str){
  34392. return str.replace(/^\s*/, '');
  34393. };
  34394. exports.right = function(str){
  34395. return str.replace(/\s*$/, '');
  34396. };
  34397. },{}],359:[function(require,module,exports){
  34398. // Copyright Joyent, Inc. and other Node contributors.
  34399. //
  34400. // Permission is hereby granted, free of charge, to any person obtaining a
  34401. // copy of this software and associated documentation files (the
  34402. // "Software"), to deal in the Software without restriction, including
  34403. // without limitation the rights to use, copy, modify, merge, publish,
  34404. // distribute, sublicense, and/or sell copies of the Software, and to permit
  34405. // persons to whom the Software is furnished to do so, subject to the
  34406. // following conditions:
  34407. //
  34408. // The above copyright notice and this permission notice shall be included
  34409. // in all copies or substantial portions of the Software.
  34410. //
  34411. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  34412. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  34413. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  34414. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  34415. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  34416. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  34417. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  34418. 'use strict';
  34419. var punycode = require('punycode');
  34420. var util = require('./util');
  34421. exports.parse = urlParse;
  34422. exports.resolve = urlResolve;
  34423. exports.resolveObject = urlResolveObject;
  34424. exports.format = urlFormat;
  34425. exports.Url = Url;
  34426. function Url() {
  34427. this.protocol = null;
  34428. this.slashes = null;
  34429. this.auth = null;
  34430. this.host = null;
  34431. this.port = null;
  34432. this.hostname = null;
  34433. this.hash = null;
  34434. this.search = null;
  34435. this.query = null;
  34436. this.pathname = null;
  34437. this.path = null;
  34438. this.href = null;
  34439. }
  34440. // Reference: RFC 3986, RFC 1808, RFC 2396
  34441. // define these here so at least they only have to be
  34442. // compiled once on the first module load.
  34443. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  34444. portPattern = /:[0-9]*$/,
  34445. // Special case for a simple path URL
  34446. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  34447. // RFC 2396: characters reserved for delimiting URLs.
  34448. // We actually just auto-escape these.
  34449. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  34450. // RFC 2396: characters not allowed for various reasons.
  34451. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  34452. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  34453. autoEscape = ['\''].concat(unwise),
  34454. // Characters that are never ever allowed in a hostname.
  34455. // Note that any invalid chars are also handled, but these
  34456. // are the ones that are *expected* to be seen, so we fast-path
  34457. // them.
  34458. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  34459. hostEndingChars = ['/', '?', '#'],
  34460. hostnameMaxLen = 255,
  34461. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  34462. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  34463. // protocols that can allow "unsafe" and "unwise" chars.
  34464. unsafeProtocol = {
  34465. 'javascript': true,
  34466. 'javascript:': true
  34467. },
  34468. // protocols that never have a hostname.
  34469. hostlessProtocol = {
  34470. 'javascript': true,
  34471. 'javascript:': true
  34472. },
  34473. // protocols that always contain a // bit.
  34474. slashedProtocol = {
  34475. 'http': true,
  34476. 'https': true,
  34477. 'ftp': true,
  34478. 'gopher': true,
  34479. 'file': true,
  34480. 'http:': true,
  34481. 'https:': true,
  34482. 'ftp:': true,
  34483. 'gopher:': true,
  34484. 'file:': true
  34485. },
  34486. querystring = require('querystring');
  34487. function urlParse(url, parseQueryString, slashesDenoteHost) {
  34488. if (url && util.isObject(url) && url instanceof Url) return url;
  34489. var u = new Url;
  34490. u.parse(url, parseQueryString, slashesDenoteHost);
  34491. return u;
  34492. }
  34493. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  34494. if (!util.isString(url)) {
  34495. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  34496. }
  34497. // Copy chrome, IE, opera backslash-handling behavior.
  34498. // Back slashes before the query string get converted to forward slashes
  34499. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  34500. var queryIndex = url.indexOf('?'),
  34501. splitter =
  34502. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  34503. uSplit = url.split(splitter),
  34504. slashRegex = /\\/g;
  34505. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  34506. url = uSplit.join(splitter);
  34507. var rest = url;
  34508. // trim before proceeding.
  34509. // This is to support parse stuff like " http://foo.com \n"
  34510. rest = rest.trim();
  34511. if (!slashesDenoteHost && url.split('#').length === 1) {
  34512. // Try fast path regexp
  34513. var simplePath = simplePathPattern.exec(rest);
  34514. if (simplePath) {
  34515. this.path = rest;
  34516. this.href = rest;
  34517. this.pathname = simplePath[1];
  34518. if (simplePath[2]) {
  34519. this.search = simplePath[2];
  34520. if (parseQueryString) {
  34521. this.query = querystring.parse(this.search.substr(1));
  34522. } else {
  34523. this.query = this.search.substr(1);
  34524. }
  34525. } else if (parseQueryString) {
  34526. this.search = '';
  34527. this.query = {};
  34528. }
  34529. return this;
  34530. }
  34531. }
  34532. var proto = protocolPattern.exec(rest);
  34533. if (proto) {
  34534. proto = proto[0];
  34535. var lowerProto = proto.toLowerCase();
  34536. this.protocol = lowerProto;
  34537. rest = rest.substr(proto.length);
  34538. }
  34539. // figure out if it's got a host
  34540. // user@server is *always* interpreted as a hostname, and url
  34541. // resolution will treat //foo/bar as host=foo,path=bar because that's
  34542. // how the browser resolves relative URLs.
  34543. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  34544. var slashes = rest.substr(0, 2) === '//';
  34545. if (slashes && !(proto && hostlessProtocol[proto])) {
  34546. rest = rest.substr(2);
  34547. this.slashes = true;
  34548. }
  34549. }
  34550. if (!hostlessProtocol[proto] &&
  34551. (slashes || (proto && !slashedProtocol[proto]))) {
  34552. // there's a hostname.
  34553. // the first instance of /, ?, ;, or # ends the host.
  34554. //
  34555. // If there is an @ in the hostname, then non-host chars *are* allowed
  34556. // to the left of the last @ sign, unless some host-ending character
  34557. // comes *before* the @-sign.
  34558. // URLs are obnoxious.
  34559. //
  34560. // ex:
  34561. // http://a@b@c/ => user:a@b host:c
  34562. // http://a@b?@c => user:a host:c path:/?@c
  34563. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  34564. // Review our test case against browsers more comprehensively.
  34565. // find the first instance of any hostEndingChars
  34566. var hostEnd = -1;
  34567. for (var i = 0; i < hostEndingChars.length; i++) {
  34568. var hec = rest.indexOf(hostEndingChars[i]);
  34569. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  34570. hostEnd = hec;
  34571. }
  34572. // at this point, either we have an explicit point where the
  34573. // auth portion cannot go past, or the last @ char is the decider.
  34574. var auth, atSign;
  34575. if (hostEnd === -1) {
  34576. // atSign can be anywhere.
  34577. atSign = rest.lastIndexOf('@');
  34578. } else {
  34579. // atSign must be in auth portion.
  34580. // http://a@b/c@d => host:b auth:a path:/c@d
  34581. atSign = rest.lastIndexOf('@', hostEnd);
  34582. }
  34583. // Now we have a portion which is definitely the auth.
  34584. // Pull that off.
  34585. if (atSign !== -1) {
  34586. auth = rest.slice(0, atSign);
  34587. rest = rest.slice(atSign + 1);
  34588. this.auth = decodeURIComponent(auth);
  34589. }
  34590. // the host is the remaining to the left of the first non-host char
  34591. hostEnd = -1;
  34592. for (var i = 0; i < nonHostChars.length; i++) {
  34593. var hec = rest.indexOf(nonHostChars[i]);
  34594. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  34595. hostEnd = hec;
  34596. }
  34597. // if we still have not hit it, then the entire thing is a host.
  34598. if (hostEnd === -1)
  34599. hostEnd = rest.length;
  34600. this.host = rest.slice(0, hostEnd);
  34601. rest = rest.slice(hostEnd);
  34602. // pull out port.
  34603. this.parseHost();
  34604. // we've indicated that there is a hostname,
  34605. // so even if it's empty, it has to be present.
  34606. this.hostname = this.hostname || '';
  34607. // if hostname begins with [ and ends with ]
  34608. // assume that it's an IPv6 address.
  34609. var ipv6Hostname = this.hostname[0] === '[' &&
  34610. this.hostname[this.hostname.length - 1] === ']';
  34611. // validate a little.
  34612. if (!ipv6Hostname) {
  34613. var hostparts = this.hostname.split(/\./);
  34614. for (var i = 0, l = hostparts.length; i < l; i++) {
  34615. var part = hostparts[i];
  34616. if (!part) continue;
  34617. if (!part.match(hostnamePartPattern)) {
  34618. var newpart = '';
  34619. for (var j = 0, k = part.length; j < k; j++) {
  34620. if (part.charCodeAt(j) > 127) {
  34621. // we replace non-ASCII char with a temporary placeholder
  34622. // we need this to make sure size of hostname is not
  34623. // broken by replacing non-ASCII by nothing
  34624. newpart += 'x';
  34625. } else {
  34626. newpart += part[j];
  34627. }
  34628. }
  34629. // we test again with ASCII char only
  34630. if (!newpart.match(hostnamePartPattern)) {
  34631. var validParts = hostparts.slice(0, i);
  34632. var notHost = hostparts.slice(i + 1);
  34633. var bit = part.match(hostnamePartStart);
  34634. if (bit) {
  34635. validParts.push(bit[1]);
  34636. notHost.unshift(bit[2]);
  34637. }
  34638. if (notHost.length) {
  34639. rest = '/' + notHost.join('.') + rest;
  34640. }
  34641. this.hostname = validParts.join('.');
  34642. break;
  34643. }
  34644. }
  34645. }
  34646. }
  34647. if (this.hostname.length > hostnameMaxLen) {
  34648. this.hostname = '';
  34649. } else {
  34650. // hostnames are always lower case.
  34651. this.hostname = this.hostname.toLowerCase();
  34652. }
  34653. if (!ipv6Hostname) {
  34654. // IDNA Support: Returns a punycoded representation of "domain".
  34655. // It only converts parts of the domain name that
  34656. // have non-ASCII characters, i.e. it doesn't matter if
  34657. // you call it with a domain that already is ASCII-only.
  34658. this.hostname = punycode.toASCII(this.hostname);
  34659. }
  34660. var p = this.port ? ':' + this.port : '';
  34661. var h = this.hostname || '';
  34662. this.host = h + p;
  34663. this.href += this.host;
  34664. // strip [ and ] from the hostname
  34665. // the host field still retains them, though
  34666. if (ipv6Hostname) {
  34667. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  34668. if (rest[0] !== '/') {
  34669. rest = '/' + rest;
  34670. }
  34671. }
  34672. }
  34673. // now rest is set to the post-host stuff.
  34674. // chop off any delim chars.
  34675. if (!unsafeProtocol[lowerProto]) {
  34676. // First, make 100% sure that any "autoEscape" chars get
  34677. // escaped, even if encodeURIComponent doesn't think they
  34678. // need to be.
  34679. for (var i = 0, l = autoEscape.length; i < l; i++) {
  34680. var ae = autoEscape[i];
  34681. if (rest.indexOf(ae) === -1)
  34682. continue;
  34683. var esc = encodeURIComponent(ae);
  34684. if (esc === ae) {
  34685. esc = escape(ae);
  34686. }
  34687. rest = rest.split(ae).join(esc);
  34688. }
  34689. }
  34690. // chop off from the tail first.
  34691. var hash = rest.indexOf('#');
  34692. if (hash !== -1) {
  34693. // got a fragment string.
  34694. this.hash = rest.substr(hash);
  34695. rest = rest.slice(0, hash);
  34696. }
  34697. var qm = rest.indexOf('?');
  34698. if (qm !== -1) {
  34699. this.search = rest.substr(qm);
  34700. this.query = rest.substr(qm + 1);
  34701. if (parseQueryString) {
  34702. this.query = querystring.parse(this.query);
  34703. }
  34704. rest = rest.slice(0, qm);
  34705. } else if (parseQueryString) {
  34706. // no query string, but parseQueryString still requested
  34707. this.search = '';
  34708. this.query = {};
  34709. }
  34710. if (rest) this.pathname = rest;
  34711. if (slashedProtocol[lowerProto] &&
  34712. this.hostname && !this.pathname) {
  34713. this.pathname = '/';
  34714. }
  34715. //to support http.request
  34716. if (this.pathname || this.search) {
  34717. var p = this.pathname || '';
  34718. var s = this.search || '';
  34719. this.path = p + s;
  34720. }
  34721. // finally, reconstruct the href based on what has been validated.
  34722. this.href = this.format();
  34723. return this;
  34724. };
  34725. // format a parsed object into a url string
  34726. function urlFormat(obj) {
  34727. // ensure it's an object, and not a string url.
  34728. // If it's an obj, this is a no-op.
  34729. // this way, you can call url_format() on strings
  34730. // to clean up potentially wonky urls.
  34731. if (util.isString(obj)) obj = urlParse(obj);
  34732. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  34733. return obj.format();
  34734. }
  34735. Url.prototype.format = function() {
  34736. var auth = this.auth || '';
  34737. if (auth) {
  34738. auth = encodeURIComponent(auth);
  34739. auth = auth.replace(/%3A/i, ':');
  34740. auth += '@';
  34741. }
  34742. var protocol = this.protocol || '',
  34743. pathname = this.pathname || '',
  34744. hash = this.hash || '',
  34745. host = false,
  34746. query = '';
  34747. if (this.host) {
  34748. host = auth + this.host;
  34749. } else if (this.hostname) {
  34750. host = auth + (this.hostname.indexOf(':') === -1 ?
  34751. this.hostname :
  34752. '[' + this.hostname + ']');
  34753. if (this.port) {
  34754. host += ':' + this.port;
  34755. }
  34756. }
  34757. if (this.query &&
  34758. util.isObject(this.query) &&
  34759. Object.keys(this.query).length) {
  34760. query = querystring.stringify(this.query);
  34761. }
  34762. var search = this.search || (query && ('?' + query)) || '';
  34763. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  34764. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  34765. // unless they had them to begin with.
  34766. if (this.slashes ||
  34767. (!protocol || slashedProtocol[protocol]) && host !== false) {
  34768. host = '//' + (host || '');
  34769. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  34770. } else if (!host) {
  34771. host = '';
  34772. }
  34773. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  34774. if (search && search.charAt(0) !== '?') search = '?' + search;
  34775. pathname = pathname.replace(/[?#]/g, function(match) {
  34776. return encodeURIComponent(match);
  34777. });
  34778. search = search.replace('#', '%23');
  34779. return protocol + host + pathname + search + hash;
  34780. };
  34781. function urlResolve(source, relative) {
  34782. return urlParse(source, false, true).resolve(relative);
  34783. }
  34784. Url.prototype.resolve = function(relative) {
  34785. return this.resolveObject(urlParse(relative, false, true)).format();
  34786. };
  34787. function urlResolveObject(source, relative) {
  34788. if (!source) return relative;
  34789. return urlParse(source, false, true).resolveObject(relative);
  34790. }
  34791. Url.prototype.resolveObject = function(relative) {
  34792. if (util.isString(relative)) {
  34793. var rel = new Url();
  34794. rel.parse(relative, false, true);
  34795. relative = rel;
  34796. }
  34797. var result = new Url();
  34798. var tkeys = Object.keys(this);
  34799. for (var tk = 0; tk < tkeys.length; tk++) {
  34800. var tkey = tkeys[tk];
  34801. result[tkey] = this[tkey];
  34802. }
  34803. // hash is always overridden, no matter what.
  34804. // even href="" will remove it.
  34805. result.hash = relative.hash;
  34806. // if the relative url is empty, then there's nothing left to do here.
  34807. if (relative.href === '') {
  34808. result.href = result.format();
  34809. return result;
  34810. }
  34811. // hrefs like //foo/bar always cut to the protocol.
  34812. if (relative.slashes && !relative.protocol) {
  34813. // take everything except the protocol from relative
  34814. var rkeys = Object.keys(relative);
  34815. for (var rk = 0; rk < rkeys.length; rk++) {
  34816. var rkey = rkeys[rk];
  34817. if (rkey !== 'protocol')
  34818. result[rkey] = relative[rkey];
  34819. }
  34820. //urlParse appends trailing / to urls like http://www.example.com
  34821. if (slashedProtocol[result.protocol] &&
  34822. result.hostname && !result.pathname) {
  34823. result.path = result.pathname = '/';
  34824. }
  34825. result.href = result.format();
  34826. return result;
  34827. }
  34828. if (relative.protocol && relative.protocol !== result.protocol) {
  34829. // if it's a known url protocol, then changing
  34830. // the protocol does weird things
  34831. // first, if it's not file:, then we MUST have a host,
  34832. // and if there was a path
  34833. // to begin with, then we MUST have a path.
  34834. // if it is file:, then the host is dropped,
  34835. // because that's known to be hostless.
  34836. // anything else is assumed to be absolute.
  34837. if (!slashedProtocol[relative.protocol]) {
  34838. var keys = Object.keys(relative);
  34839. for (var v = 0; v < keys.length; v++) {
  34840. var k = keys[v];
  34841. result[k] = relative[k];
  34842. }
  34843. result.href = result.format();
  34844. return result;
  34845. }
  34846. result.protocol = relative.protocol;
  34847. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  34848. var relPath = (relative.pathname || '').split('/');
  34849. while (relPath.length && !(relative.host = relPath.shift()));
  34850. if (!relative.host) relative.host = '';
  34851. if (!relative.hostname) relative.hostname = '';
  34852. if (relPath[0] !== '') relPath.unshift('');
  34853. if (relPath.length < 2) relPath.unshift('');
  34854. result.pathname = relPath.join('/');
  34855. } else {
  34856. result.pathname = relative.pathname;
  34857. }
  34858. result.search = relative.search;
  34859. result.query = relative.query;
  34860. result.host = relative.host || '';
  34861. result.auth = relative.auth;
  34862. result.hostname = relative.hostname || relative.host;
  34863. result.port = relative.port;
  34864. // to support http.request
  34865. if (result.pathname || result.search) {
  34866. var p = result.pathname || '';
  34867. var s = result.search || '';
  34868. result.path = p + s;
  34869. }
  34870. result.slashes = result.slashes || relative.slashes;
  34871. result.href = result.format();
  34872. return result;
  34873. }
  34874. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  34875. isRelAbs = (
  34876. relative.host ||
  34877. relative.pathname && relative.pathname.charAt(0) === '/'
  34878. ),
  34879. mustEndAbs = (isRelAbs || isSourceAbs ||
  34880. (result.host && relative.pathname)),
  34881. removeAllDots = mustEndAbs,
  34882. srcPath = result.pathname && result.pathname.split('/') || [],
  34883. relPath = relative.pathname && relative.pathname.split('/') || [],
  34884. psychotic = result.protocol && !slashedProtocol[result.protocol];
  34885. // if the url is a non-slashed url, then relative
  34886. // links like ../.. should be able
  34887. // to crawl up to the hostname, as well. This is strange.
  34888. // result.protocol has already been set by now.
  34889. // Later on, put the first path part into the host field.
  34890. if (psychotic) {
  34891. result.hostname = '';
  34892. result.port = null;
  34893. if (result.host) {
  34894. if (srcPath[0] === '') srcPath[0] = result.host;
  34895. else srcPath.unshift(result.host);
  34896. }
  34897. result.host = '';
  34898. if (relative.protocol) {
  34899. relative.hostname = null;
  34900. relative.port = null;
  34901. if (relative.host) {
  34902. if (relPath[0] === '') relPath[0] = relative.host;
  34903. else relPath.unshift(relative.host);
  34904. }
  34905. relative.host = null;
  34906. }
  34907. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  34908. }
  34909. if (isRelAbs) {
  34910. // it's absolute.
  34911. result.host = (relative.host || relative.host === '') ?
  34912. relative.host : result.host;
  34913. result.hostname = (relative.hostname || relative.hostname === '') ?
  34914. relative.hostname : result.hostname;
  34915. result.search = relative.search;
  34916. result.query = relative.query;
  34917. srcPath = relPath;
  34918. // fall through to the dot-handling below.
  34919. } else if (relPath.length) {
  34920. // it's relative
  34921. // throw away the existing file, and take the new path instead.
  34922. if (!srcPath) srcPath = [];
  34923. srcPath.pop();
  34924. srcPath = srcPath.concat(relPath);
  34925. result.search = relative.search;
  34926. result.query = relative.query;
  34927. } else if (!util.isNullOrUndefined(relative.search)) {
  34928. // just pull out the search.
  34929. // like href='?foo'.
  34930. // Put this after the other two cases because it simplifies the booleans
  34931. if (psychotic) {
  34932. result.hostname = result.host = srcPath.shift();
  34933. //occationaly the auth can get stuck only in host
  34934. //this especially happens in cases like
  34935. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  34936. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  34937. result.host.split('@') : false;
  34938. if (authInHost) {
  34939. result.auth = authInHost.shift();
  34940. result.host = result.hostname = authInHost.shift();
  34941. }
  34942. }
  34943. result.search = relative.search;
  34944. result.query = relative.query;
  34945. //to support http.request
  34946. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  34947. result.path = (result.pathname ? result.pathname : '') +
  34948. (result.search ? result.search : '');
  34949. }
  34950. result.href = result.format();
  34951. return result;
  34952. }
  34953. if (!srcPath.length) {
  34954. // no path at all. easy.
  34955. // we've already handled the other stuff above.
  34956. result.pathname = null;
  34957. //to support http.request
  34958. if (result.search) {
  34959. result.path = '/' + result.search;
  34960. } else {
  34961. result.path = null;
  34962. }
  34963. result.href = result.format();
  34964. return result;
  34965. }
  34966. // if a url ENDs in . or .., then it must get a trailing slash.
  34967. // however, if it ends in anything else non-slashy,
  34968. // then it must NOT get a trailing slash.
  34969. var last = srcPath.slice(-1)[0];
  34970. var hasTrailingSlash = (
  34971. (result.host || relative.host || srcPath.length > 1) &&
  34972. (last === '.' || last === '..') || last === '');
  34973. // strip single dots, resolve double dots to parent dir
  34974. // if the path tries to go above the root, `up` ends up > 0
  34975. var up = 0;
  34976. for (var i = srcPath.length; i >= 0; i--) {
  34977. last = srcPath[i];
  34978. if (last === '.') {
  34979. srcPath.splice(i, 1);
  34980. } else if (last === '..') {
  34981. srcPath.splice(i, 1);
  34982. up++;
  34983. } else if (up) {
  34984. srcPath.splice(i, 1);
  34985. up--;
  34986. }
  34987. }
  34988. // if the path is allowed to go above the root, restore leading ..s
  34989. if (!mustEndAbs && !removeAllDots) {
  34990. for (; up--; up) {
  34991. srcPath.unshift('..');
  34992. }
  34993. }
  34994. if (mustEndAbs && srcPath[0] !== '' &&
  34995. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  34996. srcPath.unshift('');
  34997. }
  34998. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  34999. srcPath.push('');
  35000. }
  35001. var isAbsolute = srcPath[0] === '' ||
  35002. (srcPath[0] && srcPath[0].charAt(0) === '/');
  35003. // put the host back
  35004. if (psychotic) {
  35005. result.hostname = result.host = isAbsolute ? '' :
  35006. srcPath.length ? srcPath.shift() : '';
  35007. //occationaly the auth can get stuck only in host
  35008. //this especially happens in cases like
  35009. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  35010. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  35011. result.host.split('@') : false;
  35012. if (authInHost) {
  35013. result.auth = authInHost.shift();
  35014. result.host = result.hostname = authInHost.shift();
  35015. }
  35016. }
  35017. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  35018. if (mustEndAbs && !isAbsolute) {
  35019. srcPath.unshift('');
  35020. }
  35021. if (!srcPath.length) {
  35022. result.pathname = null;
  35023. result.path = null;
  35024. } else {
  35025. result.pathname = srcPath.join('/');
  35026. }
  35027. //to support request.http
  35028. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  35029. result.path = (result.pathname ? result.pathname : '') +
  35030. (result.search ? result.search : '');
  35031. }
  35032. result.auth = relative.auth || result.auth;
  35033. result.slashes = result.slashes || relative.slashes;
  35034. result.href = result.format();
  35035. return result;
  35036. };
  35037. Url.prototype.parseHost = function() {
  35038. var host = this.host;
  35039. var port = portPattern.exec(host);
  35040. if (port) {
  35041. port = port[0];
  35042. if (port !== ':') {
  35043. this.port = port.substr(1);
  35044. }
  35045. host = host.substr(0, host.length - port.length);
  35046. }
  35047. if (host) this.hostname = host;
  35048. };
  35049. },{"./util":360,"punycode":313,"querystring":316}],360:[function(require,module,exports){
  35050. 'use strict';
  35051. module.exports = {
  35052. isString: function(arg) {
  35053. return typeof(arg) === 'string';
  35054. },
  35055. isObject: function(arg) {
  35056. return typeof(arg) === 'object' && arg !== null;
  35057. },
  35058. isNull: function(arg) {
  35059. return arg === null;
  35060. },
  35061. isNullOrUndefined: function(arg) {
  35062. return arg == null;
  35063. }
  35064. };
  35065. },{}],361:[function(require,module,exports){
  35066. (function (process){
  35067. ;(function(){
  35068. var UTIF = {};
  35069. // Make available for import by `require()`
  35070. if (typeof module == "object") {module.exports = UTIF;}
  35071. else {self.UTIF = UTIF;}
  35072. var pako;
  35073. if (typeof require == "function") {pako = require("pako");}
  35074. else {pako = self.pako;}
  35075. function log() { if (typeof process=="undefined" || process.env.NODE_ENV=="development") console.log.apply(console, arguments); }
  35076. (function(UTIF, pako){
  35077. // Following lines add a JPEG decoder to UTIF.JpegDecoder
  35078. (function(){var V="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(g){return typeof g}:function(g){return g&&"function"===typeof Symbol&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g},D=function(){function g(g){this.message="JPEG error: "+g}g.prototype=Error();g.prototype.name="JpegError";return g.constructor=g}(),P=function(){function g(g,D){this.message=g;this.g=D}g.prototype=Error();g.prototype.name="DNLMarkerError";return g.constructor=g}();(function(){function g(){this.M=
  35079. null;this.B=-1}function W(a,d){for(var f=0,e=[],b,B,k=16;0<k&&!a[k-1];)k--;e.push({children:[],index:0});var l=e[0],r;for(b=0;b<k;b++){for(B=0;B<a[b];B++){l=e.pop();for(l.children[l.index]=d[f];0<l.index;)l=e.pop();l.index++;for(e.push(l);e.length<=b;)e.push(r={children:[],index:0}),l.children[l.index]=r.children,l=r;f++}b+1<k&&(e.push(r={children:[],index:0}),l.children[l.index]=r.children,l=r)}return e[0].children}function X(a,d,f,e,b,B,k,l,r){function n(){if(0<x)return x--,z>>x&1;z=a[d++];if(255===
  35080. z){var c=a[d++];if(c){if(220===c&&g){d+=2;var b=a[d++]<<8|a[d++];if(0<b&&b!==f.g)throw new P("Found DNL marker (0xFFDC) while parsing scan data",b);}throw new D("unexpected marker "+(z<<8|c).toString(16));}}x=7;return z>>>7}function q(a){for(;;){a=a[n()];if("number"===typeof a)return a;if("object"!==("undefined"===typeof a?"undefined":V(a)))throw new D("invalid huffman sequence");}}function h(a){for(var c=0;0<a;)c=c<<1|n(),a--;return c}function c(a){if(1===a)return 1===n()?1:-1;var c=h(a);return c>=
  35081. 1<<a-1?c:c+(-1<<a)+1}function C(a,b){var d=q(a.D);d=0===d?0:c(d);a.a[b]=a.m+=d;for(d=1;64>d;){var h=q(a.o),k=h&15;h>>=4;if(0===k){if(15>h)break;d+=16}else d+=h,a.a[b+J[d]]=c(k),d++}}function w(a,d){var b=q(a.D);b=0===b?0:c(b)<<r;a.a[d]=a.m+=b}function p(a,c){a.a[c]|=n()<<r}function m(a,b){if(0<A)A--;else for(var d=B;d<=k;){var e=q(a.o),f=e&15;e>>=4;if(0===f){if(15>e){A=h(e)+(1<<e)-1;break}d+=16}else d+=e,a.a[b+J[d]]=c(f)*(1<<r),d++}}function t(a,d){for(var b=B,e=0,f;b<=k;){f=d+J[b];var l=0>a.a[f]?
  35082. -1:1;switch(E){case 0:e=q(a.o);f=e&15;e>>=4;if(0===f)15>e?(A=h(e)+(1<<e),E=4):(e=16,E=1);else{if(1!==f)throw new D("invalid ACn encoding");Q=c(f);E=e?2:3}continue;case 1:case 2:a.a[f]?a.a[f]+=l*(n()<<r):(e--,0===e&&(E=2===E?3:0));break;case 3:a.a[f]?a.a[f]+=l*(n()<<r):(a.a[f]=Q<<r,E=0);break;case 4:a.a[f]&&(a.a[f]+=l*(n()<<r))}b++}4===E&&(A--,0===A&&(E=0))}var g=9<arguments.length&&void 0!==arguments[9]?arguments[9]:!1,u=f.P,v=d,z=0,x=0,A=0,E=0,Q,K=e.length,F,L,M,I;var R=f.S?0===B?0===l?w:p:0===l?
  35083. m:t:C;var G=0;var O=1===K?e[0].c*e[0].l:u*f.O;for(var S,T;G<O;){var U=b?Math.min(O-G,b):O;for(F=0;F<K;F++)e[F].m=0;A=0;if(1===K){var y=e[0];for(I=0;I<U;I++)R(y,64*((y.c+1)*(G/y.c|0)+G%y.c)),G++}else for(I=0;I<U;I++){for(F=0;F<K;F++)for(y=e[F],S=y.h,T=y.j,L=0;L<T;L++)for(M=0;M<S;M++)R(y,64*((y.c+1)*((G/u|0)*y.j+L)+(G%u*y.h+M)));G++}x=0;(y=N(a,d))&&y.f&&((0,_util.warn)("decodeScan - unexpected MCU data, current marker is: "+y.f),d=y.offset);y=y&&y.F;if(!y||65280>=y)throw new D("marker was not found");
  35084. if(65488<=y&&65495>=y)d+=2;else break}(y=N(a,d))&&y.f&&((0,_util.warn)("decodeScan - unexpected Scan data, current marker is: "+y.f),d=y.offset);return d-v}function Y(a,d){for(var f=d.c,e=d.l,b=new Int16Array(64),B=0;B<e;B++)for(var k=0;k<f;k++){var l=64*((d.c+1)*B+k),r=b,n=d.G,q=d.a;if(!n)throw new D("missing required Quantization Table.");for(var h=0;64>h;h+=8){var c=q[l+h];var C=q[l+h+1];var w=q[l+h+2];var p=q[l+h+3];var m=q[l+h+4];var t=q[l+h+5];var g=q[l+h+6];var u=q[l+h+7];c*=n[h];if(0===(C|
  35085. w|p|m|t|g|u))c=5793*c+512>>10,r[h]=c,r[h+1]=c,r[h+2]=c,r[h+3]=c,r[h+4]=c,r[h+5]=c,r[h+6]=c,r[h+7]=c;else{C*=n[h+1];w*=n[h+2];p*=n[h+3];m*=n[h+4];t*=n[h+5];g*=n[h+6];u*=n[h+7];var v=5793*c+128>>8;var z=5793*m+128>>8;var x=w;var A=g;m=2896*(C-u)+128>>8;u=2896*(C+u)+128>>8;p<<=4;t<<=4;v=v+z+1>>1;z=v-z;c=3784*x+1567*A+128>>8;x=1567*x-3784*A+128>>8;A=c;m=m+t+1>>1;t=m-t;u=u+p+1>>1;p=u-p;v=v+A+1>>1;A=v-A;z=z+x+1>>1;x=z-x;c=2276*m+3406*u+2048>>12;m=3406*m-2276*u+2048>>12;u=c;c=799*p+4017*t+2048>>12;p=4017*
  35086. p-799*t+2048>>12;t=c;r[h]=v+u;r[h+7]=v-u;r[h+1]=z+t;r[h+6]=z-t;r[h+2]=x+p;r[h+5]=x-p;r[h+3]=A+m;r[h+4]=A-m}}for(n=0;8>n;++n)c=r[n],C=r[n+8],w=r[n+16],p=r[n+24],m=r[n+32],t=r[n+40],g=r[n+48],u=r[n+56],0===(C|w|p|m|t|g|u)?(c=5793*c+8192>>14,c=-2040>c?0:2024<=c?255:c+2056>>4,q[l+n]=c,q[l+n+8]=c,q[l+n+16]=c,q[l+n+24]=c,q[l+n+32]=c,q[l+n+40]=c,q[l+n+48]=c,q[l+n+56]=c):(v=5793*c+2048>>12,z=5793*m+2048>>12,x=w,A=g,m=2896*(C-u)+2048>>12,u=2896*(C+u)+2048>>12,v=(v+z+1>>1)+4112,z=v-z,c=3784*x+1567*A+2048>>
  35087. 12,x=1567*x-3784*A+2048>>12,A=c,m=m+t+1>>1,t=m-t,u=u+p+1>>1,p=u-p,v=v+A+1>>1,A=v-A,z=z+x+1>>1,x=z-x,c=2276*m+3406*u+2048>>12,m=3406*m-2276*u+2048>>12,u=c,c=799*p+4017*t+2048>>12,p=4017*p-799*t+2048>>12,t=c,c=v+u,u=v-u,C=z+t,g=z-t,w=x+p,t=x-p,p=A+m,m=A-m,c=16>c?0:4080<=c?255:c>>4,C=16>C?0:4080<=C?255:C>>4,w=16>w?0:4080<=w?255:w>>4,p=16>p?0:4080<=p?255:p>>4,m=16>m?0:4080<=m?255:m>>4,t=16>t?0:4080<=t?255:t>>4,g=16>g?0:4080<=g?255:g>>4,u=16>u?0:4080<=u?255:u>>4,q[l+n]=c,q[l+n+8]=C,q[l+n+16]=w,q[l+n+24]=
  35088. p,q[l+n+32]=m,q[l+n+40]=t,q[l+n+48]=g,q[l+n+56]=u)}return d.a}function N(a,d){var f=2<arguments.length&&void 0!==arguments[2]?arguments[2]:d,e=a.length-1;f=f<d?f:d;if(d>=e)return null;var b=a[d]<<8|a[d+1];if(65472<=b&&65534>=b)return{f:null,F:b,offset:d};for(var B=a[f]<<8|a[f+1];!(65472<=B&&65534>=B);){if(++f>=e)return null;B=a[f]<<8|a[f+1]}return{f:b.toString(16),F:B,offset:f}}var J=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,
  35089. 57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);g.prototype={parse:function(a){function d(){var d=a[k]<<8|a[k+1];k+=2;return d}function f(){var b=d();b=k+b-2;var c=N(a,b,k);c&&c.f&&((0,_util.warn)("readDataBlock - incorrect length, current marker is: "+c.f),b=c.offset);b=a.subarray(k,b);k+=b.length;return b}function e(a){for(var b=Math.ceil(a.v/8/a.s),c=Math.ceil(a.g/8/a.u),d=0;d<a.b.length;d++){v=a.b[d];var e=Math.ceil(Math.ceil(a.v/8)*v.h/a.s),f=Math.ceil(Math.ceil(a.g/
  35090. 8)*v.j/a.u);v.a=new Int16Array(64*c*v.j*(b*v.h+1));v.c=e;v.l=f}a.P=b;a.O=c}var b=(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}).N,B=void 0===b?null:b,k=0,l=null,r=0;b=[];var n=[],q=[],h=d();if(65496!==h)throw new D("SOI not found");for(h=d();65497!==h;){switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var c=f();65518===h&&65===c[0]&&100===
  35091. c[1]&&111===c[2]&&98===c[3]&&101===c[4]&&(l={version:c[5]<<8|c[6],Y:c[7]<<8|c[8],Z:c[9]<<8|c[10],W:c[11]});break;case 65499:h=d()+k-2;for(var g;k<h;){var w=a[k++],p=new Uint16Array(64);if(0===w>>4)for(c=0;64>c;c++)g=J[c],p[g]=a[k++];else if(1===w>>4)for(c=0;64>c;c++)g=J[c],p[g]=d();else throw new D("DQT - invalid table spec");b[w&15]=p}break;case 65472:case 65473:case 65474:if(m)throw new D("Only single frame JPEGs supported");d();var m={};m.X=65473===h;m.S=65474===h;m.precision=a[k++];h=d();m.g=
  35092. B||h;m.v=d();m.b=[];m.C={};c=a[k++];for(h=p=w=0;h<c;h++){g=a[k];var t=a[k+1]>>4;var H=a[k+1]&15;w<t&&(w=t);p<H&&(p=H);t=m.b.push({h:t,j:H,T:a[k+2],G:null});m.C[g]=t-1;k+=3}m.s=w;m.u=p;e(m);break;case 65476:g=d();for(h=2;h<g;){w=a[k++];p=new Uint8Array(16);for(c=t=0;16>c;c++,k++)t+=p[c]=a[k];H=new Uint8Array(t);for(c=0;c<t;c++,k++)H[c]=a[k];h+=17+t;(0===w>>4?q:n)[w&15]=W(p,H)}break;case 65501:d();var u=d();break;case 65498:c=1===++r&&!B;d();w=a[k++];g=[];for(h=0;h<w;h++){p=m.C[a[k++]];var v=m.b[p];
  35093. p=a[k++];v.D=q[p>>4];v.o=n[p&15];g.push(v)}h=a[k++];w=a[k++];p=a[k++];try{var z=X(a,k,m,g,u,h,w,p>>4,p&15,c);k+=z}catch(x){if(x instanceof P)return(0,_util.warn)('Attempting to re-parse JPEG image using "scanLines" parameter found in DNL marker (0xFFDC) segment.'),this.parse(a,{N:x.g});throw x;}break;case 65500:k+=4;break;case 65535:255!==a[k]&&k--;break;default:if(255===a[k-3]&&192<=a[k-2]&&254>=a[k-2])k-=3;else if((c=N(a,k-2))&&c.f)(0,_util.warn)("JpegImage.parse - unexpected data, current marker is: "+
  35094. c.f),k=c.offset;else throw new D("unknown marker "+h.toString(16));}h=d()}this.width=m.v;this.height=m.g;this.A=l;this.b=[];for(h=0;h<m.b.length;h++){v=m.b[h];if(u=b[v.T])v.G=u;this.b.push({R:Y(m,v),U:v.h/m.s,V:v.j/m.u,c:v.c,l:v.l})}this.i=this.b.length},L:function(a,d){var f=this.width/a,e=this.height/d,b,g,k=this.b.length,l=a*d*k,r=new Uint8ClampedArray(l),n=new Uint32Array(a);for(g=0;g<k;g++){var q=this.b[g];var h=q.U*f;var c=q.V*e;var C=g;var w=q.R;var p=q.c+1<<3;for(b=0;b<a;b++)q=0|b*h,n[b]=
  35095. (q&4294967288)<<3|q&7;for(h=0;h<d;h++)for(q=0|h*c,q=p*(q&4294967288)|(q&7)<<3,b=0;b<a;b++)r[C]=w[q+n[b]],C+=k}if(e=this.M)for(g=0;g<l;)for(f=q=0;q<k;q++,g++,f+=2)r[g]=(r[g]*e[f]>>8)+e[f+1];return r},w:function(){return this.A?!!this.A.W:3===this.i?0===this.B?!1:!0:1===this.B?!0:!1},I:function(a){for(var d,f,e,b=0,g=a.length;b<g;b+=3)d=a[b],f=a[b+1],e=a[b+2],a[b]=d-179.456+1.402*e,a[b+1]=d+135.459-.344*f-.714*e,a[b+2]=d-226.816+1.772*f;return a},K:function(a){for(var d,f,e,b,g=0,k=0,l=a.length;k<l;k+=
  35096. 4)d=a[k],f=a[k+1],e=a[k+2],b=a[k+3],a[g++]=-122.67195406894+f*(-6.60635669420364E-5*f+4.37130475926232E-4*e-5.4080610064599E-5*d+4.8449797120281E-4*b-.154362151871126)+e*(-9.57964378445773E-4*e+8.17076911346625E-4*d-.00477271405408747*b+1.53380253221734)+d*(9.61250184130688E-4*d-.00266257332283933*b+.48357088451265)+b*(-3.36197177618394E-4*b+.484791561490776),a[g++]=107.268039397724+f*(2.19927104525741E-5*f-6.40992018297945E-4*e+6.59397001245577E-4*d+4.26105652938837E-4*b-.176491792462875)+e*(-7.78269941513683E-4*
  35097. e+.00130872261408275*d+7.70482631801132E-4*b-.151051492775562)+d*(.00126935368114843*d-.00265090189010898*b+.25802910206845)+b*(-3.18913117588328E-4*b-.213742400323665),a[g++]=-20.810012546947+f*(-5.70115196973677E-4*f-2.63409051004589E-5*e+.0020741088115012*d-.00288260236853442*b+.814272968359295)+e*(-1.53496057440975E-5*e-1.32689043961446E-4*d+5.60833691242812E-4*b-.195152027534049)+d*(.00174418132927582*d-.00255243321439347*b+.116935020465145)+b*(-3.43531996510555E-4*b+.24165260232407);return a.subarray(0,
  35098. g)},J:function(a){for(var d,f,e,b=0,g=a.length;b<g;b+=4)d=a[b],f=a[b+1],e=a[b+2],a[b]=434.456-d-1.402*e,a[b+1]=119.541-d+.344*f+.714*e,a[b+2]=481.816-d-1.772*f;return a},H:function(a){for(var d,f,e,b,g=0,k=1/255,l=0,r=a.length;l<r;l+=4)d=a[l]*k,f=a[l+1]*k,e=a[l+2]*k,b=a[l+3]*k,a[g++]=255+d*(-4.387332384609988*d+54.48615194189176*f+18.82290502165302*e+212.25662451639585*b-285.2331026137004)+f*(1.7149763477362134*f-5.6096736904047315*e-17.873870861415444*b-5.497006427196366)+e*(-2.5217340131683033*
  35099. e-21.248923337353073*b+17.5119270841813)-b*(21.86122147463605*b+189.48180835922747),a[g++]=255+d*(8.841041422036149*d+60.118027045597366*f+6.871425592049007*e+31.159100130055922*b-79.2970844816548)+f*(-15.310361306967817*f+17.575251261109482*e+131.35250912493976*b-190.9453302588951)+e*(4.444339102852739*e+9.8632861493405*b-24.86741582555878)-b*(20.737325471181034*b+187.80453709719578),a[g++]=255+d*(.8842522430003296*d+8.078677503112928*f+30.89978309703729*e-.23883238689178934*b-14.183576799673286)+
  35100. f*(10.49593273432072*f+63.02378494754052*e+50.606957656360734*b-112.23884253719248)+e*(.03296041114873217*e+115.60384449646641*b-193.58209356861505)-b*(22.33816807309886*b+180.12613974708367);return a.subarray(0,g)},getData:function(a,d,f){if(4<this.i)throw new D("Unsupported color mode");a=this.L(a,d);if(1===this.i&&f){f=a.length;d=new Uint8ClampedArray(3*f);for(var e=0,b=0;b<f;b++){var g=a[b];d[e++]=g;d[e++]=g;d[e++]=g}return d}if(3===this.i&&this.w())return this.I(a);if(4===this.i){if(this.w())return f?
  35101. this.K(a):this.J(a);if(f)return this.H(a)}return a}}; UTIF.JpegDecoder=g})()})();
  35102. //UTIF.JpegDecoder = window.JpegDecoder;
  35103. UTIF.encodeImage = function(rgba, w, h, metadata)
  35104. {
  35105. var idf = { "t256":[w], "t257":[h], "t258":[8,8,8,8], "t259":[1], "t262":[2], "t273":[1000], // strips offset
  35106. "t277":[4], "t278":[h], /* rows per strip */ "t279":[w*h*4], // strip byte counts
  35107. "t282":[1], "t283":[1], "t284":[1], "t286":[0], "t287":[0], "t296":[1], "t305": ["Photopea (UTIF.js)"], "t338":[1]
  35108. };
  35109. if (metadata) for (var i in metadata) idf[i] = metadata[i];
  35110. var prfx = new Uint8Array(UTIF.encode([idf]));
  35111. var img = new Uint8Array(rgba);
  35112. var data = new Uint8Array(1000+w*h*4);
  35113. for(var i=0; i<prfx.length; i++) data[i] = prfx[i];
  35114. for(var i=0; i<img .length; i++) data[1000+i] = img[i];
  35115. return data.buffer;
  35116. }
  35117. UTIF.encode = function(ifds)
  35118. {
  35119. var data = new Uint8Array(20000), offset = 4, bin = UTIF._binBE;
  35120. data[0]=77; data[1]=77; data[3]=42;
  35121. var ifdo = 8;
  35122. bin.writeUint(data, offset, ifdo); offset+=4;
  35123. for(var i=0; i<ifds.length; i++)
  35124. {
  35125. var noffs = UTIF._writeIFD(bin, data, ifdo, ifds[i]);
  35126. ifdo = noffs[1];
  35127. if(i<ifds.length-1) bin.writeUint(data, noffs[0], ifdo);
  35128. }
  35129. return data.slice(0, ifdo).buffer;
  35130. }
  35131. //UTIF.encode._writeIFD
  35132. UTIF.decode = function(buff)
  35133. {
  35134. UTIF.decode._decodeG3.allow2D = null;
  35135. var data = new Uint8Array(buff), offset = 0;
  35136. var id = UTIF._binBE.readASCII(data, offset, 2); offset+=2;
  35137. var bin = id=="II" ? UTIF._binLE : UTIF._binBE;
  35138. var num = bin.readUshort(data, offset); offset+=2;
  35139. var ifdo = bin.readUint(data, offset); offset+=4;
  35140. var ifds = [];
  35141. while(true)
  35142. {
  35143. var noff = UTIF._readIFD(bin, data, ifdo, ifds);
  35144. //var ifd = ifds[ifds.length-1]; if(ifd["t34665"]) { ifd.exifIFD = []; UTIF._readIFD(bin, data, ifd["t34665"][0], ifd.exifIFD); }
  35145. ifdo = bin.readUint(data, noff);
  35146. if(ifdo==0) break;
  35147. }
  35148. return ifds;
  35149. }
  35150. UTIF.decodeImages = function(buff, ifds)
  35151. {
  35152. var data = new Uint8Array(buff);
  35153. var id = UTIF._binBE.readASCII(data, 0, 2);
  35154. for(var ii=0; ii<ifds.length; ii++)
  35155. {
  35156. var img = ifds[ii];
  35157. if(img["t256"]==null) continue; // EXIF files don't have TIFF tags
  35158. img.isLE = id=="II";
  35159. img.width = img["t256"][0]; //delete img["t256"];
  35160. img.height = img["t257"][0]; //delete img["t257"];
  35161. var cmpr = img["t259"] ? img["t259"][0] : 1; //delete img["t259"];
  35162. var fo = img["t266"] ? img["t266"][0] : 1; //delete img["t266"];
  35163. if(img["t284"] && img["t284"][0]==2) log("PlanarConfiguration 2 should not be used!");
  35164. var bipp = (img["t258"]?Math.min(32,img["t258"][0]):1) * (img["t277"]?img["t277"][0]:1); // bits per pixel
  35165. var bipl = Math.ceil(img.width*bipp/8)*8;
  35166. var soff = img["t273"]; if(soff==null) soff = img["t324"];
  35167. var bcnt = img["t279"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null) bcnt = img["t325"];
  35168. var bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0;
  35169. if(img["t322"]!=null) // tiled
  35170. {
  35171. var tw = img["t322"][0], th = img["t323"][0];
  35172. var tx = Math.floor((img.width + tw - 1) / tw);
  35173. var ty = Math.floor((img.height + th - 1) / th);
  35174. var tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0);
  35175. for(var y=0; y<ty; y++)
  35176. for(var x=0; x<tx; x++)
  35177. {
  35178. var i = y*tx+x; for(var j=0; j<tbuff.length; j++) tbuff[j]=0;
  35179. UTIF.decode._decompress(img, data, soff[i], bcnt[i], cmpr, tbuff, 0, fo);
  35180. // Might be required for 7 too. Need to check
  35181. if (cmpr==6) bytes = tbuff;
  35182. else UTIF._copyTile(tbuff, Math.ceil(tw*bipp/8)|0, th, bytes, Math.ceil(img.width*bipp/8)|0, img.height, Math.ceil(x*tw*bipp/8)|0, y*th);
  35183. }
  35184. bilen = bytes.length*8;
  35185. }
  35186. else // stripped
  35187. {
  35188. var rps = img["t278"] ? img["t278"][0] : img.height; rps = Math.min(rps, img.height);
  35189. for(var i=0; i<soff.length; i++)
  35190. {
  35191. UTIF.decode._decompress(img, data, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen/8)|0, fo);
  35192. bilen += bipl * rps;
  35193. }
  35194. bilen = Math.min(bilen, bytes.length*8);
  35195. }
  35196. img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen/8)|0);
  35197. }
  35198. }
  35199. UTIF.decode._decompress = function(img, data, off, len, cmpr, tgt, toff, fo) // fill order
  35200. {
  35201. //console.log("compression", cmpr);
  35202. if(false) {}
  35203. else if(cmpr==1) for(var j=0; j<len; j++) tgt[toff+j] = data[off+j];
  35204. else if(cmpr==3) UTIF.decode._decodeG3 (data, off, len, tgt, toff, img.width, fo);
  35205. else if(cmpr==4) UTIF.decode._decodeG4 (data, off, len, tgt, toff, img.width, fo);
  35206. else if(cmpr==5) UTIF.decode._decodeLZW(data, off, tgt, toff);
  35207. else if(cmpr==6) UTIF.decode._decodeOldJPEG(img, data, off, len, tgt, toff);
  35208. else if(cmpr==7) UTIF.decode._decodeNewJPEG(img, data, off, len, tgt, toff);
  35209. else if(cmpr==8) { var src = new Uint8Array(data.buffer,off,len); var bin = pako["inflate"](src); for(var i=0; i<bin.length; i++) tgt[toff+i]=bin[i]; }
  35210. else if(cmpr==32773) UTIF.decode._decodePackBits(data, off, len, tgt, toff);
  35211. else if(cmpr==32809) UTIF.decode._decodeThunder (data, off, len, tgt, toff);
  35212. //else if(cmpr==34713) UTIF.decode._decodeNikon (data, off, len, tgt, toff);
  35213. else log("Unknown compression", cmpr);
  35214. if(img["t317"] && img["t317"][0]==2)
  35215. {
  35216. var noc = (img["t277"]?img["t277"][0]:1), h = (img["t278"] ? img["t278"][0] : img.height), bpr = img.width*noc;
  35217. //log(noc);
  35218. for(var y=0; y<h; y++)
  35219. {
  35220. var ntoff = toff+y*bpr;
  35221. if(noc==3) for(var j= 3; j<bpr; j+=3)
  35222. {
  35223. tgt[ntoff+j ] = (tgt[ntoff+j ] + tgt[ntoff+j-3])&255;
  35224. tgt[ntoff+j+1] = (tgt[ntoff+j+1] + tgt[ntoff+j-2])&255;
  35225. tgt[ntoff+j+2] = (tgt[ntoff+j+2] + tgt[ntoff+j-1])&255;
  35226. }
  35227. else for(var j=noc; j<bpr; j++) tgt[ntoff+j] = (tgt[ntoff+j] + tgt[ntoff+j-noc])&255;
  35228. }
  35229. }
  35230. }
  35231. UTIF.decode._decodeNikon = function(data, off, len, tgt, toff)
  35232. {
  35233. var nikon_tree = [
  35234. [ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */
  35235. 5,4,3,6,2,7,1,0,8,9,11,10,12 ],
  35236. [ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */
  35237. 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ],
  35238. [ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */
  35239. 5,4,6,3,7,2,8,1,9,0,10,11,12 ],
  35240. [ 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */
  35241. 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ],
  35242. [ 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */
  35243. 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ],
  35244. [ 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */
  35245. 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ];
  35246. //struct decode *dindex;
  35247. var ver0, ver1, vpred, hpred, csize;
  35248. var i, min, max, step=0, huff=0, split=0, row, col, len, shl, diff;
  35249. log(data.slice(off,off+100));
  35250. ver0 = data[off]; off++;
  35251. ver1 = data[off]; off++;
  35252. log(ver0.toString(16), ver1.toString(16), len);
  35253. }
  35254. UTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff)
  35255. {
  35256. var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);
  35257. if (tables)
  35258. {
  35259. var SOI = 216, EOI = 217, boff = 0;
  35260. for (var i=0; i<(tlen-1); i++)
  35261. {
  35262. // Skip EOI marker from JPEGTables
  35263. if (tables[i]==255 && tables[i+1]==EOI) break;
  35264. buff[boff++] = tables[i];
  35265. }
  35266. // Skip SOI marker from data
  35267. var byte1 = data[off], byte2 = data[off + 1];
  35268. if (byte1!=255 || byte2!=SOI)
  35269. {
  35270. buff[boff++] = byte1;
  35271. buff[boff++] = byte2;
  35272. }
  35273. for (var i=2; i<len; i++) buff[boff++] = data[off+i];
  35274. }
  35275. else for (var i=0; i<len; i++) buff[i] = data[off+i];
  35276. if(img["t262"]==32803) // lossless JPEG (used in DNG files) is not available in JpegDecoder.
  35277. {
  35278. var bps = img["t258"][0], dcdr = new LosslessJpegDecoder();
  35279. var out = dcdr.decode(buff), olen=out.length;
  35280. if(false) {}
  35281. else if(bps==16) for(var i=0; i<olen; i++) { tgt[toff++] = (out[i]&255); tgt[toff++] = (out[i]>>>8); }
  35282. else if(bps==12) for(var i=0; i<olen; i+=2) { tgt[toff++] = (out[i]>>>4); tgt[toff++] = ((out[i]<<4)|(out[i+1]>>>8))&255; tgt[toff++] = out[i+1]&255; }
  35283. else throw new Error("unsupported bit depth "+bps);
  35284. }
  35285. else
  35286. {
  35287. var parser = new UTIF.JpegDecoder(); parser.parse(buff);
  35288. var decoded = parser.getData(parser.width, parser.height);
  35289. for (var i=0; i<decoded.length; i++) tgt[toff + i] = decoded[i];
  35290. }
  35291. // PhotometricInterpretation is 6 (YCbCr) for JPEG, but after decoding we populate data in
  35292. // RGB format, so updating the tag value
  35293. if(img["t262"][0] == 6) img["t262"][0] = 2;
  35294. }
  35295. UTIF.decode._decodeOldJPEGInit = function(img, data, off, len)
  35296. {
  35297. var SOI = 216, EOI = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS = 218;
  35298. var joff = 0, soff = 0, tables, sosMarker, isTiled = false, i, j, k;
  35299. var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0;
  35300. var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0;
  35301. var soffTag = img["t324"] || img["t273"] || jpgIchgFmt;
  35302. var ycbcrss = img["t530"], ssx = 0, ssy = 0;
  35303. var spp = img["t277"]?img["t277"][0]:1;
  35304. var jpgresint = img["t515"];
  35305. if(soffTag)
  35306. {
  35307. soff = soffTag[0];
  35308. isTiled = (soffTag.length > 1);
  35309. }
  35310. if(!isTiled)
  35311. {
  35312. if(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off };
  35313. if(jpgIchgFmt!=null)
  35314. {
  35315. if(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff;
  35316. else log("JPEGInterchangeFormat does not point to SOI");
  35317. if(jpgIchgFmtLen==null) log("JPEGInterchangeFormatLength field is missing");
  35318. else if(jifoff >= soff || (jifoff+jiflen) <= soff) log("JPEGInterchangeFormatLength field value is invalid");
  35319. if(joff != null) return { jpegOffset: joff };
  35320. }
  35321. }
  35322. if(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; }
  35323. if(jpgIchgFmt!=null)
  35324. if(jpgIchgFmtLen!=null)
  35325. if(jiflen >= 2 && (jifoff+jiflen) <= soff)
  35326. {
  35327. if(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2);
  35328. else tables = new Uint8Array(jiflen);
  35329. for(i=0; i<tables.length; i++) tables[i] = data[off+jifoff+i];
  35330. log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables");
  35331. }
  35332. else log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile");
  35333. if(tables == null)
  35334. {
  35335. var ooff = 0, out = [];
  35336. out[ooff++] = 255; out[ooff++] = SOI;
  35337. var qtables = img["t519"];
  35338. if(qtables==null) throw new Error("JPEGQTables tag is missing");
  35339. for(i=0; i<qtables.length; i++)
  35340. {
  35341. out[ooff++] = 255; out[ooff++] = DQT; out[ooff++] = 0; out[ooff++] = 67; out[ooff++] = i;
  35342. for(j=0; j<64; j++) out[ooff++] = data[off+qtables[i]+j];
  35343. }
  35344. for(k=0; k<2; k++)
  35345. {
  35346. var htables = img[(k == 0) ? "t520" : "t521"];
  35347. if(htables==null) throw new Error(((k == 0) ? "JPEGDCTables" : "JPEGACTables") + " tag is missing");
  35348. for(i=0; i<htables.length; i++)
  35349. {
  35350. out[ooff++] = 255; out[ooff++] = DHT;
  35351. //out[ooff++] = 0; out[ooff++] = 67; out[ooff++] = i;
  35352. var nc = 19;
  35353. for(j=0; j<16; j++) nc += data[off+htables[i]+j];
  35354. out[ooff++] = (nc >>> 8); out[ooff++] = nc & 255;
  35355. out[ooff++] = (i | (k << 4));
  35356. for(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j];
  35357. for(j=0; j<nc; j++) out[ooff++] = data[off+htables[i]+16+j];
  35358. }
  35359. }
  35360. out[ooff++] = 255; out[ooff++] = SOF0;
  35361. out[ooff++] = 0; out[ooff++] = 8 + 3*spp; out[ooff++] = 8;
  35362. out[ooff++] = (img.height >>> 8) & 255; out[ooff++] = img.height & 255;
  35363. out[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255;
  35364. out[ooff++] = spp;
  35365. if(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; }
  35366. else for(i=0; i<3; i++)
  35367. {
  35368. out[ooff++] = i + 1;
  35369. out[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
  35370. out[ooff++] = i;
  35371. }
  35372. if(jpgresint!=null && jpgresint[0]!=0)
  35373. {
  35374. out[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4;
  35375. out[ooff++] = (jpgresint[0] >>> 8) & 255;
  35376. out[ooff++] = jpgresint[0] & 255;
  35377. }
  35378. tables = new Uint8Array(out);
  35379. }
  35380. var sofpos = -1;
  35381. i = 0;
  35382. while(i < (tables.length - 1)) {
  35383. if(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; }
  35384. i++;
  35385. }
  35386. if(sofpos == -1)
  35387. {
  35388. var tmptab = new Uint8Array(tables.length + 10 + 3*spp);
  35389. tmptab.set(tables);
  35390. var tmpoff = tables.length;
  35391. sofpos = tables.length;
  35392. tables = tmptab;
  35393. tables[tmpoff++] = 255; tables[tmpoff++] = SOF0;
  35394. tables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8;
  35395. tables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255;
  35396. tables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255;
  35397. tables[tmpoff++] = spp;
  35398. if(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; }
  35399. else for(i=0; i<3; i++)
  35400. {
  35401. tables[tmpoff++] = i + 1;
  35402. tables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
  35403. tables[tmpoff++] = i;
  35404. }
  35405. }
  35406. if(data[soff]==255 && data[soff+1]==SOS)
  35407. {
  35408. var soslen = (data[soff+2]<<8) | data[soff+3];
  35409. sosMarker = new Uint8Array(soslen+2);
  35410. sosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3];
  35411. for(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4];
  35412. }
  35413. else
  35414. {
  35415. sosMarker = new Uint8Array(2 + 6 + 2*spp);
  35416. var sosoff = 0;
  35417. sosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS;
  35418. sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp;
  35419. if(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; }
  35420. else for(i=0; i<3; i++)
  35421. {
  35422. sosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i;
  35423. }
  35424. sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0;
  35425. }
  35426. return { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos };
  35427. }
  35428. UTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff)
  35429. {
  35430. var i, dlen, tlen, buff, buffoff;
  35431. var jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len);
  35432. if(jpegData.jpegOffset!=null)
  35433. {
  35434. dlen = off+len-jpegData.jpegOffset;
  35435. buff = new Uint8Array(dlen);
  35436. for(i=0; i<dlen; i++) buff[i] = data[jpegData.jpegOffset+i];
  35437. }
  35438. else
  35439. {
  35440. tlen = jpegData.tables.length;
  35441. buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2);
  35442. buff.set(jpegData.tables);
  35443. buffoff = tlen;
  35444. buff[jpegData.sofPosition+5] = (img.height >>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255;
  35445. buff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255;
  35446. if(data[off]!=255 || data[off+1]!=SOS)
  35447. {
  35448. buff.set(jpegData.sosMarker, bufoff);
  35449. bufoff += sosMarker.length;
  35450. }
  35451. for(i=0; i<len; i++) buff[bufoff++] = data[off+i];
  35452. buff[bufoff++] = 255; buff[bufoff++] = EOI;
  35453. }
  35454. var parser = new UTIF.JpegDecoder(); parser.parse(buff);
  35455. var decoded = parser.getData(parser.width, parser.height);
  35456. for (var i=0; i<decoded.length; i++) tgt[toff + i] = decoded[i];
  35457. // PhotometricInterpretation is 6 (YCbCr) for JPEG, but after decoding we populate data in
  35458. // RGB format, so updating the tag value
  35459. if(img["t262"][0] == 6) img["t262"][0] = 2;
  35460. }
  35461. UTIF.decode._decodePackBits = function(data, off, len, tgt, toff)
  35462. {
  35463. var sa = new Int8Array(data.buffer), ta = new Int8Array(tgt.buffer), lim = off+len;
  35464. while(off<lim)
  35465. {
  35466. var n = sa[off]; off++;
  35467. if(n>=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; }
  35468. if(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; }
  35469. }
  35470. }
  35471. UTIF.decode._decodeThunder = function(data, off, len, tgt, toff)
  35472. {
  35473. var d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ];
  35474. var lim = off+len, qoff = toff*2, px = 0;
  35475. while(off<lim)
  35476. {
  35477. var b = data[off], msk = (b>>>6), n = (b&63); off++;
  35478. if(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
  35479. if(msk==0) for(var i=0; i<n; i++) { tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
  35480. if(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
  35481. if(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
  35482. }
  35483. }
  35484. UTIF.decode._dmap = { "1":0,"011":1,"000011":2,"0000011":3, "010":-1,"000010":-2,"0000010":-3 };
  35485. UTIF.decode._lens = ( function()
  35486. {
  35487. var addKeys = function(lens, arr, i0, inc) { for(var i=0; i<arr.length; i++) lens[arr[i]] = i0 + i*inc; }
  35488. var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," // 15
  35489. + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," // 31
  35490. + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," // 47
  35491. + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100";
  35492. var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," // 15
  35493. + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," // 31
  35494. + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," // 47
  35495. + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111";
  35496. var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110,"
  35497. + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011";
  35498. var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100,"
  35499. + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010,"
  35500. + "0000001011011,0000001100100,0000001100101";
  35501. var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111";
  35502. termW = termW.split(","); termB = termB.split(","); makeW = makeW.split(","); makeB = makeB.split(","); makeA = makeA.split(",");
  35503. var lensW = {}, lensB = {};
  35504. addKeys(lensW, termW, 0, 1); addKeys(lensW, makeW, 64,64); addKeys(lensW, makeA, 1792,64);
  35505. addKeys(lensB, termB, 0, 1); addKeys(lensB, makeB, 64,64); addKeys(lensB, makeA, 1792,64);
  35506. return [lensW, lensB];
  35507. } )();
  35508. UTIF.decode._decodeG4 = function(data, off, slen, tgt, toff, w, fo)
  35509. {
  35510. var U = UTIF.decode, boff=off<<3, len=0, wrd=""; // previous starts with 1
  35511. var line=[], pline=[]; for(var i=0; i<w; i++) pline.push(0); pline=U._makeDiff(pline);
  35512. var a0=0, a1=0, a2=0, b1=0, b2=0, clr=0;
  35513. var y=0, mode="", toRead=0;
  35514. var bipl = Math.ceil(w/8)*8;
  35515. while((boff>>>3)<off+slen)
  35516. {
  35517. b1 = U._findDiff(pline, a0+(a0==0?0:1), 1-clr), b2 = U._findDiff(pline, b1, clr); // could be precomputed
  35518. var bit =0;
  35519. if(fo==1) bit = (data[boff>>>3]>>>(7-(boff&7)))&1;
  35520. if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
  35521. boff++; wrd+=bit;
  35522. if(mode=="H")
  35523. {
  35524. if(U._lens[clr][wrd]!=null)
  35525. {
  35526. var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
  35527. if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
  35528. }
  35529. }
  35530. else
  35531. {
  35532. if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
  35533. if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
  35534. if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
  35535. }
  35536. if(line.length==w && mode=="")
  35537. {
  35538. U._writeBits(line, tgt, toff*8+y*bipl);
  35539. clr=0; y++; a0=0;
  35540. pline=U._makeDiff(line); line=[];
  35541. }
  35542. //if(wrd.length>150) { log(wrd); break; throw "e"; }
  35543. }
  35544. }
  35545. UTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i<line.length; i+=2) if(line[i]>=x && line[i+1]==clr) return line[i]; }
  35546. UTIF.decode._makeDiff = function(line)
  35547. {
  35548. var out = []; if(line[0]==1) out.push(0,1);
  35549. for(var i=1; i<line.length; i++) if(line[i-1]!=line[i]) out.push(i, line[i]);
  35550. out.push(line.length,0,line.length,1); return out;
  35551. }
  35552. UTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo)
  35553. {
  35554. var U = UTIF.decode, boff=off<<3, len=0, wrd="";
  35555. var line=[], pline=[]; for(var i=0; i<w; i++) line.push(0);
  35556. var a0=0, a1=0, a2=0, b1=0, b2=0, clr=0;
  35557. var y=-1, mode="", toRead=0, is1D=false;
  35558. var bipl = Math.ceil(w/8)*8;
  35559. while((boff>>>3)<off+slen)
  35560. {
  35561. b1 = U._findDiff(pline, a0+(a0==0?0:1), 1-clr), b2 = U._findDiff(pline, b1, clr); // could be precomputed
  35562. var bit =0;
  35563. if(fo==1) bit = (data[boff>>>3]>>>(7-(boff&7)))&1;
  35564. if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
  35565. boff++; wrd+=bit;
  35566. if(is1D)
  35567. {
  35568. if(U._lens[clr][wrd]!=null)
  35569. {
  35570. var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
  35571. if(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; }
  35572. }
  35573. }
  35574. else
  35575. {
  35576. if(mode=="H")
  35577. {
  35578. if(U._lens[clr][wrd]!=null)
  35579. {
  35580. var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
  35581. if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
  35582. }
  35583. }
  35584. else
  35585. {
  35586. if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
  35587. if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
  35588. if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
  35589. }
  35590. }
  35591. if(wrd.endsWith("000000000001")) // needed for some files
  35592. {
  35593. if(y>=0) U._writeBits(line, tgt, toff*8+y*bipl);
  35594. if(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1;
  35595. if(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1;
  35596. boff++;
  35597. if(U._decodeG3.allow2D==null) U._decodeG3.allow2D=is1D;
  35598. if(!U._decodeG3.allow2D) { is1D = true; boff--; }
  35599. //log("EOL",y, "next 1D:", is1D);
  35600. wrd=""; clr=0; y++; a0=0;
  35601. pline=U._makeDiff(line); line=[];
  35602. }
  35603. }
  35604. if(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl);
  35605. }
  35606. UTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i<n; i++) arr.push(val); }
  35607. UTIF.decode._writeBits = function(bits, tgt, boff)
  35608. {
  35609. for(var i=0; i<bits.length; i++) tgt[(boff+i)>>>3] |= (bits[i]<<(7-((boff+i)&7)));
  35610. }
  35611. UTIF.decode._decodeLZW = function(data, off, tgt, toff)
  35612. {
  35613. if(UTIF.decode._lzwTab==null)
  35614. {
  35615. var tb=new Uint32Array(0xffff), tn=new Uint16Array(0xffff), chr=new Uint8Array(2e6);
  35616. for(var i=0; i<256; i++) { chr[i<<2]=i; tb[i]=i<<2; tn[i]=1; }
  35617. UTIF.decode._lzwTab = [tb,tn,chr];
  35618. }
  35619. var copy = UTIF.decode._copyData;
  35620. var tab = UTIF.decode._lzwTab[0], tln=UTIF.decode._lzwTab[1], chr=UTIF.decode._lzwTab[2], totl = 258, chrl = 258<<2;
  35621. var bits = 9, boff = off<<3; // offset in bits
  35622. var ClearCode = 256, EoiCode = 257;
  35623. var v = 0, Code = 0, OldCode = 0;
  35624. while(true)
  35625. {
  35626. v = (data[boff>>>3]<<16) | (data[(boff+8)>>>3]<<8) | data[(boff+16)>>>3];
  35627. Code = ( v>>(24-(boff&7)-bits) ) & ((1<<bits)-1); boff+=bits;
  35628. if(Code==EoiCode) break;
  35629. if(Code==ClearCode)
  35630. {
  35631. bits=9; totl = 258; chrl = 258<<2;
  35632. v = (data[boff>>>3]<<16) | (data[(boff+8)>>>3]<<8) | data[(boff+16)>>>3];
  35633. Code = ( v>>(24-(boff&7)-bits) ) & ((1<<bits)-1); boff+=bits;
  35634. if(Code==EoiCode) break;
  35635. tgt[toff]=Code; toff++;
  35636. }
  35637. else if(Code<totl)
  35638. {
  35639. var cd = tab[Code], cl = tln[Code];
  35640. copy(chr,cd,tgt,toff,cl); toff += cl;
  35641. if(OldCode>=totl) { tab[totl] = chrl; chr[tab[totl]] = cd[0]; tln[totl]=1; chrl=(chrl+1+3)&~0x03; totl++; }
  35642. else
  35643. {
  35644. tab[totl] = chrl;
  35645. var nit = tab[OldCode], nil = tln[OldCode];
  35646. copy(chr,nit,chr,chrl,nil);
  35647. chr[chrl+nil]=chr[cd]; nil++;
  35648. tln[totl]=nil; totl++;
  35649. chrl=(chrl+nil+3)&~0x03;
  35650. }
  35651. if(totl+1==(1<<bits)) bits++;
  35652. }
  35653. else
  35654. {
  35655. if(OldCode>=totl) { tab[totl] = chrl; tln[totl]=0; totl++; }
  35656. else
  35657. {
  35658. tab[totl] = chrl;
  35659. var nit = tab[OldCode], nil = tln[OldCode];
  35660. copy(chr,nit,chr,chrl,nil);
  35661. chr[chrl+nil]=chr[chrl]; nil++;
  35662. tln[totl]=nil; totl++;
  35663. copy(chr,chrl,tgt,toff,nil); toff += nil;
  35664. chrl=(chrl+nil+3)&~0x03;
  35665. }
  35666. if(totl+1==(1<<bits)) bits++;
  35667. }
  35668. OldCode = Code;
  35669. }
  35670. }
  35671. UTIF.decode._copyData = function(s,so,t,to,l) { for(var i=0;i<l;i+=4) { t[to+i]=s[so+i]; t[to+i+1]=s[so+i+1]; t[to+i+2]=s[so+i+2]; t[to+i+3]=s[so+i+3]; } }
  35672. UTIF.tags = {254:"NewSubfileType",255:"SubfileType",256:"ImageWidth",257:"ImageLength",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",266:"FillOrder",
  35673. 269:"DocumentName",270:"ImageDescription",271:"Make",272:"Model",273:"StripOffset",274:"Orientation",277:"SamplesPerPixel",278:"RowsPerStrip",
  35674. 279:"StripByteCounts",280:"MinSampleValue",281:"MaxSampleValue",282:"XResolution",283:"YResolution",284:"PlanarConfiguration",285:"PageName",
  35675. 286:"XPosition",287:"YPosition",
  35676. 292:"T4Options",296:"ResolutionUnit",297:"PageNumber",305:"Software",306:"DateTime",
  35677. 315:"Artist",316:"HostComputer",317:"Predictor",318:"WhitePoint",319:"PrimaryChromaticities",320:"ColorMap",
  35678. 321:"HalftoneHints",322:"TileWidth",
  35679. 323:"TileLength",324:"TileOffset",325:"TileByteCounts",330:"SubIFDs",336:"DotRange",338:"ExtraSample",339:"SampleFormat", 347:"JPEGTables",
  35680. 512:"JPEGProc",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",519:"JPEGQTables",520:"JPEGDCTables",521:"JPEGACTables",
  35681. 529:"YCbCrCoefficients",530:"YCbCrSubSampling",531:"YCbCrPositioning",532:"ReferenceBlackWhite",700:"XMP",
  35682. 33421:"CFARepeatPatternDim",33422:"CFAPattern",33432:"Copyright",33434:"ExposureTime",33437:"FNumber",33723:"IPTC/NAA",34377:"Photoshop",
  35683. 34665:"ExifIFD",34675:"ICC Profile",34850:"ExposureProgram",34853:"GPSInfo",34855:"ISOSpeedRatings",34858:"TimeZoneOffset",34859:"SelfTimeMode",
  35684. 36867:"DateTimeOriginal",36868:"DateTimeDigitized",
  35685. 37377:"ShutterSpeedValue",37378:"ApertureValue",37380:"ExposureBiasValue",37383:"MeteringMode",37385:"Flash",37386:"FocalLength",
  35686. 37390:"FocalPlaneXResolution",37391:"FocalPlaneYResolution",37392:"FocalPlaneResolutionUnit",37393:"ImageNumber",37398:"TIFF/EPStandardID",37399:"SensingMethod",
  35687. 37500:"MakerNote",37510:"UserComment",37724:"ImageSourceData",
  35688. 40092:"XPComment",40094:"XPKeywords",
  35689. 40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelXDimension",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",
  35690. 41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41990:"SceneCaptureType",
  35691. 50706:"DNGVersion",50707:"DNGBackwardVersion",50708:"UniqueCameraModel",50709:"LocalizedCameraModel",50710:"CFAPlaneColor",
  35692. 50711:"CFALayout",50712:"LinearizationTable",50713:"BlackLevelRepeatDim",50714:"BlackLevel",50716:"BlackLevelDeltaV",50717:"WhiteLevel",
  35693. 50718:"DefaultScale",50719:"DefaultCropOrigin",
  35694. 50720:"DefaultCropSize",50733:"BayerGreenSplit",50738:"AntiAliasStrength",
  35695. 50721:"ColorMatrix1",50722:"ColorMatrix2",50723:"CameraCalibration1",50724:"CameraCalibration2",50727:"AnalogBalance",50728:"AsShotNeutral",
  35696. 50730:"BaselineExposure",50731:"BaselineNoise",50732:"BaselineSharpness",50734:"LinearResponseLimit",50735:"CameraSerialNumber",50736:"LensInfo",50739:"ShadowScale",
  35697. 50740:"DNGPrivateData",50741:"MakerNoteSafety",50778:"CalibrationIlluminant1",50779:"CalibrationIlluminant2",50780:"BestQualityScale",
  35698. 50781:"RawDataUniqueID",50827:"OriginalRawFileName",50829:"ActiveArea",50830:"MaskedAreas",50931:"CameraCalibrationSignature",50932:"ProfileCalibrationSignature",
  35699. 50935:"NoiseReductionApplied",50936:"ProfileName",50937:"ProfileHueSatMapDims",50938:"ProfileHueSatMapData1",50939:"ProfileHueSatMapData2",
  35700. 50940:"ProfileToneCurve",50941:"ProfileEmbedPolicy",50942:"ProfileCopyright",
  35701. 50964:"ForwardMatrix1",50965:"ForwardMatrix2",50966:"PreviewApplicationName",50967:"PreviewApplicationVersion",50969:"PreviewSettingsDigest",
  35702. 50970:"PreviewColorSpace",50971:"PreviewDateTime",50972:"RawImageDigest",
  35703. 51008:"OpcodeList1",51009:"OpcodeList2",51022:"OpcodeList3",51041:"NoiseProfile",51089:"OriginalDefaultFinalSize",
  35704. 51090:"OriginalBestQualityFinalSize",51091:"OriginalDefaultCropSize",51125:"DefaultUserCrop"};
  35705. UTIF.ttypes = { 256:3,257:3,258:3, 259:3, 262:3, 273:4, 274:3, 277:3,278:4,279:4, 282:5, 283:5, 284:3, 286:5,287:5, 296:3, 305:2, 306:2, 338:3, 513:4, 514:4, 34665:4 };
  35706. UTIF._readIFD = function(bin, data, offset, ifds)
  35707. {
  35708. var cnt = bin.readUshort(data, offset); offset+=2;
  35709. var ifd = {}; ifds.push(ifd);
  35710. //log(">>>----------------");
  35711. for(var i=0; i<cnt; i++)
  35712. {
  35713. var tag = bin.readUshort(data, offset); offset+=2;
  35714. var type = bin.readUshort(data, offset); offset+=2;
  35715. var num = bin.readUint (data, offset); offset+=4;
  35716. var voff = bin.readUint (data, offset); offset+=4;
  35717. var arr = [];
  35718. ifd["t"+tag] = arr;
  35719. //ifd["t"+tag+"-"+UTIF.tags[tag]] = arr;
  35720. if(type== 1 || type==7) { for(var j=0; j<num; j++) arr.push(data[(num<5 ? offset-4 : voff)+j]); }
  35721. if(type== 2) { arr.push( bin.readASCII(data, (num<5 ? offset-4 : voff), num-1) ); }
  35722. if(type== 3) { for(var j=0; j<num; j++) arr.push(bin.readUshort(data, (num<3 ? offset-4 : voff)+2*j)); }
  35723. if(type== 4) { for(var j=0; j<num; j++) arr.push(bin.readUint (data, (num<2 ? offset-4 : voff)+4*j)); }
  35724. if(type== 5) { for(var j=0; j<num; j++) arr.push(bin.readUint (data, voff+j*8) / bin.readUint(data,voff+j*8+4)); }
  35725. if(type== 8) { for(var j=0; j<num; j++) arr.push(bin.readShort (data, (num<3 ? offset-4 : voff)+2*j)); }
  35726. if(type== 9) { for(var j=0; j<num; j++) arr.push(bin.readInt (data, (num<2 ? offset-4 : voff)+4*j)); }
  35727. if(type==10) { for(var j=0; j<num; j++) arr.push(bin.readInt (data, voff+j*8) / bin.readInt (data,voff+j*8+4)); }
  35728. if(type==11) { for(var j=0; j<num; j++) arr.push(bin.readFloat (data, voff+j*4)); }
  35729. if(type==12) { for(var j=0; j<num; j++) arr.push(bin.readDouble(data, voff+j*8)); }
  35730. if(num!=0 && arr.length==0) log("unknown TIFF tag type: ", type, "num:",num);
  35731. //log(tag, type, UTIF.tags[tag], arr);
  35732. if(tag==330) for(var j=0; j<num; j++) UTIF._readIFD(bin, data, arr[j], ifds);
  35733. //if(tag==34665) UTIF._readIFD(bin, data, arr[0], ifds);
  35734. }
  35735. //log("<<<---------------");
  35736. return offset;
  35737. }
  35738. UTIF._writeIFD = function(bin, data, offset, ifd)
  35739. {
  35740. var keys = Object.keys(ifd);
  35741. bin.writeUshort(data, offset, keys.length); offset+=2;
  35742. var eoff = offset + keys.length*12 + 4;
  35743. for(var ki=0; ki<keys.length; ki++)
  35744. {
  35745. var key = keys[ki];
  35746. var tag = parseInt(key.slice(1)), type = UTIF.ttypes[tag]; if(type==null) throw new Error("unknown type of tag: "+tag);
  35747. var val = ifd[key]; if(type==2) val=val[0]+"\u0000"; var num = val.length;
  35748. bin.writeUshort(data, offset, tag ); offset+=2;
  35749. bin.writeUshort(data, offset, type); offset+=2;
  35750. bin.writeUint (data, offset, num ); offset+=4;
  35751. var dlen = [-1, 1, 1, 2, 4, 8, 0, 0, 0, 0, 0, 0, 8][type] * num;
  35752. var toff = offset;
  35753. if(dlen>4) { bin.writeUint(data, offset, eoff); toff=eoff; }
  35754. if(type==2) { bin.writeASCII(data, toff, val); }
  35755. if(type==3) { for(var i=0; i<num; i++) bin.writeUshort(data, toff+2*i, val[i]); }
  35756. if(type==4) { for(var i=0; i<num; i++) bin.writeUint (data, toff+4*i, val[i]); }
  35757. if(type==5) { for(var i=0; i<num; i++) { bin.writeUint(data, toff+8*i, Math.round(val[i]*10000)); bin.writeUint(data, toff+8*i+4, 10000); } }
  35758. if (type == 12) { for (var i = 0; i < num; i++) bin.writeDouble(data, toff + 8 * i, val[i]); }
  35759. if(dlen>4) { dlen += (dlen&1); eoff += dlen; }
  35760. offset += 4;
  35761. }
  35762. return [offset, eoff];
  35763. }
  35764. UTIF.toRGBA8 = function(out)
  35765. {
  35766. var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;
  35767. var img = new Uint8Array(area*4);
  35768. // 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK
  35769. var intp = out["t262"][0], bps = (out["t258"]?Math.min(32,out["t258"][0]):1), isLE = out.isLE ? 1 : 0;
  35770. //log("interpretation: ", intp, "bps", bps, out);
  35771. if(false) {}
  35772. else if(intp==0)
  35773. {
  35774. var bpl = Math.ceil(bps*w/8);
  35775. for(var y=0; y<h; y++) {
  35776. var off = y*bpl, io = y*w;
  35777. if(bps== 1) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; }
  35778. if(bps== 4) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; }
  35779. if(bps== 8) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+i]; img[qi]=img[qi+1]=img[qi+2]=255-px; img[qi+3]=255; }
  35780. }
  35781. }
  35782. else if(intp==1)
  35783. {
  35784. var bpl = Math.ceil(bps*w/8);
  35785. for(var y=0; y<h; y++) {
  35786. var off = y*bpl, io = y*w;
  35787. if(bps== 1) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; }
  35788. if(bps== 2) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; }
  35789. if(bps== 8) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+i]; img[qi]=img[qi+1]=img[qi+2]= px; img[qi+3]=255; }
  35790. if(bps==16) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+(2*i+isLE)]; img[qi]=img[qi+1]=img[qi+2]= Math.min(255,px); img[qi+3]=255; } // ladoga.tif
  35791. }
  35792. }
  35793. else if(intp==2)
  35794. {
  35795. if(bps== 8) // this needs to be simplified ... how many channels are there???
  35796. {
  35797. if(out["t338"])
  35798. {
  35799. if(out["t338"][0]>0) for(var i=0; i<qarea; i++) img[i] = data[i]; // sometimes t338 is 1 or 2 in case of Alpha
  35800. else for(var i=0; i<qarea; i+=4) { img[i] = data[i]; img[i+1] = data[i+1]; img[i+2] = data[i+2]; img[i+3] = 255; }
  35801. }
  35802. else
  35803. {
  35804. var smpls = out["t258"]?out["t258"].length : 3;
  35805. if(smpls==4) for(var i=0; i<qarea; i++) img[i] = data[i];
  35806. if(smpls==3) for(var i=0; i< area; i++) { var qi=i<<2, ti=i*3; img[qi]=data[ti]; img[qi+1]=data[ti+1]; img[qi+2]=data[ti+2]; img[qi+3]=255; }
  35807. }
  35808. }
  35809. else // 3x 16-bit channel
  35810. for(var i=0; i<area; i++) { var qi=i<<2, ti=i*6; img[qi]=data[ti]; img[qi+1]=data[ti+2]; img[qi+2]=data[ti+4]; img[qi+3]=255; }
  35811. }
  35812. else if(intp==3)
  35813. {
  35814. var map = out["t320"];
  35815. for(var i=0; i<area; i++) { var qi=i<<2, mi=data[i]; img[qi]=(map[mi]>>8); img[qi+1]=(map[256+mi]>>8); img[qi+2]=(map[512+mi]>>8); img[qi+3]=255; }
  35816. }
  35817. else if(intp==5)
  35818. {
  35819. var smpls = out["t258"]?out["t258"].length : 4;
  35820. var gotAlpha = smpls>4 ? 1 : 0;
  35821. for(var i=0; i<area; i++) {
  35822. var qi=i<<2, si=i*smpls; var C=255-data[si], M=255-data[si+1], Y=255-data[si+2], K=(255-data[si+3])*(1/255);
  35823. img[qi]=~~(C*K+0.5); img[qi+1]=~~(M*K+0.5); img[qi+2]=~~(Y*K+0.5); img[qi+3]=255*(1-gotAlpha)+data[si+4]*gotAlpha;
  35824. }
  35825. }
  35826. else log("Unknown Photometric interpretation: "+intp);
  35827. return img;
  35828. }
  35829. UTIF.replaceIMG = function()
  35830. {
  35831. var imgs = document.getElementsByTagName("img");
  35832. for (var i=0; i<imgs.length; i++)
  35833. {
  35834. var img=imgs[i], src=img.getAttribute("src"); if(src==null) continue;
  35835. var suff=src.split(".").pop().toLowerCase();
  35836. if(suff!="tif" && suff!="tiff") continue;
  35837. var xhr = new XMLHttpRequest(); UTIF._xhrs.push(xhr); UTIF._imgs.push(img);
  35838. xhr.open("GET", src); xhr.responseType = "arraybuffer";
  35839. xhr.onload = UTIF._imgLoaded; xhr.send();
  35840. }
  35841. }
  35842. UTIF._xhrs = []; UTIF._imgs = [];
  35843. UTIF._imgLoaded = function(e)
  35844. {
  35845. var buff = e.target.response;
  35846. var ifds = UTIF.decode(buff), page = ifds[0]; UTIF.decodeImages(buff, ifds);
  35847. var rgba = UTIF.toRGBA8(page), w=page.width, h=page.height;
  35848. var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind];
  35849. UTIF._xhrs.splice(ind,1); UTIF._imgs.splice(ind,1);
  35850. var cnv = document.createElement("canvas"); cnv.width=w; cnv.height=h;
  35851. var ctx = cnv.getContext("2d"), imgd = ctx.createImageData(w,h);
  35852. for(var i=0; i<rgba.length; i++) imgd.data[i]=rgba[i]; ctx.putImageData(imgd,0,0);
  35853. var attr = ["style","class","id"];
  35854. for(var i=0; i<attr.length; i++) cnv.setAttribute(attr[i], img.getAttribute(attr[i]));
  35855. img.parentNode.replaceChild(cnv,img);
  35856. }
  35857. UTIF._binBE =
  35858. {
  35859. nextZero : function(data, o) { while(data[o]!=0) o++; return o; },
  35860. readUshort : function(buff, p) { return (buff[p]<< 8) | buff[p+1]; },
  35861. readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+1]; a[1]=buff[p+0]; return UTIF._binBE. i16[0]; },
  35862. readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE. i32[0]; },
  35863. readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE.ui32[0]; },
  35864. readASCII : function(buff, p, l) { var s = ""; for(var i=0; i<l; i++) s += String.fromCharCode(buff[p+i]); return s; },
  35865. readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+3-i]; return UTIF._binBE.fl32[0]; },
  35866. readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+7-i]; return UTIF._binBE.fl64[0]; },
  35867. writeUshort: function(buff, p, n) { buff[p] = (n>> 8)&255; buff[p+1] = n&255; },
  35868. writeUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; },
  35869. writeASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); },
  35870. writeDouble: function(buff, p, n)
  35871. {
  35872. UTIF._binBE.fl64[0] = n;
  35873. for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];
  35874. }
  35875. }
  35876. UTIF._binBE.ui8 = new Uint8Array (8);
  35877. UTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer);
  35878. UTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer);
  35879. UTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer);
  35880. UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);
  35881. UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);
  35882. UTIF._binLE =
  35883. {
  35884. nextZero : UTIF._binBE.nextZero,
  35885. readUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; },
  35886. readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; return UTIF._binBE. i16[0]; },
  35887. readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; },
  35888. readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; },
  35889. readASCII : UTIF._binBE.readASCII,
  35890. readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; },
  35891. readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; }
  35892. }
  35893. UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff)
  35894. {
  35895. //log("copyTile", tw, th, w, h, xoff, yoff);
  35896. var xlim = Math.min(tw, w-xoff);
  35897. var ylim = Math.min(th, h-yoff);
  35898. for(var y=0; y<ylim; y++)
  35899. {
  35900. var tof = (yoff+y)*w+xoff;
  35901. var sof = y*tw;
  35902. for(var x=0; x<xlim; x++) b[tof+x] = tb[sof+x];
  35903. }
  35904. }
  35905. })(UTIF, pako);
  35906. })();
  35907. }).call(this,require('_process'))
  35908. },{"_process":312,"pako":265}],362:[function(require,module,exports){
  35909. (function (global){
  35910. /**
  35911. * Module exports.
  35912. */
  35913. module.exports = deprecate;
  35914. /**
  35915. * Mark that a method should not be used.
  35916. * Returns a modified function which warns once by default.
  35917. *
  35918. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  35919. *
  35920. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  35921. * will throw an Error when invoked.
  35922. *
  35923. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  35924. * will invoke `console.trace()` instead of `console.error()`.
  35925. *
  35926. * @param {Function} fn - the function to deprecate
  35927. * @param {String} msg - the string to print to the console when `fn` is invoked
  35928. * @returns {Function} a new "deprecated" version of `fn`
  35929. * @api public
  35930. */
  35931. function deprecate (fn, msg) {
  35932. if (config('noDeprecation')) {
  35933. return fn;
  35934. }
  35935. var warned = false;
  35936. function deprecated() {
  35937. if (!warned) {
  35938. if (config('throwDeprecation')) {
  35939. throw new Error(msg);
  35940. } else if (config('traceDeprecation')) {
  35941. console.trace(msg);
  35942. } else {
  35943. console.warn(msg);
  35944. }
  35945. warned = true;
  35946. }
  35947. return fn.apply(this, arguments);
  35948. }
  35949. return deprecated;
  35950. }
  35951. /**
  35952. * Checks `localStorage` for boolean values for the given `name`.
  35953. *
  35954. * @param {String} name
  35955. * @returns {Boolean}
  35956. * @api private
  35957. */
  35958. function config (name) {
  35959. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  35960. try {
  35961. if (!global.localStorage) return false;
  35962. } catch (_) {
  35963. return false;
  35964. }
  35965. var val = global.localStorage[name];
  35966. if (null == val) return false;
  35967. return String(val).toLowerCase() === 'true';
  35968. }
  35969. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  35970. },{}],363:[function(require,module,exports){
  35971. arguments[4][25][0].apply(exports,arguments)
  35972. },{"dup":25}],364:[function(require,module,exports){
  35973. arguments[4][26][0].apply(exports,arguments)
  35974. },{"dup":26}],365:[function(require,module,exports){
  35975. arguments[4][27][0].apply(exports,arguments)
  35976. },{"./support/isBuffer":364,"_process":312,"dup":27,"inherits":363}],366:[function(require,module,exports){
  35977. "use strict";
  35978. var window = require("global/window")
  35979. var isFunction = require("is-function")
  35980. var parseHeaders = require("parse-headers")
  35981. var xtend = require("xtend")
  35982. module.exports = createXHR
  35983. // Allow use of default import syntax in TypeScript
  35984. module.exports.default = createXHR;
  35985. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  35986. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  35987. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  35988. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  35989. options = initParams(uri, options, callback)
  35990. options.method = method.toUpperCase()
  35991. return _createXHR(options)
  35992. }
  35993. })
  35994. function forEachArray(array, iterator) {
  35995. for (var i = 0; i < array.length; i++) {
  35996. iterator(array[i])
  35997. }
  35998. }
  35999. function isEmpty(obj){
  36000. for(var i in obj){
  36001. if(obj.hasOwnProperty(i)) return false
  36002. }
  36003. return true
  36004. }
  36005. function initParams(uri, options, callback) {
  36006. var params = uri
  36007. if (isFunction(options)) {
  36008. callback = options
  36009. if (typeof uri === "string") {
  36010. params = {uri:uri}
  36011. }
  36012. } else {
  36013. params = xtend(options, {uri: uri})
  36014. }
  36015. params.callback = callback
  36016. return params
  36017. }
  36018. function createXHR(uri, options, callback) {
  36019. options = initParams(uri, options, callback)
  36020. return _createXHR(options)
  36021. }
  36022. function _createXHR(options) {
  36023. if(typeof options.callback === "undefined"){
  36024. throw new Error("callback argument missing")
  36025. }
  36026. var called = false
  36027. var callback = function cbOnce(err, response, body){
  36028. if(!called){
  36029. called = true
  36030. options.callback(err, response, body)
  36031. }
  36032. }
  36033. function readystatechange() {
  36034. if (xhr.readyState === 4) {
  36035. setTimeout(loadFunc, 0)
  36036. }
  36037. }
  36038. function getBody() {
  36039. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  36040. var body = undefined
  36041. if (xhr.response) {
  36042. body = xhr.response
  36043. } else {
  36044. body = xhr.responseText || getXml(xhr)
  36045. }
  36046. if (isJson) {
  36047. try {
  36048. body = JSON.parse(body)
  36049. } catch (e) {}
  36050. }
  36051. return body
  36052. }
  36053. function errorFunc(evt) {
  36054. clearTimeout(timeoutTimer)
  36055. if(!(evt instanceof Error)){
  36056. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  36057. }
  36058. evt.statusCode = 0
  36059. return callback(evt, failureResponse)
  36060. }
  36061. // will load the data & process the response in a special response object
  36062. function loadFunc() {
  36063. if (aborted) return
  36064. var status
  36065. clearTimeout(timeoutTimer)
  36066. if(options.useXDR && xhr.status===undefined) {
  36067. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  36068. status = 200
  36069. } else {
  36070. status = (xhr.status === 1223 ? 204 : xhr.status)
  36071. }
  36072. var response = failureResponse
  36073. var err = null
  36074. if (status !== 0){
  36075. response = {
  36076. body: getBody(),
  36077. statusCode: status,
  36078. method: method,
  36079. headers: {},
  36080. url: uri,
  36081. rawRequest: xhr
  36082. }
  36083. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  36084. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  36085. }
  36086. } else {
  36087. err = new Error("Internal XMLHttpRequest Error")
  36088. }
  36089. return callback(err, response, response.body)
  36090. }
  36091. var xhr = options.xhr || null
  36092. if (!xhr) {
  36093. if (options.cors || options.useXDR) {
  36094. xhr = new createXHR.XDomainRequest()
  36095. }else{
  36096. xhr = new createXHR.XMLHttpRequest()
  36097. }
  36098. }
  36099. var key
  36100. var aborted
  36101. var uri = xhr.url = options.uri || options.url
  36102. var method = xhr.method = options.method || "GET"
  36103. var body = options.body || options.data
  36104. var headers = xhr.headers = options.headers || {}
  36105. var sync = !!options.sync
  36106. var isJson = false
  36107. var timeoutTimer
  36108. var failureResponse = {
  36109. body: undefined,
  36110. headers: {},
  36111. statusCode: 0,
  36112. method: method,
  36113. url: uri,
  36114. rawRequest: xhr
  36115. }
  36116. if ("json" in options && options.json !== false) {
  36117. isJson = true
  36118. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  36119. if (method !== "GET" && method !== "HEAD") {
  36120. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  36121. body = JSON.stringify(options.json === true ? body : options.json)
  36122. }
  36123. }
  36124. xhr.onreadystatechange = readystatechange
  36125. xhr.onload = loadFunc
  36126. xhr.onerror = errorFunc
  36127. // IE9 must have onprogress be set to a unique function.
  36128. xhr.onprogress = function () {
  36129. // IE must die
  36130. }
  36131. xhr.onabort = function(){
  36132. aborted = true;
  36133. }
  36134. xhr.ontimeout = errorFunc
  36135. xhr.open(method, uri, !sync, options.username, options.password)
  36136. //has to be after open
  36137. if(!sync) {
  36138. xhr.withCredentials = !!options.withCredentials
  36139. }
  36140. // Cannot set timeout with sync request
  36141. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  36142. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  36143. if (!sync && options.timeout > 0 ) {
  36144. timeoutTimer = setTimeout(function(){
  36145. if (aborted) return
  36146. aborted = true//IE9 may still call readystatechange
  36147. xhr.abort("timeout")
  36148. var e = new Error("XMLHttpRequest timeout")
  36149. e.code = "ETIMEDOUT"
  36150. errorFunc(e)
  36151. }, options.timeout )
  36152. }
  36153. if (xhr.setRequestHeader) {
  36154. for(key in headers){
  36155. if(headers.hasOwnProperty(key)){
  36156. xhr.setRequestHeader(key, headers[key])
  36157. }
  36158. }
  36159. } else if (options.headers && !isEmpty(options.headers)) {
  36160. throw new Error("Headers cannot be set on an XDomainRequest object")
  36161. }
  36162. if ("responseType" in options) {
  36163. xhr.responseType = options.responseType
  36164. }
  36165. if ("beforeSend" in options &&
  36166. typeof options.beforeSend === "function"
  36167. ) {
  36168. options.beforeSend(xhr)
  36169. }
  36170. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  36171. // XMLHttpRequest spec says to pass null as body to indicate no body
  36172. // See https://github.com/naugtur/xhr/issues/100.
  36173. xhr.send(body || null)
  36174. return xhr
  36175. }
  36176. function getXml(xhr) {
  36177. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  36178. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  36179. try {
  36180. if (xhr.responseType === "document") {
  36181. return xhr.responseXML
  36182. }
  36183. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  36184. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  36185. return xhr.responseXML
  36186. }
  36187. } catch (e) {}
  36188. return null
  36189. }
  36190. function noop() {}
  36191. },{"global/window":251,"is-function":257,"parse-headers":285,"xtend":368}],367:[function(require,module,exports){
  36192. module.exports = (function xmlparser() {
  36193. //common browsers
  36194. if (typeof self.DOMParser !== 'undefined') {
  36195. return function(str) {
  36196. var parser = new self.DOMParser()
  36197. return parser.parseFromString(str, 'application/xml')
  36198. }
  36199. }
  36200. //IE8 fallback
  36201. if (typeof self.ActiveXObject !== 'undefined'
  36202. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  36203. return function(str) {
  36204. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  36205. xmlDoc.async = "false"
  36206. xmlDoc.loadXML(str)
  36207. return xmlDoc
  36208. }
  36209. }
  36210. //last resort fallback
  36211. return function(str) {
  36212. var div = document.createElement('div')
  36213. div.innerHTML = str
  36214. return div
  36215. }
  36216. })()
  36217. },{}],368:[function(require,module,exports){
  36218. module.exports = extend
  36219. var hasOwnProperty = Object.prototype.hasOwnProperty;
  36220. function extend() {
  36221. var target = {}
  36222. for (var i = 0; i < arguments.length; i++) {
  36223. var source = arguments[i]
  36224. for (var key in source) {
  36225. if (hasOwnProperty.call(source, key)) {
  36226. target[key] = source[key]
  36227. }
  36228. }
  36229. }
  36230. return target
  36231. }
  36232. },{}],369:[function(require,module,exports){
  36233. "use strict";
  36234. Object.defineProperty(exports, "__esModule", {
  36235. value: true
  36236. });
  36237. exports.srcOver = srcOver;
  36238. exports.dstOver = dstOver;
  36239. exports.multiply = multiply;
  36240. exports.screen = screen;
  36241. exports.overlay = overlay;
  36242. exports.darken = darken;
  36243. exports.lighten = lighten;
  36244. exports.hardLight = hardLight;
  36245. exports.difference = difference;
  36246. exports.exclusion = exclusion;
  36247. function srcOver(src, dst) {
  36248. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36249. src.a *= ops;
  36250. var a = dst.a + src.a - dst.a * src.a;
  36251. var r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a;
  36252. var g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a;
  36253. var b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a;
  36254. return {
  36255. r: r,
  36256. g: g,
  36257. b: b,
  36258. a: a
  36259. };
  36260. }
  36261. function dstOver(src, dst) {
  36262. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36263. src.a *= ops;
  36264. var a = dst.a + src.a - dst.a * src.a;
  36265. var r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a;
  36266. var g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a;
  36267. var b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a;
  36268. return {
  36269. r: r,
  36270. g: g,
  36271. b: b,
  36272. a: a
  36273. };
  36274. }
  36275. function multiply(src, dst) {
  36276. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36277. src.a *= ops;
  36278. var a = dst.a + src.a - dst.a * src.a;
  36279. var sra = src.r * src.a;
  36280. var sga = src.g * src.a;
  36281. var sba = src.b * src.a;
  36282. var dra = dst.r * dst.a;
  36283. var dga = dst.g * dst.a;
  36284. var dba = dst.b * dst.a;
  36285. var r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
  36286. var g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
  36287. var b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
  36288. return {
  36289. r: r,
  36290. g: g,
  36291. b: b,
  36292. a: a
  36293. };
  36294. }
  36295. function screen(src, dst) {
  36296. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36297. src.a *= ops;
  36298. var a = dst.a + src.a - dst.a * src.a;
  36299. var sra = src.r * src.a;
  36300. var sga = src.g * src.a;
  36301. var sba = src.b * src.a;
  36302. var dra = dst.r * dst.a;
  36303. var dga = dst.g * dst.a;
  36304. var dba = dst.b * dst.a;
  36305. var r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
  36306. var g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
  36307. var b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
  36308. return {
  36309. r: r,
  36310. g: g,
  36311. b: b,
  36312. a: a
  36313. };
  36314. }
  36315. function overlay(src, dst) {
  36316. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36317. src.a *= ops;
  36318. var a = dst.a + src.a - dst.a * src.a;
  36319. var sra = src.r * src.a;
  36320. var sga = src.g * src.a;
  36321. var sba = src.b * src.a;
  36322. var dra = dst.r * dst.a;
  36323. var dga = dst.g * dst.a;
  36324. var dba = dst.b * dst.a;
  36325. var r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
  36326. var g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
  36327. var b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
  36328. return {
  36329. r: r,
  36330. g: g,
  36331. b: b,
  36332. a: a
  36333. };
  36334. }
  36335. function darken(src, dst) {
  36336. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36337. src.a *= ops;
  36338. var a = dst.a + src.a - dst.a * src.a;
  36339. var sra = src.r * src.a;
  36340. var sga = src.g * src.a;
  36341. var sba = src.b * src.a;
  36342. var dra = dst.r * dst.a;
  36343. var dga = dst.g * dst.a;
  36344. var dba = dst.b * dst.a;
  36345. var r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
  36346. var g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
  36347. var b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
  36348. return {
  36349. r: r,
  36350. g: g,
  36351. b: b,
  36352. a: a
  36353. };
  36354. }
  36355. function lighten(src, dst) {
  36356. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36357. src.a *= ops;
  36358. var a = dst.a + src.a - dst.a * src.a;
  36359. var sra = src.r * src.a;
  36360. var sga = src.g * src.a;
  36361. var sba = src.b * src.a;
  36362. var dra = dst.r * dst.a;
  36363. var dga = dst.g * dst.a;
  36364. var dba = dst.b * dst.a;
  36365. var r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
  36366. var g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
  36367. var b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
  36368. return {
  36369. r: r,
  36370. g: g,
  36371. b: b,
  36372. a: a
  36373. };
  36374. }
  36375. function hardLight(src, dst) {
  36376. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36377. src.a *= ops;
  36378. var a = dst.a + src.a - dst.a * src.a;
  36379. var sra = src.r * src.a;
  36380. var sga = src.g * src.a;
  36381. var sba = src.b * src.a;
  36382. var dra = dst.r * dst.a;
  36383. var dga = dst.g * dst.a;
  36384. var dba = dst.b * dst.a;
  36385. var r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
  36386. var g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
  36387. var b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
  36388. return {
  36389. r: r,
  36390. g: g,
  36391. b: b,
  36392. a: a
  36393. };
  36394. }
  36395. function difference(src, dst) {
  36396. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36397. src.a *= ops;
  36398. var a = dst.a + src.a - dst.a * src.a;
  36399. var sra = src.r * src.a;
  36400. var sga = src.g * src.a;
  36401. var sba = src.b * src.a;
  36402. var dra = dst.r * dst.a;
  36403. var dga = dst.g * dst.a;
  36404. var dba = dst.b * dst.a;
  36405. var r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a;
  36406. var g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a;
  36407. var b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a;
  36408. return {
  36409. r: r,
  36410. g: g,
  36411. b: b,
  36412. a: a
  36413. };
  36414. }
  36415. function exclusion(src, dst) {
  36416. var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  36417. src.a *= ops;
  36418. var a = dst.a + src.a - dst.a * src.a;
  36419. var sra = src.r * src.a;
  36420. var sga = src.g * src.a;
  36421. var sba = src.b * src.a;
  36422. var dra = dst.r * dst.a;
  36423. var dga = dst.g * dst.a;
  36424. var dba = dst.b * dst.a;
  36425. var r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
  36426. var g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
  36427. var b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
  36428. return {
  36429. r: r,
  36430. g: g,
  36431. b: b,
  36432. a: a
  36433. };
  36434. }
  36435. },{}],370:[function(require,module,exports){
  36436. "use strict";
  36437. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
  36438. Object.defineProperty(exports, "__esModule", {
  36439. value: true
  36440. });
  36441. exports["default"] = composite;
  36442. var _utils = require("@jimp/utils");
  36443. var constants = _interopRequireWildcard(require("../constants"));
  36444. var compositeModes = _interopRequireWildcard(require("./composite-modes"));
  36445. /**
  36446. * Composites a source image over to this image respecting alpha channels
  36447. * @param {Jimp} src the source Jimp instance
  36448. * @param {number} x the x position to blit the image
  36449. * @param {number} y the y position to blit the image
  36450. * @param {object} options determine what mode to use
  36451. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  36452. * @returns {Jimp} this for chaining of methods
  36453. */
  36454. function composite(src, x, y) {
  36455. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  36456. var cb = arguments.length > 4 ? arguments[4] : undefined;
  36457. if (typeof options === 'function') {
  36458. cb = options;
  36459. options = {};
  36460. }
  36461. if (!(src instanceof this.constructor)) {
  36462. return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
  36463. }
  36464. if (typeof x !== 'number' || typeof y !== 'number') {
  36465. return _utils.throwError.call(this, 'x and y must be numbers', cb);
  36466. }
  36467. var _options = options,
  36468. mode = _options.mode,
  36469. opacitySource = _options.opacitySource,
  36470. opacityDest = _options.opacityDest;
  36471. if (!mode) {
  36472. mode = constants.BLEND_SOURCE_OVER;
  36473. }
  36474. if (typeof opacitySource !== 'number' || opacitySource < 0 || opacitySource > 1) {
  36475. opacitySource = 1.0;
  36476. }
  36477. if (typeof opacityDest !== 'number' || opacityDest < 0 || opacityDest > 1) {
  36478. opacityDest = 1.0;
  36479. }
  36480. var blendmode = compositeModes[mode]; // round input
  36481. x = Math.round(x);
  36482. y = Math.round(y);
  36483. var baseImage = this;
  36484. if (opacityDest !== 1.0) {
  36485. baseImage.opacity(opacityDest);
  36486. }
  36487. src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {
  36488. var dstIdx = baseImage.getPixelIndex(x + sx, y + sy, constants.EDGE_CROP);
  36489. var blended = blendmode({
  36490. r: this.bitmap.data[idx + 0] / 255,
  36491. g: this.bitmap.data[idx + 1] / 255,
  36492. b: this.bitmap.data[idx + 2] / 255,
  36493. a: this.bitmap.data[idx + 3] / 255
  36494. }, {
  36495. r: baseImage.bitmap.data[dstIdx + 0] / 255,
  36496. g: baseImage.bitmap.data[dstIdx + 1] / 255,
  36497. b: baseImage.bitmap.data[dstIdx + 2] / 255,
  36498. a: baseImage.bitmap.data[dstIdx + 3] / 255
  36499. }, opacitySource);
  36500. baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(blended.r * 255);
  36501. baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(blended.g * 255);
  36502. baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(blended.b * 255);
  36503. baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(blended.a * 255);
  36504. });
  36505. if ((0, _utils.isNodePattern)(cb)) {
  36506. cb.call(this, null, this);
  36507. }
  36508. return this;
  36509. }
  36510. module.exports = exports.default;
  36511. },{"../constants":371,"./composite-modes":369,"@babel/runtime/helpers/interopRequireWildcard":11,"@jimp/utils":414}],371:[function(require,module,exports){
  36512. "use strict";
  36513. Object.defineProperty(exports, "__esModule", {
  36514. value: true
  36515. });
  36516. exports.EDGE_CROP = exports.EDGE_WRAP = exports.EDGE_EXTEND = exports.BLEND_EXCLUSION = exports.BLEND_DIFFERENCE = exports.BLEND_HARDLIGHT = exports.BLEND_LIGHTEN = exports.BLEND_DARKEN = exports.BLEND_OVERLAY = exports.BLEND_SCREEN = exports.BLEND_MULTIPLY = exports.BLEND_DESTINATION_OVER = exports.BLEND_SOURCE_OVER = exports.VERTICAL_ALIGN_BOTTOM = exports.VERTICAL_ALIGN_MIDDLE = exports.VERTICAL_ALIGN_TOP = exports.HORIZONTAL_ALIGN_RIGHT = exports.HORIZONTAL_ALIGN_CENTER = exports.HORIZONTAL_ALIGN_LEFT = exports.AUTO = void 0;
  36517. // used to auto resizing etc.
  36518. var AUTO = -1; // Align modes for cover, contain, bit masks
  36519. exports.AUTO = AUTO;
  36520. var HORIZONTAL_ALIGN_LEFT = 1;
  36521. exports.HORIZONTAL_ALIGN_LEFT = HORIZONTAL_ALIGN_LEFT;
  36522. var HORIZONTAL_ALIGN_CENTER = 2;
  36523. exports.HORIZONTAL_ALIGN_CENTER = HORIZONTAL_ALIGN_CENTER;
  36524. var HORIZONTAL_ALIGN_RIGHT = 4;
  36525. exports.HORIZONTAL_ALIGN_RIGHT = HORIZONTAL_ALIGN_RIGHT;
  36526. var VERTICAL_ALIGN_TOP = 8;
  36527. exports.VERTICAL_ALIGN_TOP = VERTICAL_ALIGN_TOP;
  36528. var VERTICAL_ALIGN_MIDDLE = 16;
  36529. exports.VERTICAL_ALIGN_MIDDLE = VERTICAL_ALIGN_MIDDLE;
  36530. var VERTICAL_ALIGN_BOTTOM = 32; // blend modes
  36531. exports.VERTICAL_ALIGN_BOTTOM = VERTICAL_ALIGN_BOTTOM;
  36532. var BLEND_SOURCE_OVER = 'srcOver';
  36533. exports.BLEND_SOURCE_OVER = BLEND_SOURCE_OVER;
  36534. var BLEND_DESTINATION_OVER = 'dstOver';
  36535. exports.BLEND_DESTINATION_OVER = BLEND_DESTINATION_OVER;
  36536. var BLEND_MULTIPLY = 'multiply';
  36537. exports.BLEND_MULTIPLY = BLEND_MULTIPLY;
  36538. var BLEND_SCREEN = 'screen';
  36539. exports.BLEND_SCREEN = BLEND_SCREEN;
  36540. var BLEND_OVERLAY = 'overlay';
  36541. exports.BLEND_OVERLAY = BLEND_OVERLAY;
  36542. var BLEND_DARKEN = 'darken';
  36543. exports.BLEND_DARKEN = BLEND_DARKEN;
  36544. var BLEND_LIGHTEN = 'lighten';
  36545. exports.BLEND_LIGHTEN = BLEND_LIGHTEN;
  36546. var BLEND_HARDLIGHT = 'hardLight';
  36547. exports.BLEND_HARDLIGHT = BLEND_HARDLIGHT;
  36548. var BLEND_DIFFERENCE = 'difference';
  36549. exports.BLEND_DIFFERENCE = BLEND_DIFFERENCE;
  36550. var BLEND_EXCLUSION = 'exclusion'; // Edge Handling
  36551. exports.BLEND_EXCLUSION = BLEND_EXCLUSION;
  36552. var EDGE_EXTEND = 1;
  36553. exports.EDGE_EXTEND = EDGE_EXTEND;
  36554. var EDGE_WRAP = 2;
  36555. exports.EDGE_WRAP = EDGE_WRAP;
  36556. var EDGE_CROP = 3;
  36557. exports.EDGE_CROP = EDGE_CROP;
  36558. },{}],372:[function(require,module,exports){
  36559. (function (Buffer){
  36560. "use strict";
  36561. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
  36562. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  36563. require("core-js/modules/es.array.concat");
  36564. require("core-js/modules/es.array.find");
  36565. require("core-js/modules/es.array.for-each");
  36566. require("core-js/modules/es.array.index-of");
  36567. require("core-js/modules/es.array.iterator");
  36568. require("core-js/modules/es.array.join");
  36569. require("core-js/modules/es.array-buffer.slice");
  36570. require("core-js/modules/es.date.to-string");
  36571. require("core-js/modules/es.number.constructor");
  36572. require("core-js/modules/es.object.assign");
  36573. require("core-js/modules/es.object.entries");
  36574. require("core-js/modules/es.object.to-string");
  36575. require("core-js/modules/es.parse-int");
  36576. require("core-js/modules/es.promise");
  36577. require("core-js/modules/es.regexp.exec");
  36578. require("core-js/modules/es.regexp.to-string");
  36579. require("core-js/modules/es.string.match");
  36580. require("core-js/modules/es.string.replace");
  36581. require("core-js/modules/es.typed-array.uint8-array");
  36582. require("core-js/modules/es.typed-array.uint8-clamped-array");
  36583. require("core-js/modules/es.typed-array.copy-within");
  36584. require("core-js/modules/es.typed-array.every");
  36585. require("core-js/modules/es.typed-array.fill");
  36586. require("core-js/modules/es.typed-array.filter");
  36587. require("core-js/modules/es.typed-array.find");
  36588. require("core-js/modules/es.typed-array.find-index");
  36589. require("core-js/modules/es.typed-array.for-each");
  36590. require("core-js/modules/es.typed-array.includes");
  36591. require("core-js/modules/es.typed-array.index-of");
  36592. require("core-js/modules/es.typed-array.iterator");
  36593. require("core-js/modules/es.typed-array.join");
  36594. require("core-js/modules/es.typed-array.last-index-of");
  36595. require("core-js/modules/es.typed-array.map");
  36596. require("core-js/modules/es.typed-array.reduce");
  36597. require("core-js/modules/es.typed-array.reduce-right");
  36598. require("core-js/modules/es.typed-array.reverse");
  36599. require("core-js/modules/es.typed-array.set");
  36600. require("core-js/modules/es.typed-array.slice");
  36601. require("core-js/modules/es.typed-array.some");
  36602. require("core-js/modules/es.typed-array.sort");
  36603. require("core-js/modules/es.typed-array.subarray");
  36604. require("core-js/modules/es.typed-array.to-locale-string");
  36605. require("core-js/modules/es.typed-array.to-string");
  36606. require("core-js/modules/web.dom-collections.for-each");
  36607. require("core-js/modules/web.timers");
  36608. Object.defineProperty(exports, "__esModule", {
  36609. value: true
  36610. });
  36611. exports.addConstants = addConstants;
  36612. exports.addJimpMethods = addJimpMethods;
  36613. exports.jimpEvMethod = jimpEvMethod;
  36614. exports.jimpEvChange = jimpEvChange;
  36615. Object.defineProperty(exports, "addType", {
  36616. enumerable: true,
  36617. get: function get() {
  36618. return MIME.addType;
  36619. }
  36620. });
  36621. exports["default"] = void 0;
  36622. var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct"));
  36623. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
  36624. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  36625. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  36626. var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
  36627. var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
  36628. var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
  36629. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  36630. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  36631. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  36632. var _fs = _interopRequireDefault(require("fs"));
  36633. var _path = _interopRequireDefault(require("path"));
  36634. var _events = _interopRequireDefault(require("events"));
  36635. var _utils = require("@jimp/utils");
  36636. var _anyBase = _interopRequireDefault(require("any-base"));
  36637. var _mkdirp = _interopRequireDefault(require("mkdirp"));
  36638. var _pixelmatch = _interopRequireDefault(require("pixelmatch"));
  36639. var _tinycolor = _interopRequireDefault(require("tinycolor2"));
  36640. var _phash = _interopRequireDefault(require("./modules/phash"));
  36641. var _request = _interopRequireDefault(require("./request"));
  36642. var _composite = _interopRequireDefault(require("./composite"));
  36643. var _promisify = _interopRequireDefault(require("./utils/promisify"));
  36644. var MIME = _interopRequireWildcard(require("./utils/mime"));
  36645. var _imageBitmap = require("./utils/image-bitmap");
  36646. var constants = _interopRequireWildcard(require("./constants"));
  36647. var alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'; // an array storing the maximum string length of hashes at various bases
  36648. // 0 and 1 do not exist as possible hash lengths
  36649. var maxHashLength = [NaN, NaN];
  36650. for (var i = 2; i < 65; i++) {
  36651. var maxHash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, i))(new Array(64 + 1).join('1'));
  36652. maxHashLength.push(maxHash.length);
  36653. } // no operation
  36654. function noop() {} // error checking methods
  36655. function isArrayBuffer(test) {
  36656. return Object.prototype.toString.call(test).toLowerCase().indexOf('arraybuffer') > -1;
  36657. } // Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion,
  36658. // But this function is not useful when running in node directly
  36659. function bufferFromArrayBuffer(arrayBuffer) {
  36660. var buffer = Buffer.alloc(arrayBuffer.byteLength);
  36661. var view = new Uint8Array(arrayBuffer);
  36662. for (var _i = 0; _i < buffer.length; ++_i) {
  36663. buffer[_i] = view[_i];
  36664. }
  36665. return buffer;
  36666. }
  36667. function loadFromURL(options, cb) {
  36668. (0, _request["default"])(options, function (err, response, data) {
  36669. if (err) {
  36670. return cb(err);
  36671. }
  36672. if ('headers' in response && 'location' in response.headers) {
  36673. options.url = response.headers.location;
  36674. return loadFromURL(options, cb);
  36675. }
  36676. if ((0, _typeof2["default"])(data) === 'object' && Buffer.isBuffer(data)) {
  36677. return cb(null, data);
  36678. }
  36679. var msg = 'Could not load Buffer from <' + options.url + '> ' + '(HTTP: ' + response.statusCode + ')';
  36680. return new Error(msg);
  36681. });
  36682. }
  36683. function loadBufferFromPath(src, cb) {
  36684. if (_fs["default"] && typeof _fs["default"].readFile === 'function' && !src.match(/^(http|ftp)s?:\/\/./)) {
  36685. _fs["default"].readFile(src, cb);
  36686. } else {
  36687. loadFromURL({
  36688. url: src
  36689. }, cb);
  36690. }
  36691. }
  36692. function isRawRGBAData(obj) {
  36693. return obj && (0, _typeof2["default"])(obj) === 'object' && typeof obj.width === 'number' && typeof obj.height === 'number' && (Buffer.isBuffer(obj.data) || obj.data instanceof Uint8Array || typeof Uint8ClampedArray === 'function' && obj.data instanceof Uint8ClampedArray) && (obj.data.length === obj.width * obj.height * 4 || obj.data.length === obj.width * obj.height * 3);
  36694. }
  36695. function makeRGBABufferFromRGB(buffer) {
  36696. if (buffer.length % 3 !== 0) {
  36697. throw new Error('Buffer length is incorrect');
  36698. }
  36699. var rgbaBuffer = Buffer.allocUnsafe(buffer.length / 3 * 4);
  36700. var j = 0;
  36701. for (var _i2 = 0; _i2 < buffer.length; _i2++) {
  36702. rgbaBuffer[j] = buffer[_i2];
  36703. if ((_i2 + 1) % 3 === 0) {
  36704. rgbaBuffer[++j] = 255;
  36705. }
  36706. j++;
  36707. }
  36708. return rgbaBuffer;
  36709. }
  36710. var emptyBitmap = {
  36711. data: null,
  36712. width: null,
  36713. height: null
  36714. };
  36715. /**
  36716. * Jimp constructor (from a file)
  36717. * @param path a path to the image
  36718. * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
  36719. */
  36720. /**
  36721. * Jimp constructor (from a url with options)
  36722. * @param options { url, otherOptions}
  36723. * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
  36724. */
  36725. /**
  36726. * Jimp constructor (from another Jimp image or raw image data)
  36727. * @param image a Jimp image to clone
  36728. * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap
  36729. */
  36730. /**
  36731. * Jimp constructor (from a Buffer)
  36732. * @param data a Buffer containing the image data
  36733. * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap
  36734. */
  36735. /**
  36736. * Jimp constructor (to generate a new image)
  36737. * @param w the width of the image
  36738. * @param h the height of the image
  36739. * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
  36740. */
  36741. /**
  36742. * Jimp constructor (to generate a new image)
  36743. * @param w the width of the image
  36744. * @param h the height of the image
  36745. * @param background color to fill the image with
  36746. * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
  36747. */
  36748. var Jimp =
  36749. /*#__PURE__*/
  36750. function (_EventEmitter) {
  36751. (0, _inherits2["default"])(Jimp, _EventEmitter);
  36752. // An object representing a bitmap in memory, comprising:
  36753. // - data: a buffer of the bitmap data
  36754. // - width: the width of the image in pixels
  36755. // - height: the height of the image in pixels
  36756. // Default colour to use for new pixels
  36757. // Default MIME is PNG
  36758. // Exif data for the image
  36759. // Whether Transparency supporting formats will be exported as RGB or RGBA
  36760. function Jimp() {
  36761. var _this;
  36762. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36763. args[_key] = arguments[_key];
  36764. }
  36765. (0, _classCallCheck2["default"])(this, Jimp);
  36766. _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Jimp).call(this));
  36767. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "bitmap", emptyBitmap);
  36768. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_background", 0x00000000);
  36769. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_originalMime", Jimp.MIME_PNG);
  36770. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_exif", null);
  36771. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_rgba", true);
  36772. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "writeAsync", function (path) {
  36773. return (0, _promisify["default"])(_this.write, (0, _assertThisInitialized2["default"])(_this), path);
  36774. });
  36775. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBase64Async", function (mime) {
  36776. return (0, _promisify["default"])(_this.getBase64, (0, _assertThisInitialized2["default"])(_this), mime);
  36777. });
  36778. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBuffer", _imageBitmap.getBuffer);
  36779. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBufferAsync", _imageBitmap.getBufferAsync);
  36780. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPixelColour", _this.getPixelColor);
  36781. (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setPixelColour", _this.setPixelColor);
  36782. var jimpInstance = (0, _assertThisInitialized2["default"])(_this);
  36783. var cb = noop;
  36784. if (isArrayBuffer(args[0])) {
  36785. args[0] = bufferFromArrayBuffer(args[0]);
  36786. }
  36787. function finish() {
  36788. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  36789. args[_key2] = arguments[_key2];
  36790. }
  36791. var err = args[0];
  36792. var evData = err || {};
  36793. evData.methodName = 'constructor';
  36794. setTimeout(function () {
  36795. var _cb;
  36796. // run on next tick.
  36797. if (err && cb === noop) {
  36798. jimpInstance.emitError('constructor', err);
  36799. } else if (!err) {
  36800. jimpInstance.emitMulti('constructor', 'initialized');
  36801. }
  36802. (_cb = cb).call.apply(_cb, [jimpInstance].concat(args));
  36803. }, 1);
  36804. }
  36805. if (typeof args[0] === 'number' && typeof args[1] === 'number' || parseInt(args[0], 10) && parseInt(args[1], 10)) {
  36806. // create a new image
  36807. var w = parseInt(args[0], 10);
  36808. var h = parseInt(args[1], 10);
  36809. cb = args[2]; // with a hex color
  36810. if (typeof args[2] === 'number') {
  36811. _this._background = args[2];
  36812. cb = args[3];
  36813. } // with a css color
  36814. if (typeof args[2] === 'string') {
  36815. _this._background = Jimp.cssColorToHex(args[2]);
  36816. cb = args[3];
  36817. }
  36818. if (typeof cb === 'undefined') {
  36819. cb = noop;
  36820. }
  36821. if (typeof cb !== 'function') {
  36822. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
  36823. }
  36824. _this.bitmap = {
  36825. data: Buffer.alloc(w * h * 4),
  36826. width: w,
  36827. height: h
  36828. };
  36829. for (var _i3 = 0; _i3 < _this.bitmap.data.length; _i3 += 4) {
  36830. _this.bitmap.data.writeUInt32BE(_this._background, _i3);
  36831. }
  36832. finish(null, (0, _assertThisInitialized2["default"])(_this));
  36833. } else if ((0, _typeof2["default"])(args[0]) === 'object' && args[0].url) {
  36834. cb = args[1] || noop;
  36835. if (typeof cb !== 'function') {
  36836. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
  36837. }
  36838. loadFromURL(args[0], function (err, data) {
  36839. if (err) {
  36840. return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish);
  36841. }
  36842. _this.parseBitmap(data, args[0].url, finish);
  36843. });
  36844. } else if (args[0] instanceof Jimp) {
  36845. // clone an existing Jimp
  36846. var original = args[0];
  36847. cb = args[1];
  36848. if (typeof cb === 'undefined') {
  36849. cb = noop;
  36850. }
  36851. if (typeof cb !== 'function') {
  36852. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
  36853. }
  36854. _this.bitmap = {
  36855. data: Buffer.from(original.bitmap.data),
  36856. width: original.bitmap.width,
  36857. height: original.bitmap.height
  36858. };
  36859. _this._quality = original._quality;
  36860. _this._deflateLevel = original._deflateLevel;
  36861. _this._deflateStrategy = original._deflateStrategy;
  36862. _this._filterType = original._filterType;
  36863. _this._rgba = original._rgba;
  36864. _this._background = original._background;
  36865. _this._originalMime = original._originalMime;
  36866. finish(null, (0, _assertThisInitialized2["default"])(_this));
  36867. } else if (isRawRGBAData(args[0])) {
  36868. var imageData = args[0];
  36869. cb = args[1] || noop;
  36870. var isRGBA = imageData.width * imageData.height * 4 === imageData.data.length;
  36871. var buffer = isRGBA ? Buffer.from(imageData.data) : makeRGBABufferFromRGB(imageData.data);
  36872. _this.bitmap = {
  36873. data: buffer,
  36874. width: imageData.width,
  36875. height: imageData.height
  36876. };
  36877. finish(null, (0, _assertThisInitialized2["default"])(_this));
  36878. } else if (typeof args[0] === 'string') {
  36879. // read from a path
  36880. var path = args[0];
  36881. cb = args[1];
  36882. if (typeof cb === 'undefined') {
  36883. cb = noop;
  36884. }
  36885. if (typeof cb !== 'function') {
  36886. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
  36887. }
  36888. loadBufferFromPath(path, function (err, data) {
  36889. if (err) {
  36890. return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish);
  36891. }
  36892. _this.parseBitmap(data, path, finish);
  36893. });
  36894. } else if ((0, _typeof2["default"])(args[0]) === 'object' && Buffer.isBuffer(args[0])) {
  36895. // read from a buffer
  36896. var data = args[0];
  36897. cb = args[1];
  36898. if (typeof cb !== 'function') {
  36899. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
  36900. }
  36901. _this.parseBitmap(data, null, finish);
  36902. } else {
  36903. // Allow client libs to add new ways to build a Jimp object.
  36904. // Extra constructors must be added by `Jimp.appendConstructorOption()`
  36905. cb = args[args.length - 1];
  36906. if (typeof cb !== 'function') {
  36907. // TODO: try to solve the args after cb problem.
  36908. cb = args[args.length - 2];
  36909. if (typeof cb !== 'function') {
  36910. cb = noop;
  36911. }
  36912. }
  36913. var extraConstructor = Jimp.__extraConstructors.find(function (c) {
  36914. return c.test.apply(c, args);
  36915. });
  36916. if (extraConstructor) {
  36917. new Promise(function (resolve, reject) {
  36918. var _extraConstructor$run;
  36919. return (_extraConstructor$run = extraConstructor.run).call.apply(_extraConstructor$run, [(0, _assertThisInitialized2["default"])(_this), resolve, reject].concat(args));
  36920. }).then(function () {
  36921. return finish(null, (0, _assertThisInitialized2["default"])(_this));
  36922. })["catch"](finish);
  36923. } else {
  36924. return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'No matching constructor overloading was found. ' + 'Please see the docs for how to call the Jimp constructor.', finish));
  36925. }
  36926. }
  36927. return _this;
  36928. }
  36929. /**
  36930. * Parse a bitmap with the loaded image types.
  36931. *
  36932. * @param {Buffer} data raw image data
  36933. * @param {string} path optional path to file
  36934. * @param {function(Error, Jimp)} finish (optional) a callback for when complete
  36935. * @memberof Jimp
  36936. */
  36937. (0, _createClass2["default"])(Jimp, [{
  36938. key: "parseBitmap",
  36939. value: function parseBitmap(data, path, finish) {
  36940. _imageBitmap.parseBitmap.call(this, data, null, finish);
  36941. }
  36942. /**
  36943. * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA)
  36944. * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB
  36945. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  36946. * @returns {Jimp} this for chaining of methods
  36947. */
  36948. }, {
  36949. key: "rgba",
  36950. value: function rgba(bool, cb) {
  36951. if (typeof bool !== 'boolean') {
  36952. return _utils.throwError.call(this, 'bool must be a boolean, true for RGBA or false for RGB', cb);
  36953. }
  36954. this._rgba = bool;
  36955. if ((0, _utils.isNodePattern)(cb)) {
  36956. cb.call(this, null, this);
  36957. }
  36958. return this;
  36959. }
  36960. /**
  36961. * Emit for multiple listeners
  36962. * @param {string} methodName name of the method to emit an error for
  36963. * @param {string} eventName name of the eventName to emit an error for
  36964. * @param {object} data to emit
  36965. */
  36966. }, {
  36967. key: "emitMulti",
  36968. value: function emitMulti(methodName, eventName) {
  36969. var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  36970. data = Object.assign(data, {
  36971. methodName: methodName,
  36972. eventName: eventName
  36973. });
  36974. this.emit('any', data);
  36975. if (methodName) {
  36976. this.emit(methodName, data);
  36977. }
  36978. this.emit(eventName, data);
  36979. }
  36980. }, {
  36981. key: "emitError",
  36982. value: function emitError(methodName, err) {
  36983. this.emitMulti(methodName, 'error', err);
  36984. }
  36985. /**
  36986. * Get the current height of the image
  36987. * @return {number} height of the image
  36988. */
  36989. }, {
  36990. key: "getHeight",
  36991. value: function getHeight() {
  36992. return this.bitmap.height;
  36993. }
  36994. /**
  36995. * Get the current width of the image
  36996. * @return {number} width of the image
  36997. */
  36998. }, {
  36999. key: "getWidth",
  37000. value: function getWidth() {
  37001. return this.bitmap.width;
  37002. }
  37003. /**
  37004. * Nicely format Jimp object when sent to the console e.g. console.log(image)
  37005. * @returns {string} pretty printed
  37006. */
  37007. }, {
  37008. key: "inspect",
  37009. value: function inspect() {
  37010. return '<Jimp ' + (this.bitmap === emptyBitmap ? 'pending...' : this.bitmap.width + 'x' + this.bitmap.height) + '>';
  37011. }
  37012. /**
  37013. * Nicely format Jimp object when converted to a string
  37014. * @returns {string} pretty printed
  37015. */
  37016. }, {
  37017. key: "toString",
  37018. value: function toString() {
  37019. return '[object Jimp]';
  37020. }
  37021. /**
  37022. * Returns the original MIME of the image (default: "image/png")
  37023. * @returns {string} the MIME
  37024. */
  37025. }, {
  37026. key: "getMIME",
  37027. value: function getMIME() {
  37028. var mime = this._originalMime || Jimp.MIME_PNG;
  37029. return mime;
  37030. }
  37031. /**
  37032. * Returns the appropriate file extension for the original MIME of the image (default: "png")
  37033. * @returns {string} the file extension
  37034. */
  37035. }, {
  37036. key: "getExtension",
  37037. value: function getExtension() {
  37038. var mime = this.getMIME();
  37039. return MIME.getExtension(mime);
  37040. }
  37041. /**
  37042. * Writes the image to a file
  37043. * @param {string} path a path to the destination file
  37044. * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk
  37045. * @returns {Jimp} this for chaining of methods
  37046. */
  37047. }, {
  37048. key: "write",
  37049. value: function write(path, cb) {
  37050. var _this2 = this;
  37051. if (!_fs["default"] || !_fs["default"].createWriteStream) {
  37052. throw new Error('Cant access the filesystem. You can use the getBase64 method.');
  37053. }
  37054. if (typeof path !== 'string') {
  37055. return _utils.throwError.call(this, 'path must be a string', cb);
  37056. }
  37057. if (typeof cb === 'undefined') {
  37058. cb = noop;
  37059. }
  37060. if (typeof cb !== 'function') {
  37061. return _utils.throwError.call(this, 'cb must be a function', cb);
  37062. }
  37063. var mime = MIME.getType(path) || this.getMIME();
  37064. var pathObj = _path["default"].parse(path);
  37065. if (pathObj.dir) {
  37066. _mkdirp["default"].sync(pathObj.dir);
  37067. }
  37068. this.getBuffer(mime, function (err, buffer) {
  37069. if (err) {
  37070. return _utils.throwError.call(_this2, err, cb);
  37071. }
  37072. var stream = _fs["default"].createWriteStream(path);
  37073. stream.on('open', function () {
  37074. stream.write(buffer);
  37075. stream.end();
  37076. }).on('error', function (err) {
  37077. return _utils.throwError.call(_this2, err, cb);
  37078. });
  37079. stream.on('finish', function () {
  37080. cb.call(_this2, null, _this2);
  37081. });
  37082. });
  37083. return this;
  37084. }
  37085. }, {
  37086. key: "getBase64",
  37087. /**
  37088. * Converts the image to a base 64 string
  37089. * @param {string} mime the mime type of the image data to be created
  37090. * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
  37091. * @returns {Jimp} this for chaining of methods
  37092. */
  37093. value: function getBase64(mime, cb) {
  37094. if (mime === Jimp.AUTO) {
  37095. // allow auto MIME detection
  37096. mime = this.getMIME();
  37097. }
  37098. if (typeof mime !== 'string') {
  37099. return _utils.throwError.call(this, 'mime must be a string', cb);
  37100. }
  37101. if (typeof cb !== 'function') {
  37102. return _utils.throwError.call(this, 'cb must be a function', cb);
  37103. }
  37104. this.getBuffer(mime, function (err, data) {
  37105. if (err) {
  37106. return _utils.throwError.call(this, err, cb);
  37107. }
  37108. var src = 'data:' + mime + ';base64,' + data.toString('base64');
  37109. cb.call(this, null, src);
  37110. });
  37111. return this;
  37112. }
  37113. }, {
  37114. key: "hash",
  37115. /**
  37116. * Generates a perceptual hash of the image <https://en.wikipedia.org/wiki/Perceptual_hashing>. And pads the string. Can configure base.
  37117. * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64.
  37118. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  37119. * @returns {string} a string representing the hash
  37120. */
  37121. value: function hash(base, cb) {
  37122. base = base || 64;
  37123. if (typeof base === 'function') {
  37124. cb = base;
  37125. base = 64;
  37126. }
  37127. if (typeof base !== 'number') {
  37128. return _utils.throwError.call(this, 'base must be a number', cb);
  37129. }
  37130. if (base < 2 || base > 64) {
  37131. return _utils.throwError.call(this, 'base must be a number between 2 and 64', cb);
  37132. }
  37133. var hash = this.pHash();
  37134. hash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, base))(hash);
  37135. while (hash.length < maxHashLength[base]) {
  37136. hash = '0' + hash; // pad out with leading zeros
  37137. }
  37138. if ((0, _utils.isNodePattern)(cb)) {
  37139. cb.call(this, null, hash);
  37140. }
  37141. return hash;
  37142. }
  37143. /**
  37144. * Calculates the perceptual hash
  37145. * @returns {number} the perceptual hash
  37146. */
  37147. }, {
  37148. key: "pHash",
  37149. value: function pHash() {
  37150. var pHash = new _phash["default"]();
  37151. return pHash.getHash(this);
  37152. }
  37153. /**
  37154. * Calculates the hamming distance of the current image and a hash based on their perceptual hash
  37155. * @param {hash} compareHash hash to compare to
  37156. * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
  37157. */
  37158. }, {
  37159. key: "distanceFromHash",
  37160. value: function distanceFromHash(compareHash) {
  37161. var pHash = new _phash["default"]();
  37162. var currentHash = pHash.getHash(this);
  37163. return pHash.distance(currentHash, compareHash);
  37164. }
  37165. /**
  37166. * Converts the image to a buffer
  37167. * @param {string} mime the mime type of the image buffer to be created
  37168. * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
  37169. * @returns {Jimp} this for chaining of methods
  37170. */
  37171. }, {
  37172. key: "getPixelIndex",
  37173. /**
  37174. * Returns the offset of a pixel in the bitmap buffer
  37175. * @param {number} x the x coordinate
  37176. * @param {number} y the y coordinate
  37177. * @param {string} edgeHandling (optional) define how to sum pixels from outside the border
  37178. * @param {number} cb (optional) a callback for when complete
  37179. * @returns {number} the index of the pixel or -1 if not found
  37180. */
  37181. value: function getPixelIndex(x, y, edgeHandling, cb) {
  37182. var xi;
  37183. var yi;
  37184. if (typeof edgeHandling === 'function' && typeof cb === 'undefined') {
  37185. cb = edgeHandling;
  37186. edgeHandling = null;
  37187. }
  37188. if (!edgeHandling) {
  37189. edgeHandling = Jimp.EDGE_EXTEND;
  37190. }
  37191. if (typeof x !== 'number' || typeof y !== 'number') {
  37192. return _utils.throwError.call(this, 'x and y must be numbers', cb);
  37193. } // round input
  37194. x = Math.round(x);
  37195. y = Math.round(y);
  37196. xi = x;
  37197. yi = y;
  37198. if (edgeHandling === Jimp.EDGE_EXTEND) {
  37199. if (x < 0) xi = 0;
  37200. if (x >= this.bitmap.width) xi = this.bitmap.width - 1;
  37201. if (y < 0) yi = 0;
  37202. if (y >= this.bitmap.height) yi = this.bitmap.height - 1;
  37203. }
  37204. if (edgeHandling === Jimp.EDGE_WRAP) {
  37205. if (x < 0) {
  37206. xi = this.bitmap.width + x;
  37207. }
  37208. if (x >= this.bitmap.width) {
  37209. xi = x % this.bitmap.width;
  37210. }
  37211. if (y < 0) {
  37212. xi = this.bitmap.height + y;
  37213. }
  37214. if (y >= this.bitmap.height) {
  37215. yi = y % this.bitmap.height;
  37216. }
  37217. }
  37218. var i = this.bitmap.width * yi + xi << 2; // if out of bounds index is -1
  37219. if (xi < 0 || xi >= this.bitmap.width) {
  37220. i = -1;
  37221. }
  37222. if (yi < 0 || yi >= this.bitmap.height) {
  37223. i = -1;
  37224. }
  37225. if ((0, _utils.isNodePattern)(cb)) {
  37226. cb.call(this, null, i);
  37227. }
  37228. return i;
  37229. }
  37230. /**
  37231. * Returns the hex colour value of a pixel
  37232. * @param {number} x the x coordinate
  37233. * @param {number} y the y coordinate
  37234. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  37235. * @returns {number} the color of the pixel
  37236. */
  37237. }, {
  37238. key: "getPixelColor",
  37239. value: function getPixelColor(x, y, cb) {
  37240. if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb); // round input
  37241. x = Math.round(x);
  37242. y = Math.round(y);
  37243. var idx = this.getPixelIndex(x, y);
  37244. var hex = this.bitmap.data.readUInt32BE(idx);
  37245. if ((0, _utils.isNodePattern)(cb)) {
  37246. cb.call(this, null, hex);
  37247. }
  37248. return hex;
  37249. }
  37250. }, {
  37251. key: "setPixelColor",
  37252. /**
  37253. * Returns the hex colour value of a pixel
  37254. * @param {number} hex color to set
  37255. * @param {number} x the x coordinate
  37256. * @param {number} y the y coordinate
  37257. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  37258. * @returns {number} the index of the pixel or -1 if not found
  37259. */
  37260. value: function setPixelColor(hex, x, y, cb) {
  37261. if (typeof hex !== 'number' || typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'hex, x and y must be numbers', cb); // round input
  37262. x = Math.round(x);
  37263. y = Math.round(y);
  37264. var idx = this.getPixelIndex(x, y);
  37265. this.bitmap.data.writeUInt32BE(hex, idx);
  37266. if ((0, _utils.isNodePattern)(cb)) {
  37267. cb.call(this, null, this);
  37268. }
  37269. return this;
  37270. }
  37271. }, {
  37272. key: "hasAlpha",
  37273. /**
  37274. * Determine if the image contains opaque pixels.
  37275. * @return {boolean} hasAlpha whether the image contains opaque pixels
  37276. */
  37277. value: function hasAlpha() {
  37278. for (var yIndex = 0; yIndex < this.bitmap.height; yIndex++) {
  37279. for (var xIndex = 0; xIndex < this.bitmap.width; xIndex++) {
  37280. var idx = this.bitmap.width * yIndex + xIndex << 2;
  37281. var alpha = this.bitmap.data[idx + 3];
  37282. if (alpha !== 0xff) {
  37283. return true;
  37284. }
  37285. }
  37286. }
  37287. return false;
  37288. }
  37289. /**
  37290. * Iterate scan through a region of the bitmap
  37291. * @param {number} x the x coordinate to begin the scan at
  37292. * @param {number} y the y coordinate to begin the scan at
  37293. * @param w the width of the scan region
  37294. * @param h the height of the scan region
  37295. * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>}
  37296. */
  37297. }, {
  37298. key: "scanIterator",
  37299. value: function scanIterator(x, y, w, h) {
  37300. if (typeof x !== 'number' || typeof y !== 'number') {
  37301. return _utils.throwError.call(this, 'x and y must be numbers');
  37302. }
  37303. if (typeof w !== 'number' || typeof h !== 'number') {
  37304. return _utils.throwError.call(this, 'w and h must be numbers');
  37305. }
  37306. return (0, _utils.scanIterator)(this, x, y, w, h);
  37307. }
  37308. }]);
  37309. return Jimp;
  37310. }(_events["default"]);
  37311. function addConstants(constants) {
  37312. var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;
  37313. Object.entries(constants).forEach(function (_ref) {
  37314. var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
  37315. name = _ref2[0],
  37316. value = _ref2[1];
  37317. jimpInstance[name] = value;
  37318. });
  37319. }
  37320. function addJimpMethods(methods) {
  37321. var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;
  37322. Object.entries(methods).forEach(function (_ref3) {
  37323. var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
  37324. name = _ref4[0],
  37325. value = _ref4[1];
  37326. jimpInstance.prototype[name] = value;
  37327. });
  37328. }
  37329. addConstants(constants);
  37330. addJimpMethods({
  37331. composite: _composite["default"]
  37332. });
  37333. Jimp.__extraConstructors = [];
  37334. /**
  37335. * Allow client libs to add new ways to build a Jimp object.
  37336. * @param {string} name identify the extra constructor.
  37337. * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor.
  37338. * @param {function} run where the magic happens.
  37339. */
  37340. Jimp.appendConstructorOption = function (name, test, run) {
  37341. Jimp.__extraConstructors.push({
  37342. name: name,
  37343. test: test,
  37344. run: run
  37345. });
  37346. };
  37347. /**
  37348. * Read an image from a file or a Buffer. Takes the same args as the constructor
  37349. * @returns {Promise} a promise
  37350. */
  37351. Jimp.read = function () {
  37352. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  37353. args[_key3] = arguments[_key3];
  37354. }
  37355. return new Promise(function (resolve, reject) {
  37356. (0, _construct2["default"])(Jimp, args.concat([function (err, image) {
  37357. if (err) reject(err);else resolve(image);
  37358. }]));
  37359. });
  37360. };
  37361. Jimp.create = Jimp.read;
  37362. /**
  37363. * A static helper method that converts RGBA values to a single integer value
  37364. * @param {number} r the red value (0-255)
  37365. * @param {number} g the green value (0-255)
  37366. * @param {number} b the blue value (0-255)
  37367. * @param {number} a the alpha value (0-255)
  37368. * @param {function(Error, Jimp)} cb (optional) A callback for when complete
  37369. * @returns {number} an single integer colour value
  37370. */
  37371. Jimp.rgbaToInt = function (r, g, b, a, cb) {
  37372. if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number' || typeof a !== 'number') {
  37373. return _utils.throwError.call(this, 'r, g, b and a must be numbers', cb);
  37374. }
  37375. if (r < 0 || r > 255) {
  37376. return _utils.throwError.call(this, 'r must be between 0 and 255', cb);
  37377. }
  37378. if (g < 0 || g > 255) {
  37379. _utils.throwError.call(this, 'g must be between 0 and 255', cb);
  37380. }
  37381. if (b < 0 || b > 255) {
  37382. return _utils.throwError.call(this, 'b must be between 0 and 255', cb);
  37383. }
  37384. if (a < 0 || a > 255) {
  37385. return _utils.throwError.call(this, 'a must be between 0 and 255', cb);
  37386. }
  37387. r = Math.round(r);
  37388. b = Math.round(b);
  37389. g = Math.round(g);
  37390. a = Math.round(a);
  37391. var i = r * Math.pow(256, 3) + g * Math.pow(256, 2) + b * Math.pow(256, 1) + a * Math.pow(256, 0);
  37392. if ((0, _utils.isNodePattern)(cb)) {
  37393. cb.call(this, null, i);
  37394. }
  37395. return i;
  37396. };
  37397. /**
  37398. * A static helper method that converts RGBA values to a single integer value
  37399. * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)
  37400. * @param {function(Error, Jimp)} cb (optional) A callback for when complete
  37401. * @returns {object} an object with the properties r, g, b and a representing RGBA values
  37402. */
  37403. Jimp.intToRGBA = function (i, cb) {
  37404. if (typeof i !== 'number') {
  37405. return _utils.throwError.call(this, 'i must be a number', cb);
  37406. }
  37407. var rgba = {};
  37408. rgba.r = Math.floor(i / Math.pow(256, 3));
  37409. rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));
  37410. rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));
  37411. rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));
  37412. if ((0, _utils.isNodePattern)(cb)) {
  37413. cb.call(this, null, rgba);
  37414. }
  37415. return rgba;
  37416. };
  37417. /**
  37418. * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number
  37419. * @param {string} cssColor a number
  37420. * @returns {number} a hex number representing a color
  37421. */
  37422. Jimp.cssColorToHex = function (cssColor) {
  37423. cssColor = cssColor || 0; // 0, null, undefined, NaN
  37424. if (typeof cssColor === 'number') return Number(cssColor);
  37425. return parseInt((0, _tinycolor["default"])(cssColor).toHex8(), 16);
  37426. };
  37427. /**
  37428. * Limits a number to between 0 or 255
  37429. * @param {number} n a number
  37430. * @returns {number} the number limited to between 0 or 255
  37431. */
  37432. Jimp.limit255 = function (n) {
  37433. n = Math.max(n, 0);
  37434. n = Math.min(n, 255);
  37435. return n;
  37436. };
  37437. /**
  37438. * Diffs two images and returns
  37439. * @param {Jimp} img1 a Jimp image to compare
  37440. * @param {Jimp} img2 a Jimp image to compare
  37441. * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)
  37442. * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences }
  37443. */
  37444. Jimp.diff = function (img1, img2) {
  37445. var threshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1;
  37446. if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp)) return _utils.throwError.call(this, 'img1 and img2 must be an Jimp images');
  37447. var bmp1 = img1.bitmap;
  37448. var bmp2 = img2.bitmap;
  37449. if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) {
  37450. if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) {
  37451. // img1 is bigger
  37452. img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height);
  37453. } else {
  37454. // img2 is bigger (or they are the same in area)
  37455. img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height);
  37456. }
  37457. }
  37458. if (typeof threshold !== 'number' || threshold < 0 || threshold > 1) {
  37459. return _utils.throwError.call(this, 'threshold must be a number between 0 and 1');
  37460. }
  37461. var diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff);
  37462. var numDiffPixels = (0, _pixelmatch["default"])(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, {
  37463. threshold: threshold
  37464. });
  37465. return {
  37466. percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height),
  37467. image: diff
  37468. };
  37469. };
  37470. /**
  37471. * Calculates the hamming distance of two images based on their perceptual hash
  37472. * @param {Jimp} img1 a Jimp image to compare
  37473. * @param {Jimp} img2 a Jimp image to compare
  37474. * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
  37475. */
  37476. Jimp.distance = function (img1, img2) {
  37477. var phash = new _phash["default"]();
  37478. var hash1 = phash.getHash(img1);
  37479. var hash2 = phash.getHash(img2);
  37480. return phash.distance(hash1, hash2);
  37481. };
  37482. /**
  37483. * Calculates the hamming distance of two images based on their perceptual hash
  37484. * @param {hash} hash1 a pHash
  37485. * @param {hash} hash2 a pHash
  37486. * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
  37487. */
  37488. Jimp.compareHashes = function (hash1, hash2) {
  37489. var phash = new _phash["default"]();
  37490. return phash.distance(hash1, hash2);
  37491. };
  37492. /**
  37493. * Compute color difference
  37494. * 0 means no difference, 1 means maximum difference.
  37495. * @param {number} rgba1: first color to compare.
  37496. * @param {number} rgba2: second color to compare.
  37497. * Both parameters must be an color object {r:val, g:val, b:val, a:val}
  37498. * Where `a` is optional and `val` is an integer between 0 and 255.
  37499. * @returns {number} float between 0 and 1.
  37500. */
  37501. Jimp.colorDiff = function (rgba1, rgba2) {
  37502. var pow = function pow(n) {
  37503. return Math.pow(n, 2);
  37504. };
  37505. var max = Math.max;
  37506. var maxVal = 255 * 255 * 3;
  37507. if (rgba1.a !== 0 && !rgba1.a) {
  37508. rgba1.a = 255;
  37509. }
  37510. if (rgba2.a !== 0 && !rgba2.a) {
  37511. rgba2.a = 255;
  37512. }
  37513. return (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) + max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) + max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) / maxVal;
  37514. };
  37515. /**
  37516. * Helper to create Jimp methods that emit events before and after its execution.
  37517. * @param {string} methodName The name to be appended to Jimp prototype.
  37518. * @param {string} evName The event name to be called.
  37519. * It will be prefixed by `before-` and emitted when on method call.
  37520. * It will be appended by `ed` and emitted after the method run.
  37521. * @param {function} method A function implementing the method itself.
  37522. * It will also create a quiet version that will not emit events, to not
  37523. * mess the user code with many `changed` event calls. You can call with
  37524. * `methodName + "Quiet"`.
  37525. *
  37526. * The emitted event comes with a object parameter to the listener with the
  37527. * `methodName` as one attribute.
  37528. */
  37529. function jimpEvMethod(methodName, evName, method) {
  37530. var evNameBefore = 'before-' + evName;
  37531. var evNameAfter = evName.replace(/e$/, '') + 'ed';
  37532. Jimp.prototype[methodName] = function () {
  37533. var wrappedCb;
  37534. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  37535. args[_key4] = arguments[_key4];
  37536. }
  37537. var cb = args[method.length - 1];
  37538. var jimpInstance = this;
  37539. if (typeof cb === 'function') {
  37540. wrappedCb = function wrappedCb() {
  37541. for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  37542. args[_key5] = arguments[_key5];
  37543. }
  37544. var err = args[0],
  37545. data = args[1];
  37546. if (err) {
  37547. jimpInstance.emitError(methodName, err);
  37548. } else {
  37549. jimpInstance.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, data));
  37550. }
  37551. cb.apply(this, args);
  37552. };
  37553. args[args.length - 1] = wrappedCb;
  37554. } else {
  37555. wrappedCb = false;
  37556. }
  37557. this.emitMulti(methodName, evNameBefore);
  37558. var result;
  37559. try {
  37560. result = method.apply(this, args);
  37561. if (!wrappedCb) {
  37562. this.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, result));
  37563. }
  37564. } catch (error) {
  37565. error.methodName = methodName;
  37566. this.emitError(methodName, error);
  37567. }
  37568. return result;
  37569. };
  37570. Jimp.prototype[methodName + 'Quiet'] = method;
  37571. }
  37572. /**
  37573. * Creates a new image that is a clone of this one.
  37574. * @param {function(Error, Jimp)} cb (optional) A callback for when complete
  37575. * @returns the new image
  37576. */
  37577. jimpEvMethod('clone', 'clone', function (cb) {
  37578. var clone = new Jimp(this);
  37579. if ((0, _utils.isNodePattern)(cb)) {
  37580. cb.call(clone, null, clone);
  37581. }
  37582. return clone;
  37583. });
  37584. /**
  37585. * Simplify jimpEvMethod call for the common `change` evName.
  37586. * @param {string} methodName name of the method
  37587. * @param {function} method to watch changes for
  37588. */
  37589. function jimpEvChange(methodName, method) {
  37590. jimpEvMethod(methodName, 'change', method);
  37591. }
  37592. /**
  37593. * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)
  37594. * @param b A Boolean, true to use RGBA or false to use RGB
  37595. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  37596. * @returns {Jimp} this for chaining of methods
  37597. */
  37598. jimpEvChange('background', function (hex, cb) {
  37599. if (typeof hex !== 'number') {
  37600. return _utils.throwError.call(this, 'hex must be a hexadecimal rgba value', cb);
  37601. }
  37602. this._background = hex;
  37603. if ((0, _utils.isNodePattern)(cb)) {
  37604. cb.call(this, null, this);
  37605. }
  37606. return this;
  37607. });
  37608. /**
  37609. * Scans through a region of the bitmap, calling a function for each pixel.
  37610. * @param {number} x the x coordinate to begin the scan at
  37611. * @param {number} y the y coordinate to begin the scan at
  37612. * @param w the width of the scan region
  37613. * @param h the height of the scan region
  37614. * @param f a function to call on even pixel; the (x, y) position of the pixel
  37615. * and the index of the pixel in the bitmap buffer are passed to the function
  37616. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  37617. * @returns {Jimp} this for chaining of methods
  37618. */
  37619. jimpEvChange('scan', function (x, y, w, h, f, cb) {
  37620. if (typeof x !== 'number' || typeof y !== 'number') {
  37621. return _utils.throwError.call(this, 'x and y must be numbers', cb);
  37622. }
  37623. if (typeof w !== 'number' || typeof h !== 'number') {
  37624. return _utils.throwError.call(this, 'w and h must be numbers', cb);
  37625. }
  37626. if (typeof f !== 'function') {
  37627. return _utils.throwError.call(this, 'f must be a function', cb);
  37628. }
  37629. var result = (0, _utils.scan)(this, x, y, w, h, f);
  37630. if ((0, _utils.isNodePattern)(cb)) {
  37631. cb.call(this, null, result);
  37632. }
  37633. return result;
  37634. });
  37635. if ("BROWSER" === 'BROWSER') {
  37636. // For use in a web browser or web worker
  37637. /* global self */
  37638. var gl;
  37639. if (typeof window !== 'undefined' && (typeof window === "undefined" ? "undefined" : (0, _typeof2["default"])(window)) === 'object') {
  37640. gl = window;
  37641. }
  37642. if (typeof self !== 'undefined' && (typeof self === "undefined" ? "undefined" : (0, _typeof2["default"])(self)) === 'object') {
  37643. gl = self;
  37644. }
  37645. gl.Jimp = Jimp;
  37646. gl.Buffer = Buffer;
  37647. }
  37648. var _default = Jimp;
  37649. exports["default"] = _default;
  37650. }).call(this,require("buffer").Buffer)
  37651. },{"./composite":370,"./constants":371,"./modules/phash":373,"./request":374,"./utils/image-bitmap":375,"./utils/mime":376,"./utils/promisify":377,"@babel/runtime/helpers/assertThisInitialized":3,"@babel/runtime/helpers/classCallCheck":4,"@babel/runtime/helpers/construct":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":8,"@babel/runtime/helpers/inherits":9,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/possibleConstructorReturn":16,"@babel/runtime/helpers/slicedToArray":18,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"any-base":22,"buffer":47,"core-js/modules/es.array-buffer.slice":172,"core-js/modules/es.array.concat":173,"core-js/modules/es.array.find":177,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.index-of":180,"core-js/modules/es.array.iterator":182,"core-js/modules/es.array.join":183,"core-js/modules/es.date.to-string":187,"core-js/modules/es.number.constructor":189,"core-js/modules/es.object.assign":190,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.to-string":197,"core-js/modules/es.parse-int":198,"core-js/modules/es.promise":199,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.regexp.to-string":201,"core-js/modules/es.string.match":204,"core-js/modules/es.string.replace":205,"core-js/modules/es.typed-array.copy-within":208,"core-js/modules/es.typed-array.every":209,"core-js/modules/es.typed-array.fill":210,"core-js/modules/es.typed-array.filter":211,"core-js/modules/es.typed-array.find":213,"core-js/modules/es.typed-array.find-index":212,"core-js/modules/es.typed-array.for-each":216,"core-js/modules/es.typed-array.includes":217,"core-js/modules/es.typed-array.index-of":218,"core-js/modules/es.typed-array.iterator":219,"core-js/modules/es.typed-array.join":220,"core-js/modules/es.typed-array.last-index-of":221,"core-js/modules/es.typed-array.map":222,"core-js/modules/es.typed-array.reduce":224,"core-js/modules/es.typed-array.reduce-right":223,"core-js/modules/es.typed-array.reverse":225,"core-js/modules/es.typed-array.set":226,"core-js/modules/es.typed-array.slice":227,"core-js/modules/es.typed-array.some":228,"core-js/modules/es.typed-array.sort":229,"core-js/modules/es.typed-array.subarray":230,"core-js/modules/es.typed-array.to-locale-string":231,"core-js/modules/es.typed-array.to-string":232,"core-js/modules/es.typed-array.uint8-array":233,"core-js/modules/es.typed-array.uint8-clamped-array":234,"core-js/modules/web.dom-collections.for-each":235,"core-js/modules/web.timers":237,"events":239,"fs":46,"mkdirp":262,"path":286,"pixelmatch":288,"tinycolor2":357}],373:[function(require,module,exports){
  37652. "use strict";
  37653. /*
  37654. Copyright (c) 2011 Elliot Shepherd
  37655. Permission is hereby granted, free of charge, to any person obtaining a copy
  37656. of this software and associated documentation files (the "Software"), to deal
  37657. in the Software without restriction, including without limitation the rights
  37658. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37659. copies of the Software, and to permit persons to whom the Software is
  37660. furnished to do so, subject to the following conditions:
  37661. The above copyright notice and this permission notice shall be included in
  37662. all copies or substantial portions of the Software.
  37663. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37664. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37665. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37666. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37667. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37668. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37669. THE SOFTWARE.
  37670. */
  37671. // https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java
  37672. /*
  37673. * pHash-like image hash.
  37674. * Author: Elliot Shepherd (elliot@jarofworms.com
  37675. * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
  37676. */
  37677. function ImagePHash(size, smallerSize) {
  37678. this.size = this.size || size;
  37679. this.smallerSize = this.smallerSize || smallerSize;
  37680. initCoefficients(this.size);
  37681. }
  37682. ImagePHash.prototype.size = 32;
  37683. ImagePHash.prototype.smallerSize = 8;
  37684. ImagePHash.prototype.distance = function (s1, s2) {
  37685. var counter = 0;
  37686. for (var k = 0; k < s1.length; k++) {
  37687. if (s1[k] !== s2[k]) {
  37688. counter++;
  37689. }
  37690. }
  37691. return counter / s1.length;
  37692. }; // Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.
  37693. ImagePHash.prototype.getHash = function (img) {
  37694. /* 1. Reduce size.
  37695. * Like Average Hash, pHash starts with a small image.
  37696. * However, the image is larger than 8x8; 32x32 is a good size.
  37697. * This is really done to simplify the DCT computation and not
  37698. * because it is needed to reduce the high frequencies.
  37699. */
  37700. img = img.clone().resize(this.size, this.size);
  37701. /* 2. Reduce color.
  37702. * The image is reduced to a grayscale just to further simplify
  37703. * the number of computations.
  37704. */
  37705. img.grayscale();
  37706. var vals = [];
  37707. for (var x = 0; x < img.bitmap.width; x++) {
  37708. vals[x] = [];
  37709. for (var y = 0; y < img.bitmap.height; y++) {
  37710. vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b;
  37711. }
  37712. }
  37713. /* 3. Compute the DCT.
  37714. * The DCT separates the image into a collection of frequencies
  37715. * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses
  37716. * a 32x32 DCT.
  37717. */
  37718. var dctVals = applyDCT(vals, this.size);
  37719. /* 4. Reduce the DCT.
  37720. * This is the magic step. While the DCT is 32x32, just keep the
  37721. * top-left 8x8. Those represent the lowest frequencies in the
  37722. * picture.
  37723. */
  37724. /* 5. Compute the average value.
  37725. * Like the Average Hash, compute the mean DCT value (using only
  37726. * the 8x8 DCT low-frequency values and excluding the first term
  37727. * since the DC coefficient can be significantly different from
  37728. * the other values and will throw off the average).
  37729. */
  37730. var total = 0;
  37731. for (var _x = 0; _x < this.smallerSize; _x++) {
  37732. for (var _y = 0; _y < this.smallerSize; _y++) {
  37733. total += dctVals[_x][_y];
  37734. }
  37735. }
  37736. var avg = total / (this.smallerSize * this.smallerSize);
  37737. /* 6. Further reduce the DCT.
  37738. * This is the magic step. Set the 64 hash bits to 0 or 1
  37739. * depending on whether each of the 64 DCT values is above or
  37740. * below the average value. The result doesn't tell us the
  37741. * actual low frequencies; it just tells us the very-rough
  37742. * relative scale of the frequencies to the mean. The result
  37743. * will not vary as long as the overall structure of the image
  37744. * remains the same; this can survive gamma and color histogram
  37745. * adjustments without a problem.
  37746. */
  37747. var hash = '';
  37748. for (var _x2 = 0; _x2 < this.smallerSize; _x2++) {
  37749. for (var _y2 = 0; _y2 < this.smallerSize; _y2++) {
  37750. hash += dctVals[_x2][_y2] > avg ? '1' : '0';
  37751. }
  37752. }
  37753. return hash;
  37754. }; // DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java
  37755. function intToRGBA(i) {
  37756. var rgba = {};
  37757. rgba.r = Math.floor(i / Math.pow(256, 3));
  37758. rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));
  37759. rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));
  37760. rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));
  37761. return rgba;
  37762. }
  37763. var c = [];
  37764. function initCoefficients(size) {
  37765. for (var i = 1; i < size; i++) {
  37766. c[i] = 1;
  37767. }
  37768. c[0] = 1 / Math.sqrt(2.0);
  37769. }
  37770. function applyDCT(f, size) {
  37771. var N = size;
  37772. var F = [];
  37773. for (var u = 0; u < N; u++) {
  37774. F[u] = [];
  37775. for (var v = 0; v < N; v++) {
  37776. var sum = 0;
  37777. for (var i = 0; i < N; i++) {
  37778. for (var j = 0; j < N; j++) {
  37779. sum += Math.cos((2 * i + 1) / (2.0 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2.0 * N) * v * Math.PI) * f[i][j];
  37780. }
  37781. }
  37782. sum *= c[u] * c[v] / 4;
  37783. F[u][v] = sum;
  37784. }
  37785. }
  37786. return F;
  37787. }
  37788. module.exports = ImagePHash;
  37789. },{}],374:[function(require,module,exports){
  37790. (function (process,Buffer){
  37791. "use strict";
  37792. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  37793. require("core-js/modules/es.symbol");
  37794. require("core-js/modules/es.array.filter");
  37795. require("core-js/modules/es.array.for-each");
  37796. require("core-js/modules/es.object.assign");
  37797. require("core-js/modules/es.object.define-properties");
  37798. require("core-js/modules/es.object.define-property");
  37799. require("core-js/modules/es.object.get-own-property-descriptor");
  37800. require("core-js/modules/es.object.get-own-property-descriptors");
  37801. require("core-js/modules/es.object.keys");
  37802. require("core-js/modules/web.dom-collections.for-each");
  37803. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  37804. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  37805. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  37806. /* global XMLHttpRequest */
  37807. if (process.browser || "BROWSER" === 'BROWSER' || typeof process.versions.electron !== 'undefined' && process.type === 'renderer' && typeof XMLHttpRequest === 'function') {
  37808. // If we run into a browser or the electron renderer process,
  37809. // use XHR method instead of Request node module.
  37810. module.exports = function (options, cb) {
  37811. var xhr = new XMLHttpRequest();
  37812. xhr.open('GET', options.url, true);
  37813. xhr.responseType = 'arraybuffer';
  37814. xhr.addEventListener('load', function () {
  37815. if (xhr.status < 400) {
  37816. try {
  37817. var data = Buffer.from(this.response);
  37818. cb(null, xhr, data);
  37819. } catch (error) {
  37820. return cb(new Error('Response is not a buffer for url ' + options.url + '. Error: ' + error.message));
  37821. }
  37822. } else {
  37823. cb(new Error('HTTP Status ' + xhr.status + ' for url ' + options.url));
  37824. }
  37825. });
  37826. xhr.addEventListener('error', function (e) {
  37827. cb(e);
  37828. });
  37829. xhr.send();
  37830. };
  37831. } else {
  37832. module.exports = function (_ref, cb) {
  37833. var options = Object.assign({}, _ref);
  37834. var p = require('phin');
  37835. p(_objectSpread({
  37836. compression: true
  37837. }, options), function (err, res) {
  37838. if (err === null) {
  37839. cb(null, res, res.body);
  37840. } else {
  37841. cb(err);
  37842. }
  37843. });
  37844. };
  37845. }
  37846. }).call(this,require('_process'),require("buffer").Buffer)
  37847. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"_process":312,"buffer":47,"core-js/modules/es.array.filter":175,"core-js/modules/es.array.for-each":178,"core-js/modules/es.object.assign":190,"core-js/modules/es.object.define-properties":191,"core-js/modules/es.object.define-property":192,"core-js/modules/es.object.get-own-property-descriptor":194,"core-js/modules/es.object.get-own-property-descriptors":195,"core-js/modules/es.object.keys":196,"core-js/modules/es.symbol":207,"core-js/modules/web.dom-collections.for-each":235,"phin":287}],375:[function(require,module,exports){
  37848. (function (Buffer){
  37849. "use strict";
  37850. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
  37851. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  37852. Object.defineProperty(exports, "__esModule", {
  37853. value: true
  37854. });
  37855. exports.parseBitmap = parseBitmap;
  37856. exports.getBuffer = getBuffer;
  37857. exports.getBufferAsync = getBufferAsync;
  37858. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
  37859. var _fileType = _interopRequireDefault(require("file-type"));
  37860. var _exifParser = _interopRequireDefault(require("exif-parser"));
  37861. var _utils = require("@jimp/utils");
  37862. var constants = _interopRequireWildcard(require("../constants"));
  37863. var MIME = _interopRequireWildcard(require("./mime"));
  37864. var _promisify = _interopRequireDefault(require("./promisify"));
  37865. function getMIMEFromBuffer(buffer, path) {
  37866. var fileTypeFromBuffer = (0, _fileType["default"])(buffer);
  37867. if (fileTypeFromBuffer) {
  37868. // If fileType returns something for buffer, then return the mime given
  37869. return fileTypeFromBuffer.mime;
  37870. }
  37871. if (path) {
  37872. // If a path is supplied, and fileType yields no results, then retry with MIME
  37873. // Path can be either a file path or a url
  37874. return MIME.getType(path);
  37875. }
  37876. return null;
  37877. }
  37878. /*
  37879. * Obtains image orientation from EXIF metadata.
  37880. *
  37881. * @param img {Jimp} a Jimp image object
  37882. * @returns {number} a number 1-8 representing EXIF orientation,
  37883. * in particular 1 if orientation tag is missing
  37884. */
  37885. function getExifOrientation(img) {
  37886. return img._exif && img._exif.tags && img._exif.tags.Orientation || 1;
  37887. }
  37888. /**
  37889. * Returns a function which translates EXIF-rotated coordinates into
  37890. * non-rotated ones.
  37891. *
  37892. * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html.
  37893. *
  37894. * @param img {Jimp} a Jimp image object
  37895. * @returns {function} transformation function for transformBitmap().
  37896. */
  37897. function getExifOrientationTransformation(img) {
  37898. var w = img.getWidth();
  37899. var h = img.getHeight();
  37900. switch (getExifOrientation(img)) {
  37901. case 1:
  37902. // Horizontal (normal)
  37903. // does not need to be supported here
  37904. return null;
  37905. case 2:
  37906. // Mirror horizontal
  37907. return function (x, y) {
  37908. return [w - x - 1, y];
  37909. };
  37910. case 3:
  37911. // Rotate 180
  37912. return function (x, y) {
  37913. return [w - x - 1, h - y - 1];
  37914. };
  37915. case 4:
  37916. // Mirror vertical
  37917. return function (x, y) {
  37918. return [x, h - y - 1];
  37919. };
  37920. case 5:
  37921. // Mirror horizontal and rotate 270 CW
  37922. return function (x, y) {
  37923. return [y, x];
  37924. };
  37925. case 6:
  37926. // Rotate 90 CW
  37927. return function (x, y) {
  37928. return [y, h - x - 1];
  37929. };
  37930. case 7:
  37931. // Mirror horizontal and rotate 90 CW
  37932. return function (x, y) {
  37933. return [w - y - 1, h - x - 1];
  37934. };
  37935. case 8:
  37936. // Rotate 270 CW
  37937. return function (x, y) {
  37938. return [w - y - 1, x];
  37939. };
  37940. default:
  37941. return null;
  37942. }
  37943. }
  37944. /*
  37945. * Transforms bitmap in place (moves pixels around) according to given
  37946. * transformation function.
  37947. *
  37948. * @param img {Jimp} a Jimp image object, which bitmap is supposed to
  37949. * be transformed
  37950. * @param width {number} bitmap width after the transformation
  37951. * @param height {number} bitmap height after the transformation
  37952. * @param transformation {function} transformation function which defines pixel
  37953. * mapping between new and source bitmap. It takes a pair of coordinates
  37954. * in the target, and returns a respective pair of coordinates in
  37955. * the source bitmap, i.e. has following form:
  37956. * `function(new_x, new_y) { return [src_x, src_y] }`.
  37957. */
  37958. function transformBitmap(img, width, height, transformation) {
  37959. // Underscore-prefixed values are related to the source bitmap
  37960. // Their counterparts with no prefix are related to the target bitmap
  37961. var _data = img.bitmap.data;
  37962. var _width = img.bitmap.width;
  37963. var data = Buffer.alloc(_data.length);
  37964. for (var x = 0; x < width; x++) {
  37965. for (var y = 0; y < height; y++) {
  37966. var _transformation = transformation(x, y),
  37967. _transformation2 = (0, _slicedToArray2["default"])(_transformation, 2),
  37968. _x = _transformation2[0],
  37969. _y = _transformation2[1];
  37970. var idx = width * y + x << 2;
  37971. var _idx = _width * _y + _x << 2;
  37972. var pixel = _data.readUInt32BE(_idx);
  37973. data.writeUInt32BE(pixel, idx);
  37974. }
  37975. }
  37976. img.bitmap.data = data;
  37977. img.bitmap.width = width;
  37978. img.bitmap.height = height;
  37979. }
  37980. /*
  37981. * Automagically rotates an image based on its EXIF data (if present).
  37982. * @param img {Jimp} a Jimp image object
  37983. */
  37984. function exifRotate(img) {
  37985. if (getExifOrientation(img) < 2) return;
  37986. var transformation = getExifOrientationTransformation(img);
  37987. var swapDimensions = getExifOrientation(img) > 4;
  37988. var newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width;
  37989. var newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height;
  37990. transformBitmap(img, newWidth, newHeight, transformation);
  37991. } // parses a bitmap from the constructor to the JIMP bitmap property
  37992. function parseBitmap(data, path, cb) {
  37993. var mime = getMIMEFromBuffer(data, path);
  37994. if (typeof mime !== 'string') {
  37995. return cb(new Error('Could not find MIME for Buffer <' + path + '>'));
  37996. }
  37997. this._originalMime = mime.toLowerCase();
  37998. try {
  37999. var _mime = this.getMIME();
  38000. if (this.constructor.decoders[_mime]) {
  38001. this.bitmap = this.constructor.decoders[_mime](data);
  38002. } else {
  38003. return _utils.throwError.call(this, 'Unsupported MIME type: ' + _mime, cb);
  38004. }
  38005. } catch (error) {
  38006. return cb.call(this, error, this);
  38007. }
  38008. try {
  38009. this._exif = _exifParser["default"].create(data).parse();
  38010. exifRotate(this); // EXIF data
  38011. } catch (error) {
  38012. /* meh */
  38013. }
  38014. cb.call(this, null, this);
  38015. return this;
  38016. }
  38017. function compositeBitmapOverBackground(Jimp, image) {
  38018. return new Jimp(image.bitmap.width, image.bitmap.height, image._background).composite(image, 0, 0).bitmap;
  38019. }
  38020. /**
  38021. * Converts the image to a buffer
  38022. * @param {string} mime the mime type of the image buffer to be created
  38023. * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
  38024. * @returns {Jimp} this for chaining of methods
  38025. */
  38026. function getBuffer(mime, cb) {
  38027. if (mime === constants.AUTO) {
  38028. // allow auto MIME detection
  38029. mime = this.getMIME();
  38030. }
  38031. if (typeof mime !== 'string') {
  38032. return _utils.throwError.call(this, 'mime must be a string', cb);
  38033. }
  38034. if (typeof cb !== 'function') {
  38035. return _utils.throwError.call(this, 'cb must be a function', cb);
  38036. }
  38037. mime = mime.toLowerCase();
  38038. if (this._rgba && this.constructor.hasAlpha[mime]) {
  38039. this.bitmap.data = Buffer.from(this.bitmap.data);
  38040. } else {
  38041. // when format doesn't support alpha
  38042. // composite onto a new image so that the background shows through alpha channels
  38043. this.bitmap.data = compositeBitmapOverBackground(this.constructor, this).data;
  38044. }
  38045. if (this.constructor.encoders[mime]) {
  38046. var buffer = this.constructor.encoders[mime](this);
  38047. cb.call(this, null, buffer);
  38048. } else {
  38049. cb.call(this, 'Unsupported MIME type: ' + mime);
  38050. }
  38051. return this;
  38052. }
  38053. function getBufferAsync(mime) {
  38054. return (0, _promisify["default"])(getBuffer, this, mime);
  38055. }
  38056. }).call(this,require("buffer").Buffer)
  38057. },{"../constants":371,"./mime":376,"./promisify":377,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/slicedToArray":18,"@jimp/utils":414,"buffer":47,"exif-parser":240,"file-type":249}],376:[function(require,module,exports){
  38058. "use strict";
  38059. require("core-js/modules/es.array.find");
  38060. require("core-js/modules/es.array.includes");
  38061. require("core-js/modules/es.array.slice");
  38062. require("core-js/modules/es.object.entries");
  38063. require("core-js/modules/es.regexp.exec");
  38064. require("core-js/modules/es.string.includes");
  38065. require("core-js/modules/es.string.split");
  38066. Object.defineProperty(exports, "__esModule", {
  38067. value: true
  38068. });
  38069. exports.getExtension = exports.getType = exports.addType = void 0;
  38070. var mimeTypes = {};
  38071. var findType = function findType(extension) {
  38072. return Object.entries(mimeTypes).find(function (type) {
  38073. return type[1].includes(extension);
  38074. }) || [];
  38075. };
  38076. var addType = function addType(mime, extensions) {
  38077. mimeTypes[mime] = extensions;
  38078. };
  38079. /**
  38080. * Lookup a mime type based on extension
  38081. * @param {string} path path to find extension for
  38082. * @returns {string} mime found mime type
  38083. */
  38084. exports.addType = addType;
  38085. var getType = function getType(path) {
  38086. var pathParts = path.split('/').slice(-1);
  38087. var extension = pathParts[pathParts.length - 1].split('.').pop();
  38088. var type = findType(extension);
  38089. return type[0];
  38090. };
  38091. /**
  38092. * Return file extension associated with a mime type
  38093. * @param {string} type mime type to look up
  38094. * @returns {string} extension file extension
  38095. */
  38096. exports.getType = getType;
  38097. var getExtension = function getExtension(type) {
  38098. return (mimeTypes[type.toLowerCase()] || [])[0];
  38099. };
  38100. exports.getExtension = getExtension;
  38101. },{"core-js/modules/es.array.find":177,"core-js/modules/es.array.includes":179,"core-js/modules/es.array.slice":186,"core-js/modules/es.object.entries":193,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.includes":202,"core-js/modules/es.string.split":206}],377:[function(require,module,exports){
  38102. "use strict";
  38103. require("core-js/modules/es.function.bind");
  38104. require("core-js/modules/es.object.to-string");
  38105. require("core-js/modules/es.promise");
  38106. Object.defineProperty(exports, "__esModule", {
  38107. value: true
  38108. });
  38109. exports["default"] = void 0;
  38110. var promisify = function promisify(fun, ctx) {
  38111. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  38112. args[_key - 2] = arguments[_key];
  38113. }
  38114. return new Promise(function (resolve, reject) {
  38115. args.push(function (err, data) {
  38116. if (err) {
  38117. reject(err);
  38118. }
  38119. resolve(data);
  38120. });
  38121. fun.bind(ctx).apply(void 0, args);
  38122. });
  38123. };
  38124. var _default = promisify;
  38125. exports["default"] = _default;
  38126. module.exports = exports.default;
  38127. },{"core-js/modules/es.function.bind":188,"core-js/modules/es.object.to-string":197,"core-js/modules/es.promise":199}],378:[function(require,module,exports){
  38128. "use strict";
  38129. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
  38130. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  38131. require("core-js/modules/es.symbol");
  38132. require("core-js/modules/es.array.filter");
  38133. require("core-js/modules/es.array.for-each");
  38134. require("core-js/modules/es.array.is-array");
  38135. require("core-js/modules/es.object.define-properties");
  38136. require("core-js/modules/es.object.define-property");
  38137. require("core-js/modules/es.object.entries");
  38138. require("core-js/modules/es.object.get-own-property-descriptor");
  38139. require("core-js/modules/es.object.get-own-property-descriptors");
  38140. require("core-js/modules/es.object.keys");
  38141. require("core-js/modules/web.dom-collections.for-each");
  38142. Object.defineProperty(exports, "__esModule", {
  38143. value: true
  38144. });
  38145. exports["default"] = configure;
  38146. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  38147. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  38148. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
  38149. var _core = _interopRequireWildcard(require("@jimp/core"));
  38150. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  38151. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  38152. function configure(configuration) {
  38153. var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _core["default"];
  38154. var jimpConfig = {
  38155. hasAlpha: {},
  38156. encoders: {},
  38157. decoders: {},
  38158. "class": {},
  38159. constants: {}
  38160. };
  38161. function addToConfig(newConfig) {
  38162. Object.entries(newConfig).forEach(function (_ref) {
  38163. var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
  38164. key = _ref2[0],
  38165. value = _ref2[1];
  38166. jimpConfig[key] = _objectSpread({}, jimpConfig[key], {}, value);
  38167. });
  38168. }
  38169. function addImageType(typeModule) {
  38170. var type = typeModule();
  38171. if (Array.isArray(type.mime)) {
  38172. _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(type.mime));
  38173. } else {
  38174. Object.entries(type.mime).forEach(function (mimeType) {
  38175. return _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(mimeType));
  38176. });
  38177. }
  38178. delete type.mime;
  38179. addToConfig(type);
  38180. }
  38181. function addPlugin(pluginModule) {
  38182. var plugin = pluginModule(_core.jimpEvChange) || {};
  38183. if (!plugin["class"] && !plugin.constants) {
  38184. // Default to class function
  38185. addToConfig({
  38186. "class": plugin
  38187. });
  38188. } else {
  38189. addToConfig(plugin);
  38190. }
  38191. }
  38192. if (configuration.types) {
  38193. configuration.types.forEach(addImageType);
  38194. jimpInstance.decoders = _objectSpread({}, jimpInstance.decoders, {}, jimpConfig.decoders);
  38195. jimpInstance.encoders = _objectSpread({}, jimpInstance.encoders, {}, jimpConfig.encoders);
  38196. jimpInstance.hasAlpha = _objectSpread({}, jimpInstance.hasAlpha, {}, jimpConfig.hasAlpha);
  38197. }
  38198. if (configuration.plugins) {
  38199. configuration.plugins.forEach(addPlugin);
  38200. }
  38201. (0, _core.addJimpMethods)(jimpConfig["class"], jimpInstance);
  38202. (0, _core.addConstants)(jimpConfig.constants, jimpInstance);
  38203. return _core["default"];
  38204. }
  38205. module.exports = exports.default;
  38206. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/slicedToArray":18,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/core":372,"core-js/modules/es.array.filter":175,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.is-array":181,"core-js/modules/es.object.define-properties":191,"core-js/modules/es.object.define-property":192,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.get-own-property-descriptor":194,"core-js/modules/es.object.get-own-property-descriptors":195,"core-js/modules/es.object.keys":196,"core-js/modules/es.symbol":207,"core-js/modules/web.dom-collections.for-each":235}],379:[function(require,module,exports){
  38207. "use strict";
  38208. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  38209. Object.defineProperty(exports, "__esModule", {
  38210. value: true
  38211. });
  38212. exports["default"] = void 0;
  38213. var _custom = _interopRequireDefault(require("@jimp/custom"));
  38214. var _types = _interopRequireDefault(require("@jimp/types"));
  38215. var _plugins = _interopRequireDefault(require("@jimp/plugins"));
  38216. var _default = (0, _custom["default"])({
  38217. types: [_types["default"]],
  38218. plugins: [_plugins["default"]]
  38219. });
  38220. exports["default"] = _default;
  38221. module.exports = exports.default;
  38222. },{"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/custom":378,"@jimp/plugins":407,"@jimp/types":413}],380:[function(require,module,exports){
  38223. "use strict";
  38224. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  38225. Object.defineProperty(exports, "__esModule", {
  38226. value: true
  38227. });
  38228. exports["default"] = void 0;
  38229. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  38230. var _utils = require("@jimp/utils");
  38231. var _default = function _default() {
  38232. return {
  38233. /**
  38234. * Blits a source image on to this image
  38235. * @param {Jimp} src the source Jimp instance
  38236. * @param {number} x the x position to blit the image
  38237. * @param {number} y the y position to blit the image
  38238. * @param {number} srcx (optional) the x position from which to crop the source image
  38239. * @param {number} srcy (optional) the y position from which to crop the source image
  38240. * @param {number} srcw (optional) the width to which to crop the source image
  38241. * @param {number} srch (optional) the height to which to crop the source image
  38242. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38243. * @returns {Jimp} this for chaining of methods
  38244. */
  38245. blit: function blit(src, x, y, srcx, srcy, srcw, srch, cb) {
  38246. if (!(src instanceof this.constructor)) {
  38247. return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
  38248. }
  38249. if (typeof x !== 'number' || typeof y !== 'number') {
  38250. return _utils.throwError.call(this, 'x and y must be numbers', cb);
  38251. }
  38252. if (typeof srcx === 'function') {
  38253. cb = srcx;
  38254. srcx = 0;
  38255. srcy = 0;
  38256. srcw = src.bitmap.width;
  38257. srch = src.bitmap.height;
  38258. } else if ((0, _typeof2["default"])(srcx) === (0, _typeof2["default"])(srcy) && (0, _typeof2["default"])(srcy) === (0, _typeof2["default"])(srcw) && (0, _typeof2["default"])(srcw) === (0, _typeof2["default"])(srch)) {
  38259. srcx = srcx || 0;
  38260. srcy = srcy || 0;
  38261. srcw = srcw || src.bitmap.width;
  38262. srch = srch || src.bitmap.height;
  38263. } else {
  38264. return _utils.throwError.call(this, 'srcx, srcy, srcw, srch must be numbers', cb);
  38265. } // round input
  38266. x = Math.round(x);
  38267. y = Math.round(y); // round input
  38268. srcx = Math.round(srcx);
  38269. srcy = Math.round(srcy);
  38270. srcw = Math.round(srcw);
  38271. srch = Math.round(srch);
  38272. var maxWidth = this.bitmap.width;
  38273. var maxHeight = this.bitmap.height;
  38274. var baseImage = this;
  38275. src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) {
  38276. var xOffset = x + sx - srcx;
  38277. var yOffset = y + sy - srcy;
  38278. if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) {
  38279. var dstIdx = baseImage.getPixelIndex(xOffset, yOffset);
  38280. var _src = {
  38281. r: this.bitmap.data[idx],
  38282. g: this.bitmap.data[idx + 1],
  38283. b: this.bitmap.data[idx + 2],
  38284. a: this.bitmap.data[idx + 3]
  38285. };
  38286. var dst = {
  38287. r: baseImage.bitmap.data[dstIdx],
  38288. g: baseImage.bitmap.data[dstIdx + 1],
  38289. b: baseImage.bitmap.data[dstIdx + 2],
  38290. a: baseImage.bitmap.data[dstIdx + 3]
  38291. };
  38292. baseImage.bitmap.data[dstIdx] = (_src.a * (_src.r - dst.r) - dst.r + 255 >> 8) + dst.r;
  38293. baseImage.bitmap.data[dstIdx + 1] = (_src.a * (_src.g - dst.g) - dst.g + 255 >> 8) + dst.g;
  38294. baseImage.bitmap.data[dstIdx + 2] = (_src.a * (_src.b - dst.b) - dst.b + 255 >> 8) + dst.b;
  38295. baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(dst.a + _src.a);
  38296. }
  38297. });
  38298. if ((0, _utils.isNodePattern)(cb)) {
  38299. cb.call(this, null, this);
  38300. }
  38301. return this;
  38302. }
  38303. };
  38304. };
  38305. exports["default"] = _default;
  38306. module.exports = exports.default;
  38307. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414}],381:[function(require,module,exports){
  38308. "use strict";
  38309. Object.defineProperty(exports, "__esModule", {
  38310. value: true
  38311. });
  38312. exports.shgTable = exports.mulTable = void 0;
  38313. var mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];
  38314. exports.mulTable = mulTable;
  38315. var shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];
  38316. exports.shgTable = shgTable;
  38317. },{}],382:[function(require,module,exports){
  38318. "use strict";
  38319. Object.defineProperty(exports, "__esModule", {
  38320. value: true
  38321. });
  38322. exports["default"] = void 0;
  38323. var _utils = require("@jimp/utils");
  38324. var _blurTables = require("./blur-tables");
  38325. /*
  38326. Superfast Blur (0.5)
  38327. http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js
  38328. Copyright (c) 2011 Mario Klingemann
  38329. Permission is hereby granted, free of charge, to any person
  38330. obtaining a copy of this software and associated documentation
  38331. files (the "Software"), to deal in the Software without
  38332. restriction, including without limitation the rights to use,
  38333. copy, modify, merge, publish, distribute, sublicense, and/or sell
  38334. copies of the Software, and to permit persons to whom the
  38335. Software is furnished to do so, subject to the following
  38336. conditions:
  38337. The above copyright notice and this permission notice shall be
  38338. included in all copies or substantial portions of the Software.
  38339. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  38340. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  38341. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  38342. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  38343. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  38344. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  38345. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  38346. OTHER DEALINGS IN THE SOFTWARE.
  38347. */
  38348. var _default = function _default() {
  38349. return {
  38350. /**
  38351. * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker
  38352. * @param {number} r the pixel radius of the blur
  38353. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38354. * @returns {Jimp} this for chaining of methods
  38355. */
  38356. blur: function blur(r, cb) {
  38357. if (typeof r !== 'number') return _utils.throwError.call(this, 'r must be a number', cb);
  38358. if (r < 1) return _utils.throwError.call(this, 'r must be greater than 0', cb);
  38359. var rsum;
  38360. var gsum;
  38361. var bsum;
  38362. var asum;
  38363. var x;
  38364. var y;
  38365. var i;
  38366. var p;
  38367. var p1;
  38368. var p2;
  38369. var yp;
  38370. var yi;
  38371. var yw;
  38372. var pa;
  38373. var wm = this.bitmap.width - 1;
  38374. var hm = this.bitmap.height - 1; // const wh = this.bitmap.width * this.bitmap.height;
  38375. var rad1 = r + 1;
  38376. var mulSum = _blurTables.mulTable[r];
  38377. var shgSum = _blurTables.shgTable[r];
  38378. var red = [];
  38379. var green = [];
  38380. var blue = [];
  38381. var alpha = [];
  38382. var vmin = [];
  38383. var vmax = [];
  38384. var iterations = 2;
  38385. while (iterations-- > 0) {
  38386. yi = 0;
  38387. yw = 0;
  38388. for (y = 0; y < this.bitmap.height; y++) {
  38389. rsum = this.bitmap.data[yw] * rad1;
  38390. gsum = this.bitmap.data[yw + 1] * rad1;
  38391. bsum = this.bitmap.data[yw + 2] * rad1;
  38392. asum = this.bitmap.data[yw + 3] * rad1;
  38393. for (i = 1; i <= r; i++) {
  38394. p = yw + ((i > wm ? wm : i) << 2);
  38395. rsum += this.bitmap.data[p++];
  38396. gsum += this.bitmap.data[p++];
  38397. bsum += this.bitmap.data[p++];
  38398. asum += this.bitmap.data[p];
  38399. }
  38400. for (x = 0; x < this.bitmap.width; x++) {
  38401. red[yi] = rsum;
  38402. green[yi] = gsum;
  38403. blue[yi] = bsum;
  38404. alpha[yi] = asum;
  38405. if (y === 0) {
  38406. vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;
  38407. vmax[x] = (p = x - r) > 0 ? p << 2 : 0;
  38408. }
  38409. p1 = yw + vmin[x];
  38410. p2 = yw + vmax[x];
  38411. rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
  38412. gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
  38413. bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
  38414. asum += this.bitmap.data[p1] - this.bitmap.data[p2];
  38415. yi++;
  38416. }
  38417. yw += this.bitmap.width << 2;
  38418. }
  38419. for (x = 0; x < this.bitmap.width; x++) {
  38420. yp = x;
  38421. rsum = red[yp] * rad1;
  38422. gsum = green[yp] * rad1;
  38423. bsum = blue[yp] * rad1;
  38424. asum = alpha[yp] * rad1;
  38425. for (i = 1; i <= r; i++) {
  38426. yp += i > hm ? 0 : this.bitmap.width;
  38427. rsum += red[yp];
  38428. gsum += green[yp];
  38429. bsum += blue[yp];
  38430. asum += alpha[yp];
  38431. }
  38432. yi = x << 2;
  38433. for (y = 0; y < this.bitmap.height; y++) {
  38434. pa = asum * mulSum >>> shgSum;
  38435. this.bitmap.data[yi + 3] = pa; // normalize alpha
  38436. if (pa > 255) {
  38437. this.bitmap.data[yi + 3] = 255;
  38438. }
  38439. if (pa > 0) {
  38440. pa = 255 / pa;
  38441. this.bitmap.data[yi] = (rsum * mulSum >>> shgSum) * pa;
  38442. this.bitmap.data[yi + 1] = (gsum * mulSum >>> shgSum) * pa;
  38443. this.bitmap.data[yi + 2] = (bsum * mulSum >>> shgSum) * pa;
  38444. } else {
  38445. this.bitmap.data[yi + 2] = 0;
  38446. this.bitmap.data[yi + 1] = 0;
  38447. this.bitmap.data[yi] = 0;
  38448. }
  38449. if (x === 0) {
  38450. vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width;
  38451. vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0;
  38452. }
  38453. p1 = x + vmin[y];
  38454. p2 = x + vmax[y];
  38455. rsum += red[p1] - red[p2];
  38456. gsum += green[p1] - green[p2];
  38457. bsum += blue[p1] - blue[p2];
  38458. asum += alpha[p1] - alpha[p2];
  38459. yi += this.bitmap.width << 2;
  38460. }
  38461. }
  38462. }
  38463. if ((0, _utils.isNodePattern)(cb)) {
  38464. cb.call(this, null, this);
  38465. }
  38466. return this;
  38467. }
  38468. };
  38469. };
  38470. exports["default"] = _default;
  38471. module.exports = exports.default;
  38472. },{"./blur-tables":381,"@jimp/utils":414}],383:[function(require,module,exports){
  38473. "use strict";
  38474. Object.defineProperty(exports, "__esModule", {
  38475. value: true
  38476. });
  38477. exports["default"] = void 0;
  38478. var _utils = require("@jimp/utils");
  38479. /**
  38480. * Creates a circle out of an image.
  38481. * @param {function(Error, Jimp)} options (optional) radius, x, y
  38482. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38483. * @returns {Jimp} this for chaining of methods
  38484. */
  38485. var _default = function _default() {
  38486. return {
  38487. circle: function circle() {
  38488. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  38489. var cb = arguments.length > 1 ? arguments[1] : undefined;
  38490. if (typeof options === 'function') {
  38491. cb = options;
  38492. options = {};
  38493. }
  38494. var radius = options.radius || (this.bitmap.width > this.bitmap.height ? this.bitmap.height : this.bitmap.width) / 2;
  38495. var center = {
  38496. x: typeof options.x === 'number' ? options.x : this.bitmap.width / 2,
  38497. y: typeof options.y === 'number' ? options.y : this.bitmap.height / 2
  38498. };
  38499. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38500. var curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));
  38501. if (radius - curR <= 0.0) {
  38502. this.bitmap.data[idx + 3] = 0;
  38503. } else if (radius - curR < 1.0) {
  38504. this.bitmap.data[idx + 3] = 255 * (radius - curR);
  38505. }
  38506. });
  38507. if ((0, _utils.isNodePattern)(cb)) {
  38508. cb.call(this, null, this);
  38509. }
  38510. return this;
  38511. }
  38512. };
  38513. };
  38514. exports["default"] = _default;
  38515. module.exports = exports.default;
  38516. },{"@jimp/utils":414}],384:[function(require,module,exports){
  38517. (function (Buffer){
  38518. "use strict";
  38519. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  38520. require("core-js/modules/es.array.for-each");
  38521. require("core-js/modules/es.array.is-array");
  38522. require("core-js/modules/es.array.map");
  38523. require("core-js/modules/es.parse-int");
  38524. require("core-js/modules/web.dom-collections.for-each");
  38525. Object.defineProperty(exports, "__esModule", {
  38526. value: true
  38527. });
  38528. exports["default"] = void 0;
  38529. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  38530. var _tinycolor = _interopRequireDefault(require("tinycolor2"));
  38531. var _utils = require("@jimp/utils");
  38532. function applyKernel(im, kernel, x, y) {
  38533. var value = [0, 0, 0];
  38534. var size = (kernel.length - 1) / 2;
  38535. for (var kx = 0; kx < kernel.length; kx += 1) {
  38536. for (var ky = 0; ky < kernel[kx].length; ky += 1) {
  38537. var idx = im.getPixelIndex(x + kx - size, y + ky - size);
  38538. value[0] += im.bitmap.data[idx] * kernel[kx][ky];
  38539. value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky];
  38540. value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky];
  38541. }
  38542. }
  38543. return value;
  38544. }
  38545. var isDef = function isDef(v) {
  38546. return typeof v !== 'undefined' && v !== null;
  38547. };
  38548. function greyscale(cb) {
  38549. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38550. var grey = parseInt(0.2126 * this.bitmap.data[idx] + 0.7152 * this.bitmap.data[idx + 1] + 0.0722 * this.bitmap.data[idx + 2], 10);
  38551. this.bitmap.data[idx] = grey;
  38552. this.bitmap.data[idx + 1] = grey;
  38553. this.bitmap.data[idx + 2] = grey;
  38554. });
  38555. if ((0, _utils.isNodePattern)(cb)) {
  38556. cb.call(this, null, this);
  38557. }
  38558. return this;
  38559. }
  38560. function mix(clr, clr2) {
  38561. var p = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
  38562. return {
  38563. r: (clr2.r - clr.r) * (p / 100) + clr.r,
  38564. g: (clr2.g - clr.g) * (p / 100) + clr.g,
  38565. b: (clr2.b - clr.b) * (p / 100) + clr.b
  38566. };
  38567. }
  38568. function colorFn(actions, cb) {
  38569. var _this = this;
  38570. if (!actions || !Array.isArray(actions)) {
  38571. return _utils.throwError.call(this, 'actions must be an array', cb);
  38572. }
  38573. actions = actions.map(function (action) {
  38574. if (action.apply === 'xor' || action.apply === 'mix') {
  38575. action.params[0] = (0, _tinycolor["default"])(action.params[0]).toRgb();
  38576. }
  38577. return action;
  38578. });
  38579. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38580. var clr = {
  38581. r: _this.bitmap.data[idx],
  38582. g: _this.bitmap.data[idx + 1],
  38583. b: _this.bitmap.data[idx + 2]
  38584. };
  38585. var colorModifier = function colorModifier(i, amount) {
  38586. return _this.constructor.limit255(clr[i] + amount);
  38587. };
  38588. actions.forEach(function (action) {
  38589. if (action.apply === 'mix') {
  38590. clr = mix(clr, action.params[0], action.params[1]);
  38591. } else if (action.apply === 'tint') {
  38592. clr = mix(clr, {
  38593. r: 255,
  38594. g: 255,
  38595. b: 255
  38596. }, action.params[0]);
  38597. } else if (action.apply === 'shade') {
  38598. clr = mix(clr, {
  38599. r: 0,
  38600. g: 0,
  38601. b: 0
  38602. }, action.params[0]);
  38603. } else if (action.apply === 'xor') {
  38604. clr = {
  38605. r: clr.r ^ action.params[0].r,
  38606. g: clr.g ^ action.params[0].g,
  38607. b: clr.b ^ action.params[0].b
  38608. };
  38609. } else if (action.apply === 'red') {
  38610. clr.r = colorModifier('r', action.params[0]);
  38611. } else if (action.apply === 'green') {
  38612. clr.g = colorModifier('g', action.params[0]);
  38613. } else if (action.apply === 'blue') {
  38614. clr.b = colorModifier('b', action.params[0]);
  38615. } else {
  38616. var _clr;
  38617. if (action.apply === 'hue') {
  38618. action.apply = 'spin';
  38619. }
  38620. clr = (0, _tinycolor["default"])(clr);
  38621. if (!clr[action.apply]) {
  38622. return _utils.throwError.call(_this, 'action ' + action.apply + ' not supported', cb);
  38623. }
  38624. clr = (_clr = clr)[action.apply].apply(_clr, (0, _toConsumableArray2["default"])(action.params)).toRgb();
  38625. }
  38626. });
  38627. _this.bitmap.data[idx] = clr.r;
  38628. _this.bitmap.data[idx + 1] = clr.g;
  38629. _this.bitmap.data[idx + 2] = clr.b;
  38630. });
  38631. if ((0, _utils.isNodePattern)(cb)) {
  38632. cb.call(this, null, this);
  38633. }
  38634. return this;
  38635. }
  38636. var _default = function _default() {
  38637. return {
  38638. /**
  38639. * Adjusts the brightness of the image
  38640. * @param {number} val the amount to adjust the brightness, a number between -1 and +1
  38641. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38642. * @returns {Jimp }this for chaining of methods
  38643. */
  38644. brightness: function brightness(val, cb) {
  38645. if (typeof val !== 'number') {
  38646. return _utils.throwError.call(this, 'val must be numbers', cb);
  38647. }
  38648. if (val < -1 || val > +1) {
  38649. return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb);
  38650. }
  38651. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38652. if (val < 0.0) {
  38653. this.bitmap.data[idx] = this.bitmap.data[idx] * (1 + val);
  38654. this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] * (1 + val);
  38655. this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] * (1 + val);
  38656. } else {
  38657. this.bitmap.data[idx] = this.bitmap.data[idx] + (255 - this.bitmap.data[idx]) * val;
  38658. this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] + (255 - this.bitmap.data[idx + 1]) * val;
  38659. this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] + (255 - this.bitmap.data[idx + 2]) * val;
  38660. }
  38661. });
  38662. if ((0, _utils.isNodePattern)(cb)) {
  38663. cb.call(this, null, this);
  38664. }
  38665. return this;
  38666. },
  38667. /**
  38668. * Adjusts the contrast of the image
  38669. * @param {number} val the amount to adjust the contrast, a number between -1 and +1
  38670. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38671. * @returns {Jimp }this for chaining of methods
  38672. */
  38673. contrast: function contrast(val, cb) {
  38674. if (typeof val !== 'number') {
  38675. return _utils.throwError.call(this, 'val must be numbers', cb);
  38676. }
  38677. if (val < -1 || val > +1) {
  38678. return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb);
  38679. }
  38680. var factor = (val + 1) / (1 - val);
  38681. function adjust(value) {
  38682. value = Math.floor(factor * (value - 127) + 127);
  38683. return value < 0 ? 0 : value > 255 ? 255 : value;
  38684. }
  38685. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38686. this.bitmap.data[idx] = adjust(this.bitmap.data[idx]);
  38687. this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]);
  38688. this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]);
  38689. });
  38690. if ((0, _utils.isNodePattern)(cb)) {
  38691. cb.call(this, null, this);
  38692. }
  38693. return this;
  38694. },
  38695. /**
  38696. * Apply a posterize effect
  38697. * @param {number} n the amount to adjust the contrast, minimum threshold is two
  38698. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38699. * @returns {Jimp }this for chaining of methods
  38700. */
  38701. posterize: function posterize(n, cb) {
  38702. if (typeof n !== 'number') {
  38703. return _utils.throwError.call(this, 'n must be numbers', cb);
  38704. }
  38705. if (n < 2) {
  38706. n = 2;
  38707. } // minimum of 2 levels
  38708. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38709. this.bitmap.data[idx] = Math.floor(this.bitmap.data[idx] / 255 * (n - 1)) / (n - 1) * 255;
  38710. this.bitmap.data[idx + 1] = Math.floor(this.bitmap.data[idx + 1] / 255 * (n - 1)) / (n - 1) * 255;
  38711. this.bitmap.data[idx + 2] = Math.floor(this.bitmap.data[idx + 2] / 255 * (n - 1)) / (n - 1) * 255;
  38712. });
  38713. if ((0, _utils.isNodePattern)(cb)) {
  38714. cb.call(this, null, this);
  38715. }
  38716. return this;
  38717. },
  38718. /**
  38719. * Removes colour from the image using ITU Rec 709 luminance values
  38720. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38721. * @returns {Jimp }this for chaining of methods
  38722. */
  38723. greyscale: greyscale,
  38724. // Alias of greyscale for our American friends
  38725. grayscale: greyscale,
  38726. /**
  38727. * Multiplies the opacity of each pixel by a factor between 0 and 1
  38728. * @param {number} f A number, the factor by which to multiply the opacity of each pixel
  38729. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38730. * @returns {Jimp }this for chaining of methods
  38731. */
  38732. opacity: function opacity(f, cb) {
  38733. if (typeof f !== 'number') return _utils.throwError.call(this, 'f must be a number', cb);
  38734. if (f < 0 || f > 1) return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb);
  38735. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38736. var v = this.bitmap.data[idx + 3] * f;
  38737. this.bitmap.data[idx + 3] = v;
  38738. });
  38739. if ((0, _utils.isNodePattern)(cb)) {
  38740. cb.call(this, null, this);
  38741. }
  38742. return this;
  38743. },
  38744. /**
  38745. * Applies a sepia tone to the image
  38746. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38747. * @returns {Jimp }this for chaining of methods
  38748. */
  38749. sepia: function sepia(cb) {
  38750. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38751. var red = this.bitmap.data[idx];
  38752. var green = this.bitmap.data[idx + 1];
  38753. var blue = this.bitmap.data[idx + 2];
  38754. red = red * 0.393 + green * 0.769 + blue * 0.189;
  38755. green = red * 0.349 + green * 0.686 + blue * 0.168;
  38756. blue = red * 0.272 + green * 0.534 + blue * 0.131;
  38757. this.bitmap.data[idx] = red < 255 ? red : 255;
  38758. this.bitmap.data[idx + 1] = green < 255 ? green : 255;
  38759. this.bitmap.data[idx + 2] = blue < 255 ? blue : 255;
  38760. });
  38761. if ((0, _utils.isNodePattern)(cb)) {
  38762. cb.call(this, null, this);
  38763. }
  38764. return this;
  38765. },
  38766. /**
  38767. * Fades each pixel by a factor between 0 and 1
  38768. * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent.
  38769. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38770. * @returns {Jimp }this for chaining of methods
  38771. */
  38772. fade: function fade(f, cb) {
  38773. if (typeof f !== 'number') {
  38774. return _utils.throwError.call(this, 'f must be a number', cb);
  38775. }
  38776. if (f < 0 || f > 1) {
  38777. return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb);
  38778. } // this method is an alternative to opacity (which may be deprecated)
  38779. this.opacity(1 - f);
  38780. if ((0, _utils.isNodePattern)(cb)) {
  38781. cb.call(this, null, this);
  38782. }
  38783. return this;
  38784. },
  38785. /**
  38786. * Adds each element of the image to its local neighbors, weighted by the kernel
  38787. * @param {array} kernel a matrix to weight the neighbors sum
  38788. * @param {string} edgeHandling (optional) define how to sum pixels from outside the border
  38789. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38790. * @returns {Jimp }this for chaining of methods
  38791. */
  38792. convolution: function convolution(kernel, edgeHandling, cb) {
  38793. if (typeof edgeHandling === 'function' && typeof cb === 'undefined') {
  38794. cb = edgeHandling;
  38795. edgeHandling = null;
  38796. }
  38797. if (!edgeHandling) {
  38798. edgeHandling = this.constructor.EDGE_EXTEND;
  38799. }
  38800. var newData = Buffer.from(this.bitmap.data);
  38801. var kRows = kernel.length;
  38802. var kCols = kernel[0].length;
  38803. var rowEnd = Math.floor(kRows / 2);
  38804. var colEnd = Math.floor(kCols / 2);
  38805. var rowIni = -rowEnd;
  38806. var colIni = -colEnd;
  38807. var weight;
  38808. var rSum;
  38809. var gSum;
  38810. var bSum;
  38811. var ri;
  38812. var gi;
  38813. var bi;
  38814. var xi;
  38815. var yi;
  38816. var idxi;
  38817. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38818. bSum = 0;
  38819. gSum = 0;
  38820. rSum = 0;
  38821. for (var row = rowIni; row <= rowEnd; row++) {
  38822. for (var col = colIni; col <= colEnd; col++) {
  38823. xi = x + col;
  38824. yi = y + row;
  38825. weight = kernel[row + rowEnd][col + colEnd];
  38826. idxi = this.getPixelIndex(xi, yi, edgeHandling);
  38827. if (idxi === -1) {
  38828. bi = 0;
  38829. gi = 0;
  38830. ri = 0;
  38831. } else {
  38832. ri = this.bitmap.data[idxi + 0];
  38833. gi = this.bitmap.data[idxi + 1];
  38834. bi = this.bitmap.data[idxi + 2];
  38835. }
  38836. rSum += weight * ri;
  38837. gSum += weight * gi;
  38838. bSum += weight * bi;
  38839. }
  38840. }
  38841. if (rSum < 0) {
  38842. rSum = 0;
  38843. }
  38844. if (gSum < 0) {
  38845. gSum = 0;
  38846. }
  38847. if (bSum < 0) {
  38848. bSum = 0;
  38849. }
  38850. if (rSum > 255) {
  38851. rSum = 255;
  38852. }
  38853. if (gSum > 255) {
  38854. gSum = 255;
  38855. }
  38856. if (bSum > 255) {
  38857. bSum = 255;
  38858. }
  38859. newData[idx + 0] = rSum;
  38860. newData[idx + 1] = gSum;
  38861. newData[idx + 2] = bSum;
  38862. });
  38863. this.bitmap.data = newData;
  38864. if ((0, _utils.isNodePattern)(cb)) {
  38865. cb.call(this, null, this);
  38866. }
  38867. return this;
  38868. },
  38869. /**
  38870. * Set the alpha channel on every pixel to fully opaque
  38871. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38872. * @returns {Jimp }this for chaining of methods
  38873. */
  38874. opaque: function opaque(cb) {
  38875. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  38876. this.bitmap.data[idx + 3] = 255;
  38877. });
  38878. if ((0, _utils.isNodePattern)(cb)) {
  38879. cb.call(this, null, this);
  38880. }
  38881. return this;
  38882. },
  38883. /**
  38884. * Pixelates the image or a region
  38885. * @param {number} size the size of the pixels
  38886. * @param {number} x (optional) the x position of the region to pixelate
  38887. * @param {number} y (optional) the y position of the region to pixelate
  38888. * @param {number} w (optional) the width of the region to pixelate
  38889. * @param {number} h (optional) the height of the region to pixelate
  38890. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38891. * @returns {Jimp }this for chaining of methods
  38892. */
  38893. pixelate: function pixelate(size, x, y, w, h, cb) {
  38894. if (typeof x === 'function') {
  38895. cb = x;
  38896. h = null;
  38897. w = null;
  38898. y = null;
  38899. x = null;
  38900. } else {
  38901. if (typeof size !== 'number') {
  38902. return _utils.throwError.call(this, 'size must be a number', cb);
  38903. }
  38904. if (isDef(x) && typeof x !== 'number') {
  38905. return _utils.throwError.call(this, 'x must be a number', cb);
  38906. }
  38907. if (isDef(y) && typeof y !== 'number') {
  38908. return _utils.throwError.call(this, 'y must be a number', cb);
  38909. }
  38910. if (isDef(w) && typeof w !== 'number') {
  38911. return _utils.throwError.call(this, 'w must be a number', cb);
  38912. }
  38913. if (isDef(h) && typeof h !== 'number') {
  38914. return _utils.throwError.call(this, 'h must be a number', cb);
  38915. }
  38916. }
  38917. var kernel = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 4 / 16, 2 / 16], [1 / 16, 2 / 16, 1 / 16]];
  38918. x = x || 0;
  38919. y = y || 0;
  38920. w = isDef(w) ? w : this.bitmap.width - x;
  38921. h = isDef(h) ? h : this.bitmap.height - y;
  38922. var source = this.cloneQuiet();
  38923. this.scanQuiet(x, y, w, h, function (xx, yx, idx) {
  38924. xx = size * Math.floor(xx / size);
  38925. yx = size * Math.floor(yx / size);
  38926. var value = applyKernel(source, kernel, xx, yx);
  38927. this.bitmap.data[idx] = value[0];
  38928. this.bitmap.data[idx + 1] = value[1];
  38929. this.bitmap.data[idx + 2] = value[2];
  38930. });
  38931. if ((0, _utils.isNodePattern)(cb)) {
  38932. cb.call(this, null, this);
  38933. }
  38934. return this;
  38935. },
  38936. /**
  38937. * Applies a convolution kernel to the image or a region
  38938. * @param {array} kernel the convolution kernel
  38939. * @param {number} x (optional) the x position of the region to apply convolution to
  38940. * @param {number} y (optional) the y position of the region to apply convolution to
  38941. * @param {number} w (optional) the width of the region to apply convolution to
  38942. * @param {number} h (optional) the height of the region to apply convolution to
  38943. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38944. * @returns {Jimp }this for chaining of methods
  38945. */
  38946. convolute: function convolute(kernel, x, y, w, h, cb) {
  38947. if (!Array.isArray(kernel)) return _utils.throwError.call(this, 'the kernel must be an array', cb);
  38948. if (typeof x === 'function') {
  38949. cb = x;
  38950. x = null;
  38951. y = null;
  38952. w = null;
  38953. h = null;
  38954. } else {
  38955. if (isDef(x) && typeof x !== 'number') {
  38956. return _utils.throwError.call(this, 'x must be a number', cb);
  38957. }
  38958. if (isDef(y) && typeof y !== 'number') {
  38959. return _utils.throwError.call(this, 'y must be a number', cb);
  38960. }
  38961. if (isDef(w) && typeof w !== 'number') {
  38962. return _utils.throwError.call(this, 'w must be a number', cb);
  38963. }
  38964. if (isDef(h) && typeof h !== 'number') {
  38965. return _utils.throwError.call(this, 'h must be a number', cb);
  38966. }
  38967. }
  38968. var ksize = (kernel.length - 1) / 2;
  38969. x = isDef(x) ? x : ksize;
  38970. y = isDef(y) ? y : ksize;
  38971. w = isDef(w) ? w : this.bitmap.width - x;
  38972. h = isDef(h) ? h : this.bitmap.height - y;
  38973. var source = this.cloneQuiet();
  38974. this.scanQuiet(x, y, w, h, function (xx, yx, idx) {
  38975. var value = applyKernel(source, kernel, xx, yx);
  38976. this.bitmap.data[idx] = this.constructor.limit255(value[0]);
  38977. this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]);
  38978. this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]);
  38979. });
  38980. if ((0, _utils.isNodePattern)(cb)) {
  38981. cb.call(this, null, this);
  38982. }
  38983. return this;
  38984. },
  38985. /**
  38986. * Apply multiple color modification rules
  38987. * @param {array} actions list of color modification rules, in following format: { apply: '<rule-name>', params: [ <rule-parameters> ] }
  38988. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  38989. * @returns {Jimp }this for chaining of methods
  38990. */
  38991. color: colorFn,
  38992. colour: colorFn
  38993. };
  38994. };
  38995. exports["default"] = _default;
  38996. module.exports = exports.default;
  38997. }).call(this,require("buffer").Buffer)
  38998. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/utils":414,"buffer":47,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.is-array":181,"core-js/modules/es.array.map":184,"core-js/modules/es.parse-int":198,"core-js/modules/web.dom-collections.for-each":235,"tinycolor2":357}],385:[function(require,module,exports){
  38999. "use strict";
  39000. Object.defineProperty(exports, "__esModule", {
  39001. value: true
  39002. });
  39003. exports["default"] = void 0;
  39004. var _utils = require("@jimp/utils");
  39005. /**
  39006. * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.
  39007. * @param {number} w the width to resize the image to
  39008. * @param {number} h the height to resize the image to
  39009. * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment
  39010. * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
  39011. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39012. * @returns {Jimp} this for chaining of methods
  39013. */
  39014. var _default = function _default() {
  39015. return {
  39016. contain: function contain(w, h, alignBits, mode, cb) {
  39017. if (typeof w !== 'number' || typeof h !== 'number') {
  39018. return _utils.throwError.call(this, 'w and h must be numbers', cb);
  39019. } // permit any sort of optional parameters combination
  39020. if (typeof alignBits === 'string') {
  39021. if (typeof mode === 'function' && typeof cb === 'undefined') cb = mode;
  39022. mode = alignBits;
  39023. alignBits = null;
  39024. }
  39025. if (typeof alignBits === 'function') {
  39026. if (typeof cb === 'undefined') cb = alignBits;
  39027. mode = null;
  39028. alignBits = null;
  39029. }
  39030. if (typeof mode === 'function' && typeof cb === 'undefined') {
  39031. cb = mode;
  39032. mode = null;
  39033. }
  39034. alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;
  39035. var hbits = alignBits & (1 << 3) - 1;
  39036. var vbits = alignBits >> 3; // check if more flags than one is in the bit sets
  39037. if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) {
  39038. return _utils.throwError.call(this, 'only use one flag per alignment direction', cb);
  39039. }
  39040. var alignH = hbits >> 1; // 0, 1, 2
  39041. var alignV = vbits >> 1; // 0, 1, 2
  39042. var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;
  39043. var c = this.cloneQuiet().scale(f, mode);
  39044. this.resize(w, h, mode);
  39045. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39046. this.bitmap.data.writeUInt32BE(this._background, idx);
  39047. });
  39048. this.blit(c, (this.bitmap.width - c.bitmap.width) / 2 * alignH, (this.bitmap.height - c.bitmap.height) / 2 * alignV);
  39049. if ((0, _utils.isNodePattern)(cb)) {
  39050. cb.call(this, null, this);
  39051. }
  39052. return this;
  39053. }
  39054. };
  39055. };
  39056. exports["default"] = _default;
  39057. module.exports = exports.default;
  39058. },{"@jimp/utils":414}],386:[function(require,module,exports){
  39059. "use strict";
  39060. Object.defineProperty(exports, "__esModule", {
  39061. value: true
  39062. });
  39063. exports["default"] = void 0;
  39064. var _utils = require("@jimp/utils");
  39065. /**
  39066. * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped.
  39067. * @param {number} w the width to resize the image to
  39068. * @param {number} h the height to resize the image to
  39069. * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment
  39070. * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
  39071. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39072. * @returns {Jimp} this for chaining of methods
  39073. */
  39074. var _default = function _default() {
  39075. return {
  39076. cover: function cover(w, h, alignBits, mode, cb) {
  39077. if (typeof w !== 'number' || typeof h !== 'number') {
  39078. return _utils.throwError.call(this, 'w and h must be numbers', cb);
  39079. }
  39080. if (alignBits && typeof alignBits === 'function' && typeof cb === 'undefined') {
  39081. cb = alignBits;
  39082. alignBits = null;
  39083. mode = null;
  39084. } else if (typeof mode === 'function' && typeof cb === 'undefined') {
  39085. cb = mode;
  39086. mode = null;
  39087. }
  39088. alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;
  39089. var hbits = alignBits & (1 << 3) - 1;
  39090. var vbits = alignBits >> 3; // check if more flags than one is in the bit sets
  39091. if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) return _utils.throwError.call(this, 'only use one flag per alignment direction', cb);
  39092. var alignH = hbits >> 1; // 0, 1, 2
  39093. var alignV = vbits >> 1; // 0, 1, 2
  39094. var f = w / h > this.bitmap.width / this.bitmap.height ? w / this.bitmap.width : h / this.bitmap.height;
  39095. this.scale(f, mode);
  39096. this.crop((this.bitmap.width - w) / 2 * alignH, (this.bitmap.height - h) / 2 * alignV, w, h);
  39097. if ((0, _utils.isNodePattern)(cb)) {
  39098. cb.call(this, null, this);
  39099. }
  39100. return this;
  39101. }
  39102. };
  39103. };
  39104. exports["default"] = _default;
  39105. module.exports = exports.default;
  39106. },{"@jimp/utils":414}],387:[function(require,module,exports){
  39107. (function (Buffer){
  39108. "use strict";
  39109. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  39110. require("core-js/modules/es.array.slice");
  39111. Object.defineProperty(exports, "__esModule", {
  39112. value: true
  39113. });
  39114. exports["default"] = pluginCrop;
  39115. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  39116. var _utils = require("@jimp/utils");
  39117. /* eslint-disable no-labels */
  39118. function pluginCrop(event) {
  39119. /**
  39120. * Crops the image at a given point to a give size
  39121. * @param {number} x the x coordinate to crop form
  39122. * @param {number} y the y coordinate to crop form
  39123. * @param w the width of the crop region
  39124. * @param h the height of the crop region
  39125. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39126. * @returns {Jimp} this for chaining of methods
  39127. */
  39128. event('crop', function (x, y, w, h, cb) {
  39129. if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb);
  39130. if (typeof w !== 'number' || typeof h !== 'number') return _utils.throwError.call(this, 'w and h must be numbers', cb); // round input
  39131. x = Math.round(x);
  39132. y = Math.round(y);
  39133. w = Math.round(w);
  39134. h = Math.round(h);
  39135. if (x === 0 && w === this.bitmap.width) {
  39136. // shortcut
  39137. var start = w * y + x << 2;
  39138. var end = start + h * w << 2;
  39139. this.bitmap.data = this.bitmap.data.slice(start, end);
  39140. } else {
  39141. var bitmap = Buffer.allocUnsafe(w * h * 4);
  39142. var offset = 0;
  39143. this.scanQuiet(x, y, w, h, function (x, y, idx) {
  39144. var data = this.bitmap.data.readUInt32BE(idx, true);
  39145. bitmap.writeUInt32BE(data, offset, true);
  39146. offset += 4;
  39147. });
  39148. this.bitmap.data = bitmap;
  39149. }
  39150. this.bitmap.width = w;
  39151. this.bitmap.height = h;
  39152. if ((0, _utils.isNodePattern)(cb)) {
  39153. cb.call(this, null, this);
  39154. }
  39155. return this;
  39156. });
  39157. return {
  39158. "class": {
  39159. /**
  39160. * Autocrop same color borders from this image
  39161. * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%)
  39162. * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true)
  39163. * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback)
  39164. * @returns {Jimp} this for chaining of methods
  39165. */
  39166. autocrop: function autocrop() {
  39167. var w = this.bitmap.width;
  39168. var h = this.bitmap.height;
  39169. var minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image
  39170. var cb; // callback
  39171. var leaveBorder = 0; // Amount of pixels in border to leave
  39172. var tolerance = 0.0002; // percent of color difference tolerance (default value)
  39173. var cropOnlyFrames = true; // flag to force cropping only if the image has a real "frame"
  39174. // i.e. all 4 sides have some border (default value)
  39175. var cropSymmetric = false; // flag to force cropping top be symmetric.
  39176. // i.e. north and south / east and west are cropped by the same value
  39177. // parse arguments
  39178. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  39179. args[_key] = arguments[_key];
  39180. }
  39181. for (var a = 0, len = args.length; a < len; a++) {
  39182. if (typeof args[a] === 'number') {
  39183. // tolerance value passed
  39184. tolerance = args[a];
  39185. }
  39186. if (typeof args[a] === 'boolean') {
  39187. // cropOnlyFrames value passed
  39188. cropOnlyFrames = args[a];
  39189. }
  39190. if (typeof args[a] === 'function') {
  39191. // callback value passed
  39192. cb = args[a];
  39193. }
  39194. if ((0, _typeof2["default"])(args[a]) === 'object') {
  39195. // config object passed
  39196. var config = args[a];
  39197. if (typeof config.tolerance !== 'undefined') {
  39198. tolerance = config.tolerance;
  39199. }
  39200. if (typeof config.cropOnlyFrames !== 'undefined') {
  39201. cropOnlyFrames = config.cropOnlyFrames;
  39202. }
  39203. if (typeof config.cropSymmetric !== 'undefined') {
  39204. cropSymmetric = config.cropSymmetric;
  39205. }
  39206. if (typeof config.leaveBorder !== 'undefined') {
  39207. leaveBorder = config.leaveBorder;
  39208. }
  39209. }
  39210. }
  39211. /**
  39212. * All borders must be of the same color as the top left pixel, to be cropped.
  39213. * It should be possible to crop borders each with a different color,
  39214. * but since there are many ways for corners to intersect, it would
  39215. * introduce unnecessary complexity to the algorithm.
  39216. */
  39217. // scan each side for same color borders
  39218. var colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color
  39219. var rgba1 = this.constructor.intToRGBA(colorTarget); // for north and east sides
  39220. var northPixelsToCrop = 0;
  39221. var eastPixelsToCrop = 0;
  39222. var southPixelsToCrop = 0;
  39223. var westPixelsToCrop = 0; // north side (scan rows from north to south)
  39224. colorTarget = this.getPixelColor(0, 0);
  39225. north: for (var y = 0; y < h - minPixelsPerSide; y++) {
  39226. for (var x = 0; x < w; x++) {
  39227. var colorXY = this.getPixelColor(x, y);
  39228. var rgba2 = this.constructor.intToRGBA(colorXY);
  39229. if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {
  39230. // this pixel is too distant from the first one: abort this side scan
  39231. break north;
  39232. }
  39233. } // this row contains all pixels with the same color: increment this side pixels to crop
  39234. northPixelsToCrop++;
  39235. } // east side (scan columns from east to west)
  39236. colorTarget = this.getPixelColor(w, 0);
  39237. east: for (var _x = 0; _x < w - minPixelsPerSide; _x++) {
  39238. for (var _y = 0 + northPixelsToCrop; _y < h; _y++) {
  39239. var _colorXY = this.getPixelColor(_x, _y);
  39240. var _rgba = this.constructor.intToRGBA(_colorXY);
  39241. if (this.constructor.colorDiff(rgba1, _rgba) > tolerance) {
  39242. // this pixel is too distant from the first one: abort this side scan
  39243. break east;
  39244. }
  39245. } // this column contains all pixels with the same color: increment this side pixels to crop
  39246. eastPixelsToCrop++;
  39247. } // south side (scan rows from south to north)
  39248. colorTarget = this.getPixelColor(0, h);
  39249. south: for (var _y2 = h - 1; _y2 >= northPixelsToCrop + minPixelsPerSide; _y2--) {
  39250. for (var _x2 = w - eastPixelsToCrop - 1; _x2 >= 0; _x2--) {
  39251. var _colorXY2 = this.getPixelColor(_x2, _y2);
  39252. var _rgba2 = this.constructor.intToRGBA(_colorXY2);
  39253. if (this.constructor.colorDiff(rgba1, _rgba2) > tolerance) {
  39254. // this pixel is too distant from the first one: abort this side scan
  39255. break south;
  39256. }
  39257. } // this row contains all pixels with the same color: increment this side pixels to crop
  39258. southPixelsToCrop++;
  39259. } // west side (scan columns from west to east)
  39260. colorTarget = this.getPixelColor(w, h);
  39261. west: for (var _x3 = w - 1; _x3 >= 0 + eastPixelsToCrop + minPixelsPerSide; _x3--) {
  39262. for (var _y3 = h - 1; _y3 >= 0 + northPixelsToCrop; _y3--) {
  39263. var _colorXY3 = this.getPixelColor(_x3, _y3);
  39264. var _rgba3 = this.constructor.intToRGBA(_colorXY3);
  39265. if (this.constructor.colorDiff(rgba1, _rgba3) > tolerance) {
  39266. // this pixel is too distant from the first one: abort this side scan
  39267. break west;
  39268. }
  39269. } // this column contains all pixels with the same color: increment this side pixels to crop
  39270. westPixelsToCrop++;
  39271. } // decide if a crop is needed
  39272. var doCrop = false; // apply leaveBorder
  39273. westPixelsToCrop -= leaveBorder;
  39274. eastPixelsToCrop -= leaveBorder;
  39275. northPixelsToCrop -= leaveBorder;
  39276. southPixelsToCrop -= leaveBorder;
  39277. if (cropSymmetric) {
  39278. var horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop);
  39279. var vertical = Math.min(northPixelsToCrop, southPixelsToCrop);
  39280. westPixelsToCrop = horizontal;
  39281. eastPixelsToCrop = horizontal;
  39282. northPixelsToCrop = vertical;
  39283. southPixelsToCrop = vertical;
  39284. } // make sure that crops are >= 0
  39285. westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0;
  39286. eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0;
  39287. northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0;
  39288. southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0; // safety checks
  39289. var widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop);
  39290. var heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop);
  39291. if (cropOnlyFrames) {
  39292. // crop image if all sides should be cropped
  39293. doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0;
  39294. } else {
  39295. // crop image if at least one side should be cropped
  39296. doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0;
  39297. }
  39298. if (doCrop) {
  39299. // do the real crop
  39300. this.crop(eastPixelsToCrop, northPixelsToCrop, widthOfRemainingPixels, heightOfRemainingPixels);
  39301. }
  39302. if ((0, _utils.isNodePattern)(cb)) {
  39303. cb.call(this, null, this);
  39304. }
  39305. return this;
  39306. }
  39307. }
  39308. };
  39309. }
  39310. module.exports = exports.default;
  39311. }).call(this,require("buffer").Buffer)
  39312. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"buffer":47,"core-js/modules/es.array.slice":186}],388:[function(require,module,exports){
  39313. "use strict";
  39314. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  39315. Object.defineProperty(exports, "__esModule", {
  39316. value: true
  39317. });
  39318. exports["default"] = void 0;
  39319. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  39320. var _utils = require("@jimp/utils");
  39321. /**
  39322. * Displaces the image based on the provided displacement map
  39323. * @param {object} map the source Jimp instance
  39324. * @param {number} offset the maximum displacement value
  39325. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39326. * @returns {Jimp} this for chaining of methods
  39327. */
  39328. var _default = function _default() {
  39329. return {
  39330. displace: function displace(map, offset, cb) {
  39331. if ((0, _typeof2["default"])(map) !== 'object' || map.constructor !== this.constructor) {
  39332. return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
  39333. }
  39334. if (typeof offset !== 'number') {
  39335. return _utils.throwError.call(this, 'factor must be a number', cb);
  39336. }
  39337. var source = this.cloneQuiet();
  39338. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39339. var displacement = map.bitmap.data[idx] / 256 * offset;
  39340. displacement = Math.round(displacement);
  39341. var ids = this.getPixelIndex(x + displacement, y);
  39342. this.bitmap.data[ids] = source.bitmap.data[idx];
  39343. this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];
  39344. this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];
  39345. });
  39346. if ((0, _utils.isNodePattern)(cb)) {
  39347. cb.call(this, null, this);
  39348. }
  39349. return this;
  39350. }
  39351. };
  39352. };
  39353. exports["default"] = _default;
  39354. module.exports = exports.default;
  39355. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414}],389:[function(require,module,exports){
  39356. "use strict";
  39357. Object.defineProperty(exports, "__esModule", {
  39358. value: true
  39359. });
  39360. exports["default"] = void 0;
  39361. var _utils = require("@jimp/utils");
  39362. /**
  39363. * Apply a ordered dithering effect
  39364. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39365. * @returns {Jimp} this for chaining of methods
  39366. */
  39367. function dither(cb) {
  39368. var rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
  39369. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39370. var thresholdId = ((y & 3) << 2) + x % 4;
  39371. var dither = rgb565Matrix[thresholdId];
  39372. this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);
  39373. this.bitmap.data[idx + 1] = Math.min(this.bitmap.data[idx + 1] + dither, 0xff);
  39374. this.bitmap.data[idx + 2] = Math.min(this.bitmap.data[idx + 2] + dither, 0xff);
  39375. });
  39376. if ((0, _utils.isNodePattern)(cb)) {
  39377. cb.call(this, null, this);
  39378. }
  39379. return this;
  39380. }
  39381. var _default = function _default() {
  39382. return {
  39383. dither565: dither,
  39384. dither16: dither
  39385. };
  39386. };
  39387. exports["default"] = _default;
  39388. module.exports = exports.default;
  39389. },{"@jimp/utils":414}],390:[function(require,module,exports){
  39390. "use strict";
  39391. Object.defineProperty(exports, "__esModule", {
  39392. value: true
  39393. });
  39394. exports["default"] = void 0;
  39395. var _utils = require("@jimp/utils");
  39396. /**
  39397. * Creates a circle out of an image.
  39398. * @param {object} options (optional) r: radius of effect
  39399. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39400. * @returns {Jimp} this for chaining of methods
  39401. */
  39402. var _default = function _default() {
  39403. return {
  39404. fisheye: function fisheye() {
  39405. var _this = this;
  39406. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  39407. r: 2.5
  39408. };
  39409. var cb = arguments.length > 1 ? arguments[1] : undefined;
  39410. if (typeof options === 'function') {
  39411. cb = options;
  39412. options = {
  39413. r: 2.5
  39414. };
  39415. }
  39416. var source = this.cloneQuiet();
  39417. var _source$bitmap = source.bitmap,
  39418. width = _source$bitmap.width,
  39419. height = _source$bitmap.height;
  39420. source.scanQuiet(0, 0, width, height, function (x, y) {
  39421. var hx = x / width;
  39422. var hy = y / height;
  39423. var r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2));
  39424. var rn = 2 * Math.pow(r, options.r);
  39425. var cosA = (hx - 0.5) / r;
  39426. var sinA = (hy - 0.5) / r;
  39427. var newX = Math.round((rn * cosA + 0.5) * width);
  39428. var newY = Math.round((rn * sinA + 0.5) * height);
  39429. var color = source.getPixelColor(newX, newY);
  39430. _this.setPixelColor(color, x, y);
  39431. });
  39432. /* Set center pixel color, otherwise it will be transparent */
  39433. this.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2);
  39434. if ((0, _utils.isNodePattern)(cb)) {
  39435. cb.call(this, null, this);
  39436. }
  39437. return this;
  39438. }
  39439. };
  39440. };
  39441. exports["default"] = _default;
  39442. module.exports = exports.default;
  39443. },{"@jimp/utils":414}],391:[function(require,module,exports){
  39444. (function (Buffer){
  39445. "use strict";
  39446. Object.defineProperty(exports, "__esModule", {
  39447. value: true
  39448. });
  39449. exports["default"] = void 0;
  39450. var _utils = require("@jimp/utils");
  39451. /**
  39452. * Flip the image horizontally
  39453. * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally
  39454. * @param {boolean} vertical a Boolean, if true the image will be flipped vertically
  39455. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39456. * @returns {Jimp} this for chaining of methods
  39457. */
  39458. function flipFn(horizontal, vertical, cb) {
  39459. if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean') return _utils.throwError.call(this, 'horizontal and vertical must be Booleans', cb);
  39460. var bitmap = Buffer.alloc(this.bitmap.data.length);
  39461. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39462. var _x = horizontal ? this.bitmap.width - 1 - x : x;
  39463. var _y = vertical ? this.bitmap.height - 1 - y : y;
  39464. var _idx = this.bitmap.width * _y + _x << 2;
  39465. var data = this.bitmap.data.readUInt32BE(idx);
  39466. bitmap.writeUInt32BE(data, _idx);
  39467. });
  39468. this.bitmap.data = Buffer.from(bitmap);
  39469. if ((0, _utils.isNodePattern)(cb)) {
  39470. cb.call(this, null, this);
  39471. }
  39472. return this;
  39473. }
  39474. var _default = function _default() {
  39475. return {
  39476. flip: flipFn,
  39477. mirror: flipFn
  39478. };
  39479. };
  39480. exports["default"] = _default;
  39481. module.exports = exports.default;
  39482. }).call(this,require("buffer").Buffer)
  39483. },{"@jimp/utils":414,"buffer":47}],392:[function(require,module,exports){
  39484. "use strict";
  39485. Object.defineProperty(exports, "__esModule", {
  39486. value: true
  39487. });
  39488. exports["default"] = void 0;
  39489. var _utils = require("@jimp/utils");
  39490. /**
  39491. * Applies a true Gaussian blur to the image (warning: this is VERY slow)
  39492. * @param {number} r the pixel radius of the blur
  39493. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39494. * @returns {Jimp} this for chaining of methods
  39495. */
  39496. var _default = function _default() {
  39497. return {
  39498. gaussian: function gaussian(r, cb) {
  39499. // http://blog.ivank.net/fastest-gaussian-blur.html
  39500. if (typeof r !== 'number') {
  39501. return _utils.throwError.call(this, 'r must be a number', cb);
  39502. }
  39503. if (r < 1) {
  39504. return _utils.throwError.call(this, 'r must be greater than 0', cb);
  39505. }
  39506. var rs = Math.ceil(r * 2.57); // significant radius
  39507. var range = rs * 2 + 1;
  39508. var rr2 = r * r * 2;
  39509. var rr2pi = rr2 * Math.PI;
  39510. var weights = [];
  39511. for (var y = 0; y < range; y++) {
  39512. weights[y] = [];
  39513. for (var x = 0; x < range; x++) {
  39514. var dsq = Math.pow(x - rs, 2) + Math.pow(y - rs, 2);
  39515. weights[y][x] = Math.exp(-dsq / rr2) / rr2pi;
  39516. }
  39517. }
  39518. for (var _y = 0; _y < this.bitmap.height; _y++) {
  39519. for (var _x = 0; _x < this.bitmap.width; _x++) {
  39520. var red = 0;
  39521. var green = 0;
  39522. var blue = 0;
  39523. var alpha = 0;
  39524. var wsum = 0;
  39525. for (var iy = 0; iy < range; iy++) {
  39526. for (var ix = 0; ix < range; ix++) {
  39527. var x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + _x - rs));
  39528. var y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + _y - rs));
  39529. var weight = weights[iy][ix];
  39530. var _idx = y1 * this.bitmap.width + x1 << 2;
  39531. red += this.bitmap.data[_idx] * weight;
  39532. green += this.bitmap.data[_idx + 1] * weight;
  39533. blue += this.bitmap.data[_idx + 2] * weight;
  39534. alpha += this.bitmap.data[_idx + 3] * weight;
  39535. wsum += weight;
  39536. }
  39537. var idx = _y * this.bitmap.width + _x << 2;
  39538. this.bitmap.data[idx] = Math.round(red / wsum);
  39539. this.bitmap.data[idx + 1] = Math.round(green / wsum);
  39540. this.bitmap.data[idx + 2] = Math.round(blue / wsum);
  39541. this.bitmap.data[idx + 3] = Math.round(alpha / wsum);
  39542. }
  39543. }
  39544. }
  39545. if ((0, _utils.isNodePattern)(cb)) {
  39546. cb.call(this, null, this);
  39547. }
  39548. return this;
  39549. }
  39550. };
  39551. };
  39552. exports["default"] = _default;
  39553. module.exports = exports.default;
  39554. },{"@jimp/utils":414}],393:[function(require,module,exports){
  39555. "use strict";
  39556. Object.defineProperty(exports, "__esModule", {
  39557. value: true
  39558. });
  39559. exports["default"] = void 0;
  39560. var _utils = require("@jimp/utils");
  39561. /**
  39562. * Inverts the image
  39563. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39564. * @returns {Jimp} this for chaining of methods
  39565. */
  39566. var _default = function _default() {
  39567. return {
  39568. invert: function invert(cb) {
  39569. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39570. this.bitmap.data[idx] = 255 - this.bitmap.data[idx];
  39571. this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1];
  39572. this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2];
  39573. });
  39574. if ((0, _utils.isNodePattern)(cb)) {
  39575. cb.call(this, null, this);
  39576. }
  39577. return this;
  39578. }
  39579. };
  39580. };
  39581. exports["default"] = _default;
  39582. module.exports = exports.default;
  39583. },{"@jimp/utils":414}],394:[function(require,module,exports){
  39584. "use strict";
  39585. Object.defineProperty(exports, "__esModule", {
  39586. value: true
  39587. });
  39588. exports["default"] = void 0;
  39589. var _utils = require("@jimp/utils");
  39590. /**
  39591. * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent.
  39592. * @param {Jimp} src the source Jimp instance
  39593. * @param {number} x the horizontal position to blit the image
  39594. * @param {number} y the vertical position to blit the image
  39595. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39596. * @returns {Jimp} this for chaining of methods
  39597. */
  39598. var _default = function _default() {
  39599. return {
  39600. mask: function mask(src) {
  39601. var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  39602. var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  39603. var cb = arguments.length > 3 ? arguments[3] : undefined;
  39604. if (!(src instanceof this.constructor)) {
  39605. return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
  39606. }
  39607. if (typeof x !== 'number' || typeof y !== 'number') {
  39608. return _utils.throwError.call(this, 'x and y must be numbers', cb);
  39609. } // round input
  39610. x = Math.round(x);
  39611. y = Math.round(y);
  39612. var w = this.bitmap.width;
  39613. var h = this.bitmap.height;
  39614. var baseImage = this;
  39615. src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {
  39616. var destX = x + sx;
  39617. var destY = y + sy;
  39618. if (destX >= 0 && destY >= 0 && destX < w && destY < h) {
  39619. var dstIdx = baseImage.getPixelIndex(destX, destY);
  39620. var data = this.bitmap.data;
  39621. var avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;
  39622. baseImage.bitmap.data[dstIdx + 3] *= avg / 255;
  39623. }
  39624. });
  39625. if ((0, _utils.isNodePattern)(cb)) {
  39626. cb.call(this, null, this);
  39627. }
  39628. return this;
  39629. }
  39630. };
  39631. };
  39632. exports["default"] = _default;
  39633. module.exports = exports.default;
  39634. },{"@jimp/utils":414}],395:[function(require,module,exports){
  39635. "use strict";
  39636. require("core-js/modules/es.array.fill");
  39637. require("core-js/modules/es.array.find-index");
  39638. require("core-js/modules/es.array.reverse");
  39639. require("core-js/modules/es.array.slice");
  39640. Object.defineProperty(exports, "__esModule", {
  39641. value: true
  39642. });
  39643. exports["default"] = void 0;
  39644. var _utils = require("@jimp/utils");
  39645. /**
  39646. * Get an image's histogram
  39647. * @return {object} An object with an array of color occurrence counts for each channel (r,g,b)
  39648. */
  39649. function histogram() {
  39650. var histogram = {
  39651. r: new Array(256).fill(0),
  39652. g: new Array(256).fill(0),
  39653. b: new Array(256).fill(0)
  39654. };
  39655. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, index) {
  39656. histogram.r[this.bitmap.data[index + 0]]++;
  39657. histogram.g[this.bitmap.data[index + 1]]++;
  39658. histogram.b[this.bitmap.data[index + 2]]++;
  39659. });
  39660. return histogram;
  39661. }
  39662. /**
  39663. * Normalize values
  39664. * @param {integer} value Pixel channel value.
  39665. * @param {integer} min Minimum value for channel
  39666. * @param {integer} max Maximum value for channel
  39667. * @return {integer} normalized values
  39668. */
  39669. var _normalize = function normalize(value, min, max) {
  39670. return (value - min) * 255 / (max - min);
  39671. };
  39672. var getBounds = function getBounds(histogramChannel) {
  39673. return [histogramChannel.findIndex(function (value) {
  39674. return value > 0;
  39675. }), 255 - histogramChannel.slice().reverse().findIndex(function (value) {
  39676. return value > 0;
  39677. })];
  39678. };
  39679. /**
  39680. * Normalizes the image
  39681. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  39682. * @returns {Jimp} this for chaining of methods
  39683. */
  39684. var _default = function _default() {
  39685. return {
  39686. normalize: function normalize(cb) {
  39687. var h = histogram.call(this); // store bounds (minimum and maximum values)
  39688. var bounds = {
  39689. r: getBounds(h.r),
  39690. g: getBounds(h.g),
  39691. b: getBounds(h.b)
  39692. }; // apply value transformations
  39693. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  39694. var r = this.bitmap.data[idx + 0];
  39695. var g = this.bitmap.data[idx + 1];
  39696. var b = this.bitmap.data[idx + 2];
  39697. this.bitmap.data[idx + 0] = _normalize(r, bounds.r[0], bounds.r[1]);
  39698. this.bitmap.data[idx + 1] = _normalize(g, bounds.g[0], bounds.g[1]);
  39699. this.bitmap.data[idx + 2] = _normalize(b, bounds.b[0], bounds.b[1]);
  39700. });
  39701. if ((0, _utils.isNodePattern)(cb)) {
  39702. cb.call(this, null, this);
  39703. }
  39704. return this;
  39705. }
  39706. };
  39707. };
  39708. exports["default"] = _default;
  39709. module.exports = exports.default;
  39710. },{"@jimp/utils":414,"core-js/modules/es.array.fill":174,"core-js/modules/es.array.find-index":176,"core-js/modules/es.array.reverse":185,"core-js/modules/es.array.slice":186}],396:[function(require,module,exports){
  39711. (function (__dirname){
  39712. "use strict";
  39713. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  39714. require("core-js/modules/es.array.concat");
  39715. require("core-js/modules/es.array.for-each");
  39716. require("core-js/modules/es.array.iterator");
  39717. require("core-js/modules/es.array.join");
  39718. require("core-js/modules/es.array.map");
  39719. require("core-js/modules/es.date.to-string");
  39720. require("core-js/modules/es.object.entries");
  39721. require("core-js/modules/es.object.to-string");
  39722. require("core-js/modules/es.promise");
  39723. require("core-js/modules/es.regexp.exec");
  39724. require("core-js/modules/es.regexp.to-string");
  39725. require("core-js/modules/es.string.iterator");
  39726. require("core-js/modules/es.string.split");
  39727. require("core-js/modules/web.dom-collections.for-each");
  39728. require("core-js/modules/web.dom-collections.iterator");
  39729. Object.defineProperty(exports, "__esModule", {
  39730. value: true
  39731. });
  39732. exports["default"] = void 0;
  39733. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  39734. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  39735. var _path = _interopRequireDefault(require("path"));
  39736. var _loadBmfont = _interopRequireDefault(require("load-bmfont"));
  39737. var _utils = require("@jimp/utils");
  39738. var _measureText = require("./measure-text");
  39739. function xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) {
  39740. if (alignment === constants.HORIZONTAL_ALIGN_LEFT) {
  39741. return 0;
  39742. }
  39743. if (alignment === constants.HORIZONTAL_ALIGN_CENTER) {
  39744. return (maxWidth - (0, _measureText.measureText)(font, line)) / 2;
  39745. }
  39746. return maxWidth - (0, _measureText.measureText)(font, line);
  39747. }
  39748. function drawCharacter(image, font, x, y, _char) {
  39749. if (_char.width > 0 && _char.height > 0) {
  39750. var characterPage = font.pages[_char.page];
  39751. image.blit(characterPage, x + _char.xoffset, y + _char.yoffset, _char.x, _char.y, _char.width, _char.height);
  39752. }
  39753. return image;
  39754. }
  39755. function printText(font, x, y, text, defaultCharWidth) {
  39756. for (var i = 0; i < text.length; i++) {
  39757. var _char2 = void 0;
  39758. if (font.chars[text[i]]) {
  39759. _char2 = text[i];
  39760. } else if (/\s/.test(text[i])) {
  39761. _char2 = '';
  39762. } else {
  39763. _char2 = '?';
  39764. }
  39765. var fontChar = font.chars[_char2] || {};
  39766. var fontKerning = font.kernings[_char2];
  39767. drawCharacter(this, font, x, y, fontChar || {});
  39768. var kerning = fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0;
  39769. x += kerning + (fontChar.xadvance || defaultCharWidth);
  39770. }
  39771. }
  39772. function splitLines(font, text, maxWidth) {
  39773. var words = text.split(' ');
  39774. var lines = [];
  39775. var currentLine = [];
  39776. var longestLine = 0;
  39777. words.forEach(function (word) {
  39778. var line = [].concat((0, _toConsumableArray2["default"])(currentLine), [word]).join(' ');
  39779. var length = (0, _measureText.measureText)(font, line);
  39780. if (length <= maxWidth) {
  39781. if (length > longestLine) {
  39782. longestLine = length;
  39783. }
  39784. currentLine.push(word);
  39785. } else {
  39786. lines.push(currentLine);
  39787. currentLine = [word];
  39788. }
  39789. });
  39790. lines.push(currentLine);
  39791. return {
  39792. lines: lines,
  39793. longestLine: longestLine
  39794. };
  39795. }
  39796. function loadPages(Jimp, dir, pages) {
  39797. var newPages = pages.map(function (page) {
  39798. return Jimp.read(dir + '/' + page);
  39799. });
  39800. return Promise.all(newPages);
  39801. }
  39802. var dir = "browser/lib/" || "".concat(__dirname, "/../");
  39803. var _default = function _default() {
  39804. return {
  39805. constants: {
  39806. measureText: _measureText.measureText,
  39807. measureTextHeight: _measureText.measureTextHeight,
  39808. FONT_SANS_8_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt'),
  39809. FONT_SANS_10_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt'),
  39810. FONT_SANS_12_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt'),
  39811. FONT_SANS_14_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt'),
  39812. FONT_SANS_16_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt'),
  39813. FONT_SANS_32_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt'),
  39814. FONT_SANS_64_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt'),
  39815. FONT_SANS_128_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt'),
  39816. FONT_SANS_8_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt'),
  39817. FONT_SANS_16_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt'),
  39818. FONT_SANS_32_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt'),
  39819. FONT_SANS_64_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt'),
  39820. FONT_SANS_128_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt'),
  39821. /**
  39822. * Loads a bitmap font from a file
  39823. * @param {string} file the file path of a .fnt file
  39824. * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded
  39825. * @returns {Promise} a promise
  39826. */
  39827. loadFont: function loadFont(file, cb) {
  39828. var _this = this;
  39829. if (typeof file !== 'string') return _utils.throwError.call(this, 'file must be a string', cb);
  39830. return new Promise(function (resolve, reject) {
  39831. cb = cb || function (err, font) {
  39832. if (err) reject(err);else resolve(font);
  39833. };
  39834. (0, _loadBmfont["default"])(file, function (err, font) {
  39835. var chars = {};
  39836. var kernings = {};
  39837. if (err) {
  39838. return _utils.throwError.call(_this, err, cb);
  39839. }
  39840. for (var i = 0; i < font.chars.length; i++) {
  39841. chars[String.fromCharCode(font.chars[i].id)] = font.chars[i];
  39842. }
  39843. for (var _i = 0; _i < font.kernings.length; _i++) {
  39844. var firstString = String.fromCharCode(font.kernings[_i].first);
  39845. kernings[firstString] = kernings[firstString] || {};
  39846. kernings[firstString][String.fromCharCode(font.kernings[_i].second)] = font.kernings[_i].amount;
  39847. }
  39848. loadPages(_this, _path["default"].dirname(file), font.pages).then(function (pages) {
  39849. cb(null, {
  39850. chars: chars,
  39851. kernings: kernings,
  39852. pages: pages,
  39853. common: font.common,
  39854. info: font.info
  39855. });
  39856. });
  39857. });
  39858. });
  39859. }
  39860. },
  39861. "class": {
  39862. /**
  39863. * Draws a text on a image on a given boundary
  39864. * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command
  39865. * @param {number} x the x position to start drawing the text
  39866. * @param {number} y the y position to start drawing the text
  39867. * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`)
  39868. * @param {number} maxWidth (optional) the boundary width to draw in
  39869. * @param {number} maxHeight (optional) the boundary height to draw in
  39870. * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written
  39871. * @returns {Jimp} this for chaining of methods
  39872. */
  39873. print: function print(font, x, y, text, maxWidth, maxHeight, cb) {
  39874. var _this2 = this;
  39875. if (typeof maxWidth === 'function' && typeof cb === 'undefined') {
  39876. cb = maxWidth;
  39877. maxWidth = Infinity;
  39878. }
  39879. if (typeof maxWidth === 'undefined') {
  39880. maxWidth = Infinity;
  39881. }
  39882. if (typeof maxHeight === 'function' && typeof cb === 'undefined') {
  39883. cb = maxHeight;
  39884. maxHeight = Infinity;
  39885. }
  39886. if (typeof maxHeight === 'undefined') {
  39887. maxHeight = Infinity;
  39888. }
  39889. if ((0, _typeof2["default"])(font) !== 'object') {
  39890. return _utils.throwError.call(this, 'font must be a Jimp loadFont', cb);
  39891. }
  39892. if (typeof x !== 'number' || typeof y !== 'number' || typeof maxWidth !== 'number') {
  39893. return _utils.throwError.call(this, 'x, y and maxWidth must be numbers', cb);
  39894. }
  39895. if (typeof maxWidth !== 'number') {
  39896. return _utils.throwError.call(this, 'maxWidth must be a number', cb);
  39897. }
  39898. if (typeof maxHeight !== 'number') {
  39899. return _utils.throwError.call(this, 'maxHeight must be a number', cb);
  39900. }
  39901. var alignmentX;
  39902. var alignmentY;
  39903. if ((0, _typeof2["default"])(text) === 'object' && text.text !== null && text.text !== undefined) {
  39904. alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT;
  39905. alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP;
  39906. var _text = text;
  39907. text = _text.text;
  39908. } else {
  39909. alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT;
  39910. alignmentY = this.constructor.VERTICAL_ALIGN_TOP;
  39911. text = text.toString();
  39912. }
  39913. if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM) {
  39914. y += maxHeight - (0, _measureText.measureTextHeight)(font, text, maxWidth);
  39915. } else if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE) {
  39916. y += maxHeight / 2 - (0, _measureText.measureTextHeight)(font, text, maxWidth) / 2;
  39917. }
  39918. var defaultCharWidth = Object.entries(font.chars)[0][1].xadvance;
  39919. var _splitLines = splitLines(font, text, maxWidth),
  39920. lines = _splitLines.lines,
  39921. longestLine = _splitLines.longestLine;
  39922. lines.forEach(function (line) {
  39923. var lineString = line.join(' ');
  39924. var alignmentWidth = xOffsetBasedOnAlignment(_this2.constructor, font, lineString, maxWidth, alignmentX);
  39925. printText.call(_this2, font, x + alignmentWidth, y, lineString, defaultCharWidth);
  39926. y += font.common.lineHeight;
  39927. });
  39928. if ((0, _utils.isNodePattern)(cb)) {
  39929. cb.call(this, null, this, {
  39930. x: x + longestLine,
  39931. y: y
  39932. });
  39933. }
  39934. return this;
  39935. }
  39936. }
  39937. };
  39938. };
  39939. exports["default"] = _default;
  39940. module.exports = exports.default;
  39941. }).call(this,"/../../node_modules/@jimp/plugin-print/dist")
  39942. },{"./measure-text":397,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"core-js/modules/es.array.concat":173,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.iterator":182,"core-js/modules/es.array.join":183,"core-js/modules/es.array.map":184,"core-js/modules/es.date.to-string":187,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.to-string":197,"core-js/modules/es.promise":199,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.regexp.to-string":201,"core-js/modules/es.string.iterator":203,"core-js/modules/es.string.split":206,"core-js/modules/web.dom-collections.for-each":235,"core-js/modules/web.dom-collections.iterator":236,"load-bmfont":398,"path":286}],397:[function(require,module,exports){
  39943. "use strict";
  39944. require("core-js/modules/es.regexp.exec");
  39945. require("core-js/modules/es.string.split");
  39946. Object.defineProperty(exports, "__esModule", {
  39947. value: true
  39948. });
  39949. exports.measureText = measureText;
  39950. exports.measureTextHeight = measureTextHeight;
  39951. function measureText(font, text) {
  39952. var x = 0;
  39953. for (var i = 0; i < text.length; i++) {
  39954. if (font.chars[text[i]]) {
  39955. var kerning = font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0;
  39956. x += (font.chars[text[i]].xadvance || 0) + kerning;
  39957. }
  39958. }
  39959. return x;
  39960. }
  39961. function measureTextHeight(font, text, maxWidth) {
  39962. var words = text.split(' ');
  39963. var line = '';
  39964. var textTotalHeight = font.common.lineHeight;
  39965. for (var n = 0; n < words.length; n++) {
  39966. var testLine = line + words[n] + ' ';
  39967. var testWidth = measureText(font, testLine);
  39968. if (testWidth > maxWidth && n > 0) {
  39969. textTotalHeight += font.common.lineHeight;
  39970. line = words[n] + ' ';
  39971. } else {
  39972. line = testLine;
  39973. }
  39974. }
  39975. return textTotalHeight;
  39976. }
  39977. },{"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.split":206}],398:[function(require,module,exports){
  39978. (function (Buffer){
  39979. var xhr = require('xhr')
  39980. var noop = function(){}
  39981. var parseASCII = require('parse-bmfont-ascii')
  39982. var parseXML = require('parse-bmfont-xml')
  39983. var readBinary = require('parse-bmfont-binary')
  39984. var isBinaryFormat = require('./lib/is-binary')
  39985. var xtend = require('xtend')
  39986. var xml2 = (function hasXML2() {
  39987. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  39988. })()
  39989. module.exports = function(opt, cb) {
  39990. cb = typeof cb === 'function' ? cb : noop
  39991. if (typeof opt === 'string')
  39992. opt = { uri: opt }
  39993. else if (!opt)
  39994. opt = {}
  39995. var expectBinary = opt.binary
  39996. if (expectBinary)
  39997. opt = getBinaryOpts(opt)
  39998. xhr(opt, function(err, res, body) {
  39999. if (err)
  40000. return cb(err)
  40001. if (!/^2/.test(res.statusCode))
  40002. return cb(new Error('http status code: '+res.statusCode))
  40003. if (!body)
  40004. return cb(new Error('no body result'))
  40005. var binary = false
  40006. //if the response type is an array buffer,
  40007. //we need to convert it into a regular Buffer object
  40008. if (isArrayBuffer(body)) {
  40009. var array = new Uint8Array(body)
  40010. body = new Buffer(array, 'binary')
  40011. }
  40012. //now check the string/Buffer response
  40013. //and see if it has a binary BMF header
  40014. if (isBinaryFormat(body)) {
  40015. binary = true
  40016. //if we have a string, turn it into a Buffer
  40017. if (typeof body === 'string')
  40018. body = new Buffer(body, 'binary')
  40019. }
  40020. //we are not parsing a binary format, just ASCII/XML/etc
  40021. if (!binary) {
  40022. //might still be a buffer if responseType is 'arraybuffer'
  40023. if (Buffer.isBuffer(body))
  40024. body = body.toString(opt.encoding)
  40025. body = body.trim()
  40026. }
  40027. var result
  40028. try {
  40029. var type = res.headers['content-type']
  40030. if (binary)
  40031. result = readBinary(body)
  40032. else if (/json/.test(type) || body.charAt(0) === '{')
  40033. result = JSON.parse(body)
  40034. else if (/xml/.test(type) || body.charAt(0) === '<')
  40035. result = parseXML(body)
  40036. else
  40037. result = parseASCII(body)
  40038. } catch (e) {
  40039. cb(new Error('error parsing font '+e.message))
  40040. cb = noop
  40041. }
  40042. cb(null, result)
  40043. })
  40044. }
  40045. function isArrayBuffer(arr) {
  40046. var str = Object.prototype.toString
  40047. return str.call(arr) === '[object ArrayBuffer]'
  40048. }
  40049. function getBinaryOpts(opt) {
  40050. //IE10+ and other modern browsers support array buffers
  40051. if (xml2)
  40052. return xtend(opt, { responseType: 'arraybuffer' })
  40053. if (typeof self.XMLHttpRequest === 'undefined')
  40054. throw new Error('your browser does not support XHR loading')
  40055. //IE9 and XML1 browsers could still use an override
  40056. var req = new self.XMLHttpRequest()
  40057. req.overrideMimeType('text/plain; charset=x-user-defined')
  40058. return xtend({
  40059. xhr: req
  40060. }, opt)
  40061. }
  40062. }).call(this,require("buffer").Buffer)
  40063. },{"./lib/is-binary":399,"buffer":47,"parse-bmfont-ascii":281,"parse-bmfont-binary":282,"parse-bmfont-xml":283,"xhr":366,"xtend":368}],399:[function(require,module,exports){
  40064. (function (Buffer){
  40065. var equal = require('buffer-equal')
  40066. var HEADER = new Buffer([66, 77, 70, 3])
  40067. module.exports = function(buf) {
  40068. if (typeof buf === 'string')
  40069. return buf.substring(0, 3) === 'BMF'
  40070. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  40071. }
  40072. }).call(this,require("buffer").Buffer)
  40073. },{"buffer":47,"buffer-equal":48}],400:[function(require,module,exports){
  40074. (function (Buffer){
  40075. "use strict";
  40076. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  40077. Object.defineProperty(exports, "__esModule", {
  40078. value: true
  40079. });
  40080. exports["default"] = void 0;
  40081. var _utils = require("@jimp/utils");
  40082. var _resize = _interopRequireDefault(require("./modules/resize"));
  40083. var _resize2 = _interopRequireDefault(require("./modules/resize2"));
  40084. var _default = function _default() {
  40085. return {
  40086. constants: {
  40087. RESIZE_NEAREST_NEIGHBOR: 'nearestNeighbor',
  40088. RESIZE_BILINEAR: 'bilinearInterpolation',
  40089. RESIZE_BICUBIC: 'bicubicInterpolation',
  40090. RESIZE_HERMITE: 'hermiteInterpolation',
  40091. RESIZE_BEZIER: 'bezierInterpolation'
  40092. },
  40093. "class": {
  40094. /**
  40095. * Resizes the image to a set width and height using a 2-pass bilinear algorithm
  40096. * @param {number} w the width to resize the image to (or Jimp.AUTO)
  40097. * @param {number} h the height to resize the image to (or Jimp.AUTO)
  40098. * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
  40099. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  40100. * @returns {Jimp} this for chaining of methods
  40101. */
  40102. resize: function resize(w, h, mode, cb) {
  40103. if (typeof w !== 'number' || typeof h !== 'number') {
  40104. return _utils.throwError.call(this, 'w and h must be numbers', cb);
  40105. }
  40106. if (typeof mode === 'function' && typeof cb === 'undefined') {
  40107. cb = mode;
  40108. mode = null;
  40109. }
  40110. if (w === this.constructor.AUTO && h === this.constructor.AUTO) {
  40111. return _utils.throwError.call(this, 'w and h cannot both be set to auto', cb);
  40112. }
  40113. if (w === this.constructor.AUTO) {
  40114. w = this.bitmap.width * (h / this.bitmap.height);
  40115. }
  40116. if (h === this.constructor.AUTO) {
  40117. h = this.bitmap.height * (w / this.bitmap.width);
  40118. }
  40119. if (w < 0 || h < 0) {
  40120. return _utils.throwError.call(this, 'w and h must be positive numbers', cb);
  40121. } // round inputs
  40122. w = Math.round(w);
  40123. h = Math.round(h);
  40124. if (typeof _resize2["default"][mode] === 'function') {
  40125. var dst = {
  40126. data: Buffer.alloc(w * h * 4),
  40127. width: w,
  40128. height: h
  40129. };
  40130. _resize2["default"][mode](this.bitmap, dst);
  40131. this.bitmap = dst;
  40132. } else {
  40133. var image = this;
  40134. var resize = new _resize["default"](this.bitmap.width, this.bitmap.height, w, h, true, true, function (buffer) {
  40135. image.bitmap.data = Buffer.from(buffer);
  40136. image.bitmap.width = w;
  40137. image.bitmap.height = h;
  40138. });
  40139. resize.resize(this.bitmap.data);
  40140. }
  40141. if ((0, _utils.isNodePattern)(cb)) {
  40142. cb.call(this, null, this);
  40143. }
  40144. return this;
  40145. }
  40146. }
  40147. };
  40148. };
  40149. exports["default"] = _default;
  40150. module.exports = exports.default;
  40151. }).call(this,require("buffer").Buffer)
  40152. },{"./modules/resize":401,"./modules/resize2":402,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"buffer":47}],401:[function(require,module,exports){
  40153. "use strict";
  40154. require("core-js/modules/es.array.iterator");
  40155. require("core-js/modules/es.array-buffer.slice");
  40156. require("core-js/modules/es.object.to-string");
  40157. require("core-js/modules/es.typed-array.float32-array");
  40158. require("core-js/modules/es.typed-array.float64-array");
  40159. require("core-js/modules/es.typed-array.uint8-array");
  40160. require("core-js/modules/es.typed-array.copy-within");
  40161. require("core-js/modules/es.typed-array.every");
  40162. require("core-js/modules/es.typed-array.fill");
  40163. require("core-js/modules/es.typed-array.filter");
  40164. require("core-js/modules/es.typed-array.find");
  40165. require("core-js/modules/es.typed-array.find-index");
  40166. require("core-js/modules/es.typed-array.for-each");
  40167. require("core-js/modules/es.typed-array.includes");
  40168. require("core-js/modules/es.typed-array.index-of");
  40169. require("core-js/modules/es.typed-array.iterator");
  40170. require("core-js/modules/es.typed-array.join");
  40171. require("core-js/modules/es.typed-array.last-index-of");
  40172. require("core-js/modules/es.typed-array.map");
  40173. require("core-js/modules/es.typed-array.reduce");
  40174. require("core-js/modules/es.typed-array.reduce-right");
  40175. require("core-js/modules/es.typed-array.reverse");
  40176. require("core-js/modules/es.typed-array.set");
  40177. require("core-js/modules/es.typed-array.slice");
  40178. require("core-js/modules/es.typed-array.some");
  40179. require("core-js/modules/es.typed-array.sort");
  40180. require("core-js/modules/es.typed-array.subarray");
  40181. require("core-js/modules/es.typed-array.to-locale-string");
  40182. require("core-js/modules/es.typed-array.to-string");
  40183. // JavaScript Image Resizer (c) 2012 - Grant Galitz
  40184. // Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4
  40185. function Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) {
  40186. this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0);
  40187. this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0);
  40188. this.targetWidth = Math.abs(Math.floor(targetWidth) || 0);
  40189. this.targetHeight = Math.abs(Math.floor(targetHeight) || 0);
  40190. this.colorChannels = blendAlpha ? 4 : 3;
  40191. this.interpolationPass = Boolean(interpolationPass);
  40192. this.resizeCallback = typeof resizeCallback === 'function' ? resizeCallback : function () {};
  40193. this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels;
  40194. this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels;
  40195. this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels;
  40196. this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal;
  40197. this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight;
  40198. this.initialize();
  40199. }
  40200. Resize.prototype.initialize = function () {
  40201. // Perform some checks:
  40202. if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) {
  40203. this.configurePasses();
  40204. } else {
  40205. throw new Error('Invalid settings specified for the resizer.');
  40206. }
  40207. };
  40208. Resize.prototype.configurePasses = function () {
  40209. if (this.widthOriginal === this.targetWidth) {
  40210. // Bypass the width resizer pass:
  40211. this.resizeWidth = this.bypassResizer;
  40212. } else {
  40213. // Setup the width resizer pass:
  40214. this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth;
  40215. if (this.ratioWeightWidthPass < 1 && this.interpolationPass) {
  40216. this.initializeFirstPassBuffers(true);
  40217. this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB;
  40218. } else {
  40219. this.initializeFirstPassBuffers(false);
  40220. this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB;
  40221. }
  40222. }
  40223. if (this.heightOriginal === this.targetHeight) {
  40224. // Bypass the height resizer pass:
  40225. this.resizeHeight = this.bypassResizer;
  40226. } else {
  40227. // Setup the height resizer pass:
  40228. this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight;
  40229. if (this.ratioWeightHeightPass < 1 && this.interpolationPass) {
  40230. this.initializeSecondPassBuffers(true);
  40231. this.resizeHeight = this.resizeHeightInterpolated;
  40232. } else {
  40233. this.initializeSecondPassBuffers(false);
  40234. this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB;
  40235. }
  40236. }
  40237. };
  40238. Resize.prototype._resizeWidthInterpolatedRGBChannels = function (buffer, fourthChannel) {
  40239. var channelsNum = fourthChannel ? 4 : 3;
  40240. var ratioWeight = this.ratioWeightWidthPass;
  40241. var outputBuffer = this.widthBuffer;
  40242. var weight = 0;
  40243. var finalOffset = 0;
  40244. var pixelOffset = 0;
  40245. var firstWeight = 0;
  40246. var secondWeight = 0;
  40247. var targetPosition; // Handle for only one interpolation input being valid for start calculation:
  40248. for (targetPosition = 0; weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) {
  40249. for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
  40250. outputBuffer[finalOffset] = buffer[pixelOffset];
  40251. outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
  40252. outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
  40253. if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
  40254. }
  40255. } // Adjust for overshoot of the last pass's counter:
  40256. weight -= 1 / 3;
  40257. var interpolationWidthSourceReadStop;
  40258. for (interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) {
  40259. // Calculate weightings:
  40260. secondWeight = weight % 1;
  40261. firstWeight = 1 - secondWeight; // Interpolate:
  40262. for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
  40263. outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight;
  40264. outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight;
  40265. outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight;
  40266. if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight;
  40267. }
  40268. } // Handle for only one interpolation input being valid for end calculation:
  40269. for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) {
  40270. for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
  40271. outputBuffer[finalOffset] = buffer[pixelOffset];
  40272. outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
  40273. outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
  40274. if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
  40275. }
  40276. }
  40277. return outputBuffer;
  40278. };
  40279. Resize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) {
  40280. var channelsNum = fourthChannel ? 4 : 3;
  40281. var ratioWeight = this.ratioWeightWidthPass;
  40282. var ratioWeightDivisor = 1 / ratioWeight;
  40283. var nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1;
  40284. var nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1;
  40285. var output = this.outputWidthWorkBench;
  40286. var outputBuffer = this.widthBuffer;
  40287. var trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount;
  40288. var weight = 0;
  40289. var amountToNext = 0;
  40290. var actualPosition = 0;
  40291. var currentPosition = 0;
  40292. var line = 0;
  40293. var pixelOffset = 0;
  40294. var outputOffset = 0;
  40295. var multiplier = 1;
  40296. var r = 0;
  40297. var g = 0;
  40298. var b = 0;
  40299. var a = 0;
  40300. do {
  40301. for (line = 0; line < this.originalHeightMultipliedByChannels;) {
  40302. output[line++] = 0;
  40303. output[line++] = 0;
  40304. output[line++] = 0;
  40305. if (fourthChannel) {
  40306. output[line++] = 0;
  40307. trustworthyColorsCount[line / channelsNum - 1] = 0;
  40308. }
  40309. }
  40310. weight = ratioWeight;
  40311. do {
  40312. amountToNext = 1 + actualPosition - currentPosition;
  40313. multiplier = Math.min(weight, amountToNext);
  40314. for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) {
  40315. r = buffer[pixelOffset];
  40316. g = buffer[++pixelOffset];
  40317. b = buffer[++pixelOffset];
  40318. a = fourthChannel ? buffer[++pixelOffset] : 255; // Ignore RGB values if pixel is completely transparent
  40319. output[line++] += (a ? r : 0) * multiplier;
  40320. output[line++] += (a ? g : 0) * multiplier;
  40321. output[line++] += (a ? b : 0) * multiplier;
  40322. if (fourthChannel) {
  40323. output[line++] += a * multiplier;
  40324. trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0;
  40325. }
  40326. }
  40327. if (weight >= amountToNext) {
  40328. actualPosition += channelsNum;
  40329. currentPosition = actualPosition;
  40330. weight -= amountToNext;
  40331. } else {
  40332. currentPosition += weight;
  40333. break;
  40334. }
  40335. } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels);
  40336. for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) {
  40337. weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1;
  40338. multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
  40339. outputBuffer[pixelOffset] = output[line++] * multiplier;
  40340. outputBuffer[++pixelOffset] = output[line++] * multiplier;
  40341. outputBuffer[++pixelOffset] = output[line++] * multiplier;
  40342. if (fourthChannel) outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor;
  40343. }
  40344. outputOffset += channelsNum;
  40345. } while (outputOffset < this.targetWidthMultipliedByChannels);
  40346. return outputBuffer;
  40347. };
  40348. Resize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) {
  40349. var ratioWeight = this.ratioWeightHeightPass;
  40350. var ratioWeightDivisor = 1 / ratioWeight;
  40351. var output = this.outputHeightWorkBench;
  40352. var outputBuffer = this.heightBuffer;
  40353. var trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount;
  40354. var weight = 0;
  40355. var amountToNext = 0;
  40356. var actualPosition = 0;
  40357. var currentPosition = 0;
  40358. var pixelOffset = 0;
  40359. var outputOffset = 0;
  40360. var caret = 0;
  40361. var multiplier = 1;
  40362. var r = 0;
  40363. var g = 0;
  40364. var b = 0;
  40365. var a = 0;
  40366. do {
  40367. for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
  40368. output[pixelOffset++] = 0;
  40369. output[pixelOffset++] = 0;
  40370. output[pixelOffset++] = 0;
  40371. if (fourthChannel) {
  40372. output[pixelOffset++] = 0;
  40373. trustworthyColorsCount[pixelOffset / 4 - 1] = 0;
  40374. }
  40375. }
  40376. weight = ratioWeight;
  40377. do {
  40378. amountToNext = 1 + actualPosition - currentPosition;
  40379. multiplier = Math.min(weight, amountToNext);
  40380. caret = actualPosition;
  40381. for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
  40382. r = buffer[caret++];
  40383. g = buffer[caret++];
  40384. b = buffer[caret++];
  40385. a = fourthChannel ? buffer[caret++] : 255; // Ignore RGB values if pixel is completely transparent
  40386. output[pixelOffset++] += (a ? r : 0) * multiplier;
  40387. output[pixelOffset++] += (a ? g : 0) * multiplier;
  40388. output[pixelOffset++] += (a ? b : 0) * multiplier;
  40389. if (fourthChannel) {
  40390. output[pixelOffset++] += a * multiplier;
  40391. trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0;
  40392. }
  40393. }
  40394. if (weight >= amountToNext) {
  40395. actualPosition = caret;
  40396. currentPosition = actualPosition;
  40397. weight -= amountToNext;
  40398. } else {
  40399. currentPosition += weight;
  40400. break;
  40401. }
  40402. } while (weight > 0 && actualPosition < this.widthPassResultSize);
  40403. for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
  40404. weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1;
  40405. multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
  40406. outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
  40407. outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
  40408. outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
  40409. if (fourthChannel) {
  40410. outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor);
  40411. }
  40412. }
  40413. } while (outputOffset < this.finalResultSize);
  40414. return outputBuffer;
  40415. };
  40416. Resize.prototype.resizeWidthInterpolatedRGB = function (buffer) {
  40417. return this._resizeWidthInterpolatedRGBChannels(buffer, false);
  40418. };
  40419. Resize.prototype.resizeWidthInterpolatedRGBA = function (buffer) {
  40420. return this._resizeWidthInterpolatedRGBChannels(buffer, true);
  40421. };
  40422. Resize.prototype.resizeWidthRGB = function (buffer) {
  40423. return this._resizeWidthRGBChannels(buffer, false);
  40424. };
  40425. Resize.prototype.resizeWidthRGBA = function (buffer) {
  40426. return this._resizeWidthRGBChannels(buffer, true);
  40427. };
  40428. Resize.prototype.resizeHeightInterpolated = function (buffer) {
  40429. var ratioWeight = this.ratioWeightHeightPass;
  40430. var outputBuffer = this.heightBuffer;
  40431. var weight = 0;
  40432. var finalOffset = 0;
  40433. var pixelOffset = 0;
  40434. var pixelOffsetAccumulated = 0;
  40435. var pixelOffsetAccumulated2 = 0;
  40436. var firstWeight = 0;
  40437. var secondWeight = 0;
  40438. var interpolationHeightSourceReadStop; // Handle for only one interpolation input being valid for start calculation:
  40439. for (; weight < 1 / 3; weight += ratioWeight) {
  40440. for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
  40441. outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]);
  40442. }
  40443. } // Adjust for overshoot of the last pass's counter:
  40444. weight -= 1 / 3;
  40445. for (interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) {
  40446. // Calculate weightings:
  40447. secondWeight = weight % 1;
  40448. firstWeight = 1 - secondWeight; // Interpolate:
  40449. pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels;
  40450. pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels;
  40451. for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
  40452. outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight);
  40453. }
  40454. } // Handle for only one interpolation input being valid for end calculation:
  40455. while (finalOffset < this.finalResultSize) {
  40456. for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
  40457. outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]);
  40458. }
  40459. }
  40460. return outputBuffer;
  40461. };
  40462. Resize.prototype.resizeHeightRGB = function (buffer) {
  40463. return this._resizeHeightRGBChannels(buffer, false);
  40464. };
  40465. Resize.prototype.resizeHeightRGBA = function (buffer) {
  40466. return this._resizeHeightRGBChannels(buffer, true);
  40467. };
  40468. Resize.prototype.resize = function (buffer) {
  40469. this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer)));
  40470. };
  40471. Resize.prototype.bypassResizer = function (buffer) {
  40472. // Just return the buffer passed:
  40473. return buffer;
  40474. };
  40475. Resize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) {
  40476. // Initialize the internal width pass buffers:
  40477. this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize);
  40478. if (!BILINEARAlgo) {
  40479. this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels);
  40480. if (this.colorChannels > 3) {
  40481. this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal);
  40482. }
  40483. }
  40484. };
  40485. Resize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) {
  40486. // Initialize the internal height pass buffers:
  40487. this.heightBuffer = this.generateUint8Buffer(this.finalResultSize);
  40488. if (!BILINEARAlgo) {
  40489. this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels);
  40490. if (this.colorChannels > 3) {
  40491. this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth);
  40492. }
  40493. }
  40494. };
  40495. Resize.prototype.generateFloatBuffer = function (bufferLength) {
  40496. // Generate a float32 typed array buffer:
  40497. try {
  40498. return new Float32Array(bufferLength);
  40499. } catch (error) {
  40500. return [];
  40501. }
  40502. };
  40503. Resize.prototype.generateFloat64Buffer = function (bufferLength) {
  40504. // Generate a float64 typed array buffer:
  40505. try {
  40506. return new Float64Array(bufferLength);
  40507. } catch (error) {
  40508. return [];
  40509. }
  40510. };
  40511. Resize.prototype.generateUint8Buffer = function (bufferLength) {
  40512. // Generate a uint8 typed array buffer:
  40513. try {
  40514. return new Uint8Array(bufferLength);
  40515. } catch (error) {
  40516. return [];
  40517. }
  40518. };
  40519. module.exports = Resize;
  40520. },{"core-js/modules/es.array-buffer.slice":172,"core-js/modules/es.array.iterator":182,"core-js/modules/es.object.to-string":197,"core-js/modules/es.typed-array.copy-within":208,"core-js/modules/es.typed-array.every":209,"core-js/modules/es.typed-array.fill":210,"core-js/modules/es.typed-array.filter":211,"core-js/modules/es.typed-array.find":213,"core-js/modules/es.typed-array.find-index":212,"core-js/modules/es.typed-array.float32-array":214,"core-js/modules/es.typed-array.float64-array":215,"core-js/modules/es.typed-array.for-each":216,"core-js/modules/es.typed-array.includes":217,"core-js/modules/es.typed-array.index-of":218,"core-js/modules/es.typed-array.iterator":219,"core-js/modules/es.typed-array.join":220,"core-js/modules/es.typed-array.last-index-of":221,"core-js/modules/es.typed-array.map":222,"core-js/modules/es.typed-array.reduce":224,"core-js/modules/es.typed-array.reduce-right":223,"core-js/modules/es.typed-array.reverse":225,"core-js/modules/es.typed-array.set":226,"core-js/modules/es.typed-array.slice":227,"core-js/modules/es.typed-array.some":228,"core-js/modules/es.typed-array.sort":229,"core-js/modules/es.typed-array.subarray":230,"core-js/modules/es.typed-array.to-locale-string":231,"core-js/modules/es.typed-array.to-string":232,"core-js/modules/es.typed-array.uint8-array":233}],402:[function(require,module,exports){
  40521. (function (Buffer){
  40522. "use strict";
  40523. /**
  40524. * Copyright (c) 2015 Guyon Roche
  40525. *
  40526. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40527. * of this software and associated documentation files (the "Software"), to deal
  40528. * in the Software without restriction, including without limitation the rights
  40529. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40530. * copies of the Software, and to permit persons to whom the Software is
  40531. * furnished to do so, subject to the following conditions:</p>
  40532. *
  40533. * The above copyright notice and this permission notice shall be included in
  40534. * all copies or substantial portions of the Software.
  40535. *
  40536. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40537. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40538. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40539. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40540. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40541. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40542. * THE SOFTWARE.
  40543. */
  40544. module.exports = {
  40545. nearestNeighbor: function nearestNeighbor(src, dst) {
  40546. var wSrc = src.width;
  40547. var hSrc = src.height;
  40548. var wDst = dst.width;
  40549. var hDst = dst.height;
  40550. var bufSrc = src.data;
  40551. var bufDst = dst.data;
  40552. for (var i = 0; i < hDst; i++) {
  40553. for (var j = 0; j < wDst; j++) {
  40554. var posDst = (i * wDst + j) * 4;
  40555. var iSrc = Math.floor(i * hSrc / hDst);
  40556. var jSrc = Math.floor(j * wSrc / wDst);
  40557. var posSrc = (iSrc * wSrc + jSrc) * 4;
  40558. bufDst[posDst++] = bufSrc[posSrc++];
  40559. bufDst[posDst++] = bufSrc[posSrc++];
  40560. bufDst[posDst++] = bufSrc[posSrc++];
  40561. bufDst[posDst++] = bufSrc[posSrc++];
  40562. }
  40563. }
  40564. },
  40565. bilinearInterpolation: function bilinearInterpolation(src, dst) {
  40566. var wSrc = src.width;
  40567. var hSrc = src.height;
  40568. var wDst = dst.width;
  40569. var hDst = dst.height;
  40570. var bufSrc = src.data;
  40571. var bufDst = dst.data;
  40572. var interpolate = function interpolate(k, kMin, vMin, kMax, vMax) {
  40573. // special case - k is integer
  40574. if (kMin === kMax) {
  40575. return vMin;
  40576. }
  40577. return Math.round((k - kMin) * vMax + (kMax - k) * vMin);
  40578. };
  40579. var assign = function assign(pos, offset, x, xMin, xMax, y, yMin, yMax) {
  40580. var posMin = (yMin * wSrc + xMin) * 4 + offset;
  40581. var posMax = (yMin * wSrc + xMax) * 4 + offset;
  40582. var vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); // special case, y is integer
  40583. if (yMax === yMin) {
  40584. bufDst[pos + offset] = vMin;
  40585. } else {
  40586. posMin = (yMax * wSrc + xMin) * 4 + offset;
  40587. posMax = (yMax * wSrc + xMax) * 4 + offset;
  40588. var vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);
  40589. bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax);
  40590. }
  40591. };
  40592. for (var i = 0; i < hDst; i++) {
  40593. for (var j = 0; j < wDst; j++) {
  40594. var posDst = (i * wDst + j) * 4; // x & y in src coordinates
  40595. var x = j * wSrc / wDst;
  40596. var xMin = Math.floor(x);
  40597. var xMax = Math.min(Math.ceil(x), wSrc - 1);
  40598. var y = i * hSrc / hDst;
  40599. var yMin = Math.floor(y);
  40600. var yMax = Math.min(Math.ceil(y), hSrc - 1);
  40601. assign(posDst, 0, x, xMin, xMax, y, yMin, yMax);
  40602. assign(posDst, 1, x, xMin, xMax, y, yMin, yMax);
  40603. assign(posDst, 2, x, xMin, xMax, y, yMin, yMax);
  40604. assign(posDst, 3, x, xMin, xMax, y, yMin, yMax);
  40605. }
  40606. }
  40607. },
  40608. _interpolate2D: function _interpolate2D(src, dst, options, interpolate) {
  40609. var bufSrc = src.data;
  40610. var bufDst = dst.data;
  40611. var wSrc = src.width;
  40612. var hSrc = src.height;
  40613. var wDst = dst.width;
  40614. var hDst = dst.height; // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares
  40615. var wM = Math.max(1, Math.floor(wSrc / wDst));
  40616. var wDst2 = wDst * wM;
  40617. var hM = Math.max(1, Math.floor(hSrc / hDst));
  40618. var hDst2 = hDst * hM; // ===========================================================
  40619. // Pass 1 - interpolate rows
  40620. // buf1 has width of dst2 and height of src
  40621. var buf1 = Buffer.alloc(wDst2 * hSrc * 4);
  40622. for (var i = 0; i < hSrc; i++) {
  40623. for (var j = 0; j < wDst2; j++) {
  40624. // i in src coords, j in dst coords
  40625. // calculate x in src coords
  40626. // this interpolation requires 4 sample points and the two inner ones must be real
  40627. // the outer points can be fudged for the edges.
  40628. // therefore (wSrc-1)/wDst2
  40629. var x = j * (wSrc - 1) / wDst2;
  40630. var xPos = Math.floor(x);
  40631. var t = x - xPos;
  40632. var srcPos = (i * wSrc + xPos) * 4;
  40633. var buf1Pos = (i * wDst2 + j) * 4;
  40634. for (var k = 0; k < 4; k++) {
  40635. var kPos = srcPos + k;
  40636. var x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4];
  40637. var x1 = bufSrc[kPos];
  40638. var x2 = bufSrc[kPos + 4];
  40639. var x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos];
  40640. buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t);
  40641. }
  40642. }
  40643. } // this._writeFile(wDst2, hSrc, buf1, "out/buf1.jpg");
  40644. // ===========================================================
  40645. // Pass 2 - interpolate columns
  40646. // buf2 has width and height of dst2
  40647. var buf2 = Buffer.alloc(wDst2 * hDst2 * 4);
  40648. for (var _i = 0; _i < hDst2; _i++) {
  40649. for (var _j = 0; _j < wDst2; _j++) {
  40650. // i&j in dst2 coords
  40651. // calculate y in buf1 coords
  40652. // this interpolation requires 4 sample points and the two inner ones must be real
  40653. // the outer points can be fudged for the edges.
  40654. // therefore (hSrc-1)/hDst2
  40655. var y = _i * (hSrc - 1) / hDst2;
  40656. var yPos = Math.floor(y);
  40657. var _t = y - yPos;
  40658. var _buf1Pos = (yPos * wDst2 + _j) * 4;
  40659. var buf2Pos = (_i * wDst2 + _j) * 4;
  40660. for (var _k = 0; _k < 4; _k++) {
  40661. var _kPos = _buf1Pos + _k;
  40662. var y0 = yPos > 0 ? buf1[_kPos - wDst2 * 4] : 2 * buf1[_kPos] - buf1[_kPos + wDst2 * 4];
  40663. var y1 = buf1[_kPos];
  40664. var y2 = buf1[_kPos + wDst2 * 4];
  40665. var y3 = yPos < hSrc - 2 ? buf1[_kPos + wDst2 * 8] : 2 * buf1[_kPos + wDst2 * 4] - buf1[_kPos];
  40666. buf2[buf2Pos + _k] = interpolate(y0, y1, y2, y3, _t);
  40667. }
  40668. }
  40669. } // this._writeFile(wDst2, hDst2, buf2, "out/buf2.jpg");
  40670. // ===========================================================
  40671. // Pass 3 - scale to dst
  40672. var m = wM * hM;
  40673. if (m > 1) {
  40674. for (var _i2 = 0; _i2 < hDst; _i2++) {
  40675. for (var _j2 = 0; _j2 < wDst; _j2++) {
  40676. // i&j in dst bounded coords
  40677. var r = 0;
  40678. var g = 0;
  40679. var b = 0;
  40680. var a = 0;
  40681. var realColors = 0;
  40682. for (var _y = 0; _y < hM; _y++) {
  40683. var _yPos = _i2 * hM + _y;
  40684. for (var _x = 0; _x < wM; _x++) {
  40685. var _xPos = _j2 * wM + _x;
  40686. var xyPos = (_yPos * wDst2 + _xPos) * 4;
  40687. var pixelAlpha = buf2[xyPos + 3];
  40688. if (pixelAlpha) {
  40689. r += buf2[xyPos];
  40690. g += buf2[xyPos + 1];
  40691. b += buf2[xyPos + 2];
  40692. realColors++;
  40693. }
  40694. a += pixelAlpha;
  40695. }
  40696. }
  40697. var pos = (_i2 * wDst + _j2) * 4;
  40698. bufDst[pos] = realColors ? Math.round(r / realColors) : 0;
  40699. bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0;
  40700. bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0;
  40701. bufDst[pos + 3] = Math.round(a / m);
  40702. }
  40703. }
  40704. } else {
  40705. // replace dst buffer with buf2
  40706. dst.data = buf2;
  40707. }
  40708. },
  40709. bicubicInterpolation: function bicubicInterpolation(src, dst, options) {
  40710. var interpolateCubic = function interpolateCubic(x0, x1, x2, x3, t) {
  40711. var a0 = x3 - x2 - x0 + x1;
  40712. var a1 = x0 - x1 - a0;
  40713. var a2 = x2 - x0;
  40714. var a3 = x1;
  40715. return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3));
  40716. };
  40717. return this._interpolate2D(src, dst, options, interpolateCubic);
  40718. },
  40719. hermiteInterpolation: function hermiteInterpolation(src, dst, options) {
  40720. var interpolateHermite = function interpolateHermite(x0, x1, x2, x3, t) {
  40721. var c0 = x1;
  40722. var c1 = 0.5 * (x2 - x0);
  40723. var c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3;
  40724. var c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2);
  40725. return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0)));
  40726. };
  40727. return this._interpolate2D(src, dst, options, interpolateHermite);
  40728. },
  40729. bezierInterpolation: function bezierInterpolation(src, dst, options) {
  40730. // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2)
  40731. // to predict control points (a & b) to be placed at n+0.5
  40732. // ya(n) = y(n) + (y(n+1)-y(n-1))/4
  40733. // yb(n) = y(n+1) - (y(n+2)-y(n))/4
  40734. // then use std bezier to interpolate [n,n+1)
  40735. // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3
  40736. // note the 3* factor for the two control points
  40737. // for edge cases, can choose:
  40738. // y(-1) = y(0) - 2*(y(1)-y(0))
  40739. // y(w) = y(w-1) + 2*(y(w-1)-y(w-2))
  40740. // but can go with y(-1) = y(0) and y(w) = y(w-1)
  40741. var interpolateBezier = function interpolateBezier(x0, x1, x2, x3, t) {
  40742. // x1, x2 are the knots, use x0 and x3 to calculate control points
  40743. var cp1 = x1 + (x2 - x0) / 4;
  40744. var cp2 = x2 - (x3 - x1) / 4;
  40745. var nt = 1 - t;
  40746. var c0 = x1 * nt * nt * nt;
  40747. var c1 = 3 * cp1 * nt * nt * t;
  40748. var c2 = 3 * cp2 * nt * t * t;
  40749. var c3 = x2 * t * t * t;
  40750. return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3)));
  40751. };
  40752. return this._interpolate2D(src, dst, options, interpolateBezier);
  40753. }
  40754. };
  40755. }).call(this,require("buffer").Buffer)
  40756. },{"buffer":47}],403:[function(require,module,exports){
  40757. (function (Buffer){
  40758. "use strict";
  40759. Object.defineProperty(exports, "__esModule", {
  40760. value: true
  40761. });
  40762. exports["default"] = void 0;
  40763. var _utils = require("@jimp/utils");
  40764. /**
  40765. * Rotates an image clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object.
  40766. * @param {number} deg the number of degrees to rotate the image by
  40767. * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed
  40768. */
  40769. function advancedRotate(deg, mode) {
  40770. deg %= 360;
  40771. var rad = deg * Math.PI / 180;
  40772. var cosine = Math.cos(rad);
  40773. var sine = Math.sin(rad); // the final width and height will change if resize == true
  40774. var w = this.bitmap.width;
  40775. var h = this.bitmap.height;
  40776. if (mode === true || typeof mode === 'string') {
  40777. // resize the image to it maximum dimension and blit the existing image
  40778. // onto the center so that when it is rotated the image is kept in bounds
  40779. // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle
  40780. // Plus 1 border pixel to ensure to show all rotated result for some cases.
  40781. w = Math.ceil(Math.abs(this.bitmap.width * cosine) + Math.abs(this.bitmap.height * sine)) + 1;
  40782. h = Math.ceil(Math.abs(this.bitmap.width * sine) + Math.abs(this.bitmap.height * cosine)) + 1; // Ensure destination to have even size to a better result.
  40783. if (w % 2 !== 0) {
  40784. w++;
  40785. }
  40786. if (h % 2 !== 0) {
  40787. h++;
  40788. }
  40789. var c = this.cloneQuiet();
  40790. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  40791. this.bitmap.data.writeUInt32BE(this._background, idx);
  40792. });
  40793. var max = Math.max(w, h, this.bitmap.width, this.bitmap.height);
  40794. this.resize(max, max, mode);
  40795. this.blit(c, this.bitmap.width / 2 - c.bitmap.width / 2, this.bitmap.height / 2 - c.bitmap.height / 2);
  40796. }
  40797. var bW = this.bitmap.width;
  40798. var bH = this.bitmap.height;
  40799. var dstBuffer = Buffer.alloc(this.bitmap.data.length);
  40800. function createTranslationFunction(deltaX, deltaY) {
  40801. return function (x, y) {
  40802. return {
  40803. x: x + deltaX,
  40804. y: y + deltaY
  40805. };
  40806. };
  40807. }
  40808. var translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));
  40809. var translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5);
  40810. for (var y = 1; y <= bH; y++) {
  40811. for (var x = 1; x <= bW; x++) {
  40812. var cartesian = translate2Cartesian(x, y);
  40813. var source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x);
  40814. var dstIdx = bW * (y - 1) + x - 1 << 2;
  40815. if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) {
  40816. var srcIdx = (bW * (source.y | 0) + source.x | 0) << 2;
  40817. var pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);
  40818. dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);
  40819. } else {
  40820. // reset off-image pixels
  40821. dstBuffer.writeUInt32BE(this._background, dstIdx);
  40822. }
  40823. }
  40824. }
  40825. this.bitmap.data = dstBuffer;
  40826. if (mode === true || typeof mode === 'string') {
  40827. // now crop the image to the final size
  40828. var _x = bW / 2 - w / 2;
  40829. var _y = bH / 2 - h / 2;
  40830. this.crop(_x, _y, w, h);
  40831. }
  40832. }
  40833. var _default = function _default() {
  40834. return {
  40835. /**
  40836. * Rotates the image clockwise by a number of degrees. By default the width and height of the image will be resized appropriately.
  40837. * @param {number} deg the number of degrees to rotate the image by
  40838. * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed
  40839. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  40840. * @returns {Jimp} this for chaining of methods
  40841. */
  40842. rotate: function rotate(deg, mode, cb) {
  40843. // enable overloading
  40844. if (typeof mode === 'undefined' || mode === null) {
  40845. // e.g. image.resize(120);
  40846. // e.g. image.resize(120, null, cb);
  40847. // e.g. image.resize(120, undefined, cb);
  40848. mode = true;
  40849. }
  40850. if (typeof mode === 'function' && typeof cb === 'undefined') {
  40851. // e.g. image.resize(120, cb);
  40852. cb = mode;
  40853. mode = true;
  40854. }
  40855. if (typeof deg !== 'number') {
  40856. return _utils.throwError.call(this, 'deg must be a number', cb);
  40857. }
  40858. if (typeof mode !== 'boolean' && typeof mode !== 'string') {
  40859. return _utils.throwError.call(this, 'mode must be a boolean or a string', cb);
  40860. }
  40861. advancedRotate.call(this, deg, mode, cb);
  40862. if ((0, _utils.isNodePattern)(cb)) {
  40863. cb.call(this, null, this);
  40864. }
  40865. return this;
  40866. }
  40867. };
  40868. };
  40869. exports["default"] = _default;
  40870. module.exports = exports.default;
  40871. }).call(this,require("buffer").Buffer)
  40872. },{"@jimp/utils":414,"buffer":47}],404:[function(require,module,exports){
  40873. "use strict";
  40874. Object.defineProperty(exports, "__esModule", {
  40875. value: true
  40876. });
  40877. exports["default"] = void 0;
  40878. var _utils = require("@jimp/utils");
  40879. var _default = function _default() {
  40880. return {
  40881. /**
  40882. * Uniformly scales the image by a factor.
  40883. * @param {number} f the factor to scale the image by
  40884. * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
  40885. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  40886. * @returns {Jimp} this for chaining of methods
  40887. */
  40888. scale: function scale(f, mode, cb) {
  40889. if (typeof f !== 'number') {
  40890. return _utils.throwError.call(this, 'f must be a number', cb);
  40891. }
  40892. if (f < 0) {
  40893. return _utils.throwError.call(this, 'f must be a positive number', cb);
  40894. }
  40895. if (typeof mode === 'function' && typeof cb === 'undefined') {
  40896. cb = mode;
  40897. mode = null;
  40898. }
  40899. var w = this.bitmap.width * f;
  40900. var h = this.bitmap.height * f;
  40901. this.resize(w, h, mode);
  40902. if ((0, _utils.isNodePattern)(cb)) {
  40903. cb.call(this, null, this);
  40904. }
  40905. return this;
  40906. },
  40907. /**
  40908. * Scale the image to the largest size that fits inside the rectangle that has the given width and height.
  40909. * @param {number} w the width to resize the image to
  40910. * @param {number} h the height to resize the image to
  40911. * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
  40912. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  40913. * @returns {Jimp} this for chaining of methods
  40914. */
  40915. scaleToFit: function scaleToFit(w, h, mode, cb) {
  40916. if (typeof w !== 'number' || typeof h !== 'number') {
  40917. return _utils.throwError.call(this, 'w and h must be numbers', cb);
  40918. }
  40919. if (typeof mode === 'function' && typeof cb === 'undefined') {
  40920. cb = mode;
  40921. mode = null;
  40922. }
  40923. var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;
  40924. this.scale(f, mode);
  40925. if ((0, _utils.isNodePattern)(cb)) {
  40926. cb.call(this, null, this);
  40927. }
  40928. return this;
  40929. }
  40930. };
  40931. };
  40932. exports["default"] = _default;
  40933. module.exports = exports.default;
  40934. },{"@jimp/utils":414}],405:[function(require,module,exports){
  40935. "use strict";
  40936. Object.defineProperty(exports, "__esModule", {
  40937. value: true
  40938. });
  40939. exports["default"] = void 0;
  40940. var _utils = require("@jimp/utils");
  40941. /**
  40942. * Creates a circle out of an image.
  40943. * @param {function(Error, Jimp)} options (optional)
  40944. * opacity - opacity of the shadow between 0 and 1
  40945. * size,- of the shadow
  40946. * blur - how blurry the shadow is
  40947. * x- x position of shadow
  40948. * y - y position of shadow
  40949. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  40950. * @returns {Jimp} this for chaining of methods
  40951. */
  40952. var _default = function _default() {
  40953. return {
  40954. shadow: function shadow() {
  40955. var _this = this;
  40956. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  40957. var cb = arguments.length > 1 ? arguments[1] : undefined;
  40958. if (typeof options === 'function') {
  40959. cb = options;
  40960. options = {};
  40961. }
  40962. var _options = options,
  40963. _options$opacity = _options.opacity,
  40964. opacity = _options$opacity === void 0 ? 0.7 : _options$opacity,
  40965. _options$size = _options.size,
  40966. size = _options$size === void 0 ? 1.1 : _options$size,
  40967. _options$x = _options.x,
  40968. x = _options$x === void 0 ? -25 : _options$x,
  40969. _options$y = _options.y,
  40970. y = _options$y === void 0 ? 25 : _options$y,
  40971. _options$blur = _options.blur,
  40972. blur = _options$blur === void 0 ? 5 : _options$blur; // clone the image
  40973. var orig = this.clone();
  40974. var shadow = this.clone(); // turn all it's pixels black
  40975. shadow.scan(0, 0, shadow.bitmap.width, shadow.bitmap.height, function (x, y, idx) {
  40976. shadow.bitmap.data[idx] = 0x00;
  40977. shadow.bitmap.data[idx + 1] = 0x00;
  40978. shadow.bitmap.data[idx + 2] = 0x00; // up the opacity a little,
  40979. shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(shadow.bitmap.data[idx + 3] * opacity);
  40980. _this.bitmap.data[idx] = 0x00;
  40981. _this.bitmap.data[idx + 1] = 0x00;
  40982. _this.bitmap.data[idx + 2] = 0x00;
  40983. _this.bitmap.data[idx + 3] = 0x00;
  40984. }); // enlarge it. This creates a "shadow".
  40985. shadow.resize(shadow.bitmap.width * size, shadow.bitmap.height * size).blur(blur); // Then blit the "shadow" onto the background and the image on top of that.
  40986. this.composite(shadow, x, y);
  40987. this.composite(orig, 0, 0);
  40988. if ((0, _utils.isNodePattern)(cb)) {
  40989. cb.call(this, null, this);
  40990. }
  40991. return this;
  40992. }
  40993. };
  40994. };
  40995. exports["default"] = _default;
  40996. module.exports = exports.default;
  40997. },{"@jimp/utils":414}],406:[function(require,module,exports){
  40998. "use strict";
  40999. require("core-js/modules/es.regexp.exec");
  41000. require("core-js/modules/es.string.replace");
  41001. Object.defineProperty(exports, "__esModule", {
  41002. value: true
  41003. });
  41004. exports["default"] = void 0;
  41005. var _utils = require("@jimp/utils");
  41006. /**
  41007. * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default
  41008. * @param {number} options object
  41009. * max: A number auto limited between 0 - 255
  41010. * replace: (optional) A number auto limited between 0 - 255 (default 255)
  41011. * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true)
  41012. * @param {number} cb (optional) a callback for when complete
  41013. * @return {this} this for chaining of methods
  41014. */
  41015. var _default = function _default() {
  41016. return {
  41017. threshold: function threshold(_ref, cb) {
  41018. var _this = this;
  41019. var max = _ref.max,
  41020. _ref$replace = _ref.replace,
  41021. replace = _ref$replace === void 0 ? 255 : _ref$replace,
  41022. _ref$autoGreyscale = _ref.autoGreyscale,
  41023. autoGreyscale = _ref$autoGreyscale === void 0 ? true : _ref$autoGreyscale;
  41024. if (typeof max !== 'number') {
  41025. return _utils.throwError.call(this, 'max must be a number', cb);
  41026. }
  41027. if (typeof replace !== 'number') {
  41028. return _utils.throwError.call(this, 'replace must be a number', cb);
  41029. }
  41030. if (typeof autoGreyscale !== 'boolean') {
  41031. return _utils.throwError.call(this, 'autoGreyscale must be a boolean', cb);
  41032. }
  41033. max = this.constructor.limit255(max);
  41034. replace = this.constructor.limit255(replace);
  41035. if (autoGreyscale) {
  41036. this.greyscale();
  41037. }
  41038. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
  41039. var grey = _this.bitmap.data[idx] < max ? _this.bitmap.data[idx] : replace;
  41040. _this.bitmap.data[idx] = grey;
  41041. _this.bitmap.data[idx + 1] = grey;
  41042. _this.bitmap.data[idx + 2] = grey;
  41043. });
  41044. if ((0, _utils.isNodePattern)(cb)) {
  41045. cb.call(this, null, this);
  41046. }
  41047. return this;
  41048. }
  41049. };
  41050. };
  41051. exports["default"] = _default;
  41052. module.exports = exports.default;
  41053. },{"@jimp/utils":414,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.replace":205}],407:[function(require,module,exports){
  41054. "use strict";
  41055. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41056. require("core-js/modules/es.array.map");
  41057. Object.defineProperty(exports, "__esModule", {
  41058. value: true
  41059. });
  41060. exports["default"] = void 0;
  41061. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  41062. var _timm = require("timm");
  41063. var _pluginBlit = _interopRequireDefault(require("@jimp/plugin-blit"));
  41064. var _pluginBlur = _interopRequireDefault(require("@jimp/plugin-blur"));
  41065. var _pluginCircle = _interopRequireDefault(require("@jimp/plugin-circle"));
  41066. var _pluginColor = _interopRequireDefault(require("@jimp/plugin-color"));
  41067. var _pluginContain = _interopRequireDefault(require("@jimp/plugin-contain"));
  41068. var _pluginCover = _interopRequireDefault(require("@jimp/plugin-cover"));
  41069. var _pluginCrop = _interopRequireDefault(require("@jimp/plugin-crop"));
  41070. var _pluginDisplace = _interopRequireDefault(require("@jimp/plugin-displace"));
  41071. var _pluginDither = _interopRequireDefault(require("@jimp/plugin-dither"));
  41072. var _pluginFisheye = _interopRequireDefault(require("@jimp/plugin-fisheye"));
  41073. var _pluginFlip = _interopRequireDefault(require("@jimp/plugin-flip"));
  41074. var _pluginGaussian = _interopRequireDefault(require("@jimp/plugin-gaussian"));
  41075. var _pluginInvert = _interopRequireDefault(require("@jimp/plugin-invert"));
  41076. var _pluginMask = _interopRequireDefault(require("@jimp/plugin-mask"));
  41077. var _pluginNormalize = _interopRequireDefault(require("@jimp/plugin-normalize"));
  41078. var _pluginPrint = _interopRequireDefault(require("@jimp/plugin-print"));
  41079. var _pluginResize = _interopRequireDefault(require("@jimp/plugin-resize"));
  41080. var _pluginRotate = _interopRequireDefault(require("@jimp/plugin-rotate"));
  41081. var _pluginScale = _interopRequireDefault(require("@jimp/plugin-scale"));
  41082. var _pluginShadow = _interopRequireDefault(require("@jimp/plugin-shadow"));
  41083. var _pluginThreshold = _interopRequireDefault(require("@jimp/plugin-threshold"));
  41084. var plugins = [_pluginBlit["default"], _pluginBlur["default"], _pluginCircle["default"], _pluginColor["default"], _pluginContain["default"], _pluginCover["default"], _pluginCrop["default"], _pluginDisplace["default"], _pluginDither["default"], _pluginFisheye["default"], _pluginFlip["default"], _pluginGaussian["default"], _pluginInvert["default"], _pluginMask["default"], _pluginNormalize["default"], _pluginPrint["default"], _pluginResize["default"], _pluginRotate["default"], _pluginScale["default"], _pluginShadow["default"], _pluginThreshold["default"]];
  41085. var _default = function _default(jimpEvChange) {
  41086. var initializedPlugins = plugins.map(function (pluginModule) {
  41087. var plugin = pluginModule(jimpEvChange) || {};
  41088. if (!plugin["class"] && !plugin.constants) {
  41089. // Default to class function
  41090. plugin = {
  41091. "class": plugin
  41092. };
  41093. }
  41094. return plugin;
  41095. });
  41096. return _timm.mergeDeep.apply(void 0, (0, _toConsumableArray2["default"])(initializedPlugins));
  41097. };
  41098. exports["default"] = _default;
  41099. module.exports = exports.default;
  41100. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/plugin-blit":380,"@jimp/plugin-blur":382,"@jimp/plugin-circle":383,"@jimp/plugin-color":384,"@jimp/plugin-contain":385,"@jimp/plugin-cover":386,"@jimp/plugin-crop":387,"@jimp/plugin-displace":388,"@jimp/plugin-dither":389,"@jimp/plugin-fisheye":390,"@jimp/plugin-flip":391,"@jimp/plugin-gaussian":392,"@jimp/plugin-invert":393,"@jimp/plugin-mask":394,"@jimp/plugin-normalize":395,"@jimp/plugin-print":396,"@jimp/plugin-resize":400,"@jimp/plugin-rotate":403,"@jimp/plugin-scale":404,"@jimp/plugin-shadow":405,"@jimp/plugin-threshold":406,"core-js/modules/es.array.map":184,"timm":356}],408:[function(require,module,exports){
  41101. "use strict";
  41102. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41103. Object.defineProperty(exports, "__esModule", {
  41104. value: true
  41105. });
  41106. exports["default"] = void 0;
  41107. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  41108. var _bmpJs = _interopRequireDefault(require("bmp-js"));
  41109. var _utils = require("@jimp/utils");
  41110. var MIME_TYPE = 'image/bmp';
  41111. var MIME_TYPE_SECOND = 'image/x-ms-bmp';
  41112. function toAGBR(image) {
  41113. return (0, _utils.scan)(image, 0, 0, image.bitmap.width, image.bitmap.height, function (x, y, index) {
  41114. var red = this.bitmap.data[index + 0];
  41115. var green = this.bitmap.data[index + 1];
  41116. var blue = this.bitmap.data[index + 2];
  41117. var alpha = this.bitmap.data[index + 3];
  41118. this.bitmap.data[index + 0] = alpha;
  41119. this.bitmap.data[index + 1] = blue;
  41120. this.bitmap.data[index + 2] = green;
  41121. this.bitmap.data[index + 3] = red;
  41122. }).bitmap;
  41123. }
  41124. function fromAGBR(bitmap) {
  41125. return (0, _utils.scan)({
  41126. bitmap: bitmap
  41127. }, 0, 0, bitmap.width, bitmap.height, function (x, y, index) {
  41128. var alpha = this.bitmap.data[index + 0];
  41129. var blue = this.bitmap.data[index + 1];
  41130. var green = this.bitmap.data[index + 2];
  41131. var red = this.bitmap.data[index + 3];
  41132. this.bitmap.data[index + 0] = red;
  41133. this.bitmap.data[index + 1] = green;
  41134. this.bitmap.data[index + 2] = blue;
  41135. this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff;
  41136. }).bitmap;
  41137. }
  41138. var decode = function decode(data) {
  41139. return fromAGBR(_bmpJs["default"].decode(data));
  41140. };
  41141. var encode = function encode(image) {
  41142. return _bmpJs["default"].encode(toAGBR(image)).data;
  41143. };
  41144. var _default = function _default() {
  41145. var _decoders, _encoders;
  41146. return {
  41147. mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['bmp']),
  41148. constants: {
  41149. MIME_BMP: MIME_TYPE,
  41150. MIME_X_MS_BMP: MIME_TYPE_SECOND
  41151. },
  41152. decoders: (_decoders = {}, (0, _defineProperty2["default"])(_decoders, MIME_TYPE, decode), (0, _defineProperty2["default"])(_decoders, MIME_TYPE_SECOND, decode), _decoders),
  41153. encoders: (_encoders = {}, (0, _defineProperty2["default"])(_encoders, MIME_TYPE, encode), (0, _defineProperty2["default"])(_encoders, MIME_TYPE_SECOND, encode), _encoders)
  41154. };
  41155. };
  41156. exports["default"] = _default;
  41157. module.exports = exports.default;
  41158. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"bmp-js":29}],409:[function(require,module,exports){
  41159. (function (Buffer){
  41160. "use strict";
  41161. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41162. Object.defineProperty(exports, "__esModule", {
  41163. value: true
  41164. });
  41165. exports["default"] = void 0;
  41166. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  41167. var _omggif = _interopRequireDefault(require("omggif"));
  41168. var MIME_TYPE = 'image/gif';
  41169. var _default = function _default() {
  41170. return {
  41171. mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['gif']),
  41172. constants: {
  41173. MIME_GIF: MIME_TYPE
  41174. },
  41175. decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
  41176. var gifObj = new _omggif["default"].GifReader(data);
  41177. var gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);
  41178. gifObj.decodeAndBlitFrameRGBA(0, gifData);
  41179. return {
  41180. data: gifData,
  41181. width: gifObj.width,
  41182. height: gifObj.height
  41183. };
  41184. })
  41185. };
  41186. };
  41187. exports["default"] = _default;
  41188. module.exports = exports.default;
  41189. }).call(this,require("buffer").Buffer)
  41190. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"buffer":47,"omggif":264}],410:[function(require,module,exports){
  41191. "use strict";
  41192. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41193. Object.defineProperty(exports, "__esModule", {
  41194. value: true
  41195. });
  41196. exports["default"] = void 0;
  41197. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  41198. var _jpegJs = _interopRequireDefault(require("jpeg-js"));
  41199. var _utils = require("@jimp/utils");
  41200. var MIME_TYPE = 'image/jpeg';
  41201. var _default = function _default() {
  41202. return {
  41203. mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['jpeg', 'jpg', 'jpe']),
  41204. constants: {
  41205. MIME_JPEG: MIME_TYPE
  41206. },
  41207. decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _jpegJs["default"].decode),
  41208. encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) {
  41209. return _jpegJs["default"].encode(image.bitmap, image._quality).data;
  41210. }),
  41211. "class": {
  41212. // The quality to be used when saving JPEG images
  41213. _quality: 100,
  41214. /**
  41215. * Sets the quality of the image when saving as JPEG format (default is 100)
  41216. * @param {number} n The quality to use 0-100
  41217. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  41218. * @returns {Jimp} this for chaining of methods
  41219. */
  41220. quality: function quality(n, cb) {
  41221. if (typeof n !== 'number') {
  41222. return _utils.throwError.call(this, 'n must be a number', cb);
  41223. }
  41224. if (n < 0 || n > 100) {
  41225. return _utils.throwError.call(this, 'n must be a number 0 - 100', cb);
  41226. }
  41227. this._quality = Math.round(n);
  41228. if ((0, _utils.isNodePattern)(cb)) {
  41229. cb.call(this, null, this);
  41230. }
  41231. return this;
  41232. }
  41233. }
  41234. };
  41235. };
  41236. exports["default"] = _default;
  41237. module.exports = exports.default;
  41238. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"jpeg-js":259}],411:[function(require,module,exports){
  41239. "use strict";
  41240. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41241. Object.defineProperty(exports, "__esModule", {
  41242. value: true
  41243. });
  41244. exports["default"] = void 0;
  41245. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  41246. var _pngjs = require("pngjs");
  41247. var _utils = require("@jimp/utils");
  41248. var MIME_TYPE = 'image/png'; // PNG filter types
  41249. var PNG_FILTER_AUTO = -1;
  41250. var PNG_FILTER_NONE = 0;
  41251. var PNG_FILTER_SUB = 1;
  41252. var PNG_FILTER_UP = 2;
  41253. var PNG_FILTER_AVERAGE = 3;
  41254. var PNG_FILTER_PATH = 4;
  41255. var _default = function _default() {
  41256. return {
  41257. mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['png']),
  41258. constants: {
  41259. MIME_PNG: MIME_TYPE,
  41260. PNG_FILTER_AUTO: PNG_FILTER_AUTO,
  41261. PNG_FILTER_NONE: PNG_FILTER_NONE,
  41262. PNG_FILTER_SUB: PNG_FILTER_SUB,
  41263. PNG_FILTER_UP: PNG_FILTER_UP,
  41264. PNG_FILTER_AVERAGE: PNG_FILTER_AVERAGE,
  41265. PNG_FILTER_PATH: PNG_FILTER_PATH
  41266. },
  41267. hasAlpha: (0, _defineProperty2["default"])({}, MIME_TYPE, true),
  41268. decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _pngjs.PNG.sync.read),
  41269. encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
  41270. var png = new _pngjs.PNG({
  41271. width: data.bitmap.width,
  41272. height: data.bitmap.height
  41273. });
  41274. png.data = data.bitmap.data;
  41275. return _pngjs.PNG.sync.write(png, {
  41276. width: data.bitmap.width,
  41277. height: data.bitmap.height,
  41278. deflateLevel: data._deflateLevel,
  41279. deflateStrategy: data._deflateStrategy,
  41280. filterType: data._filterType,
  41281. colorType: typeof data._colorType === 'number' ? data._colorType : data._rgba ? 6 : 2,
  41282. inputHasAlpha: data._rgba
  41283. });
  41284. }),
  41285. "class": {
  41286. _deflateLevel: 9,
  41287. _deflateStrategy: 3,
  41288. _filterType: PNG_FILTER_AUTO,
  41289. _colorType: null,
  41290. /**
  41291. * Sets the deflate level used when saving as PNG format (default is 9)
  41292. * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression.
  41293. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  41294. * @returns {Jimp} this for chaining of methods
  41295. */
  41296. deflateLevel: function deflateLevel(l, cb) {
  41297. if (typeof l !== 'number') {
  41298. return _utils.throwError.call(this, 'l must be a number', cb);
  41299. }
  41300. if (l < 0 || l > 9) {
  41301. return _utils.throwError.call(this, 'l must be a number 0 - 9', cb);
  41302. }
  41303. this._deflateLevel = Math.round(l);
  41304. if ((0, _utils.isNodePattern)(cb)) {
  41305. cb.call(this, null, this);
  41306. }
  41307. return this;
  41308. },
  41309. /**
  41310. * Sets the deflate strategy used when saving as PNG format (default is 3)
  41311. * @param {number} s Deflate strategy to use 0-3.
  41312. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  41313. * @returns {Jimp} this for chaining of methods
  41314. */
  41315. deflateStrategy: function deflateStrategy(s, cb) {
  41316. if (typeof s !== 'number') {
  41317. return _utils.throwError.call(this, 's must be a number', cb);
  41318. }
  41319. if (s < 0 || s > 3) {
  41320. return _utils.throwError.call(this, 's must be a number 0 - 3', cb);
  41321. }
  41322. this._deflateStrategy = Math.round(s);
  41323. if ((0, _utils.isNodePattern)(cb)) {
  41324. cb.call(this, null, this);
  41325. }
  41326. return this;
  41327. },
  41328. /**
  41329. * Sets the filter type used when saving as PNG format (default is automatic filters)
  41330. * @param {number} f The quality to use -1-4.
  41331. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  41332. * @returns {Jimp} this for chaining of methods
  41333. */
  41334. filterType: function filterType(f, cb) {
  41335. if (typeof f !== 'number') {
  41336. return _utils.throwError.call(this, 'n must be a number', cb);
  41337. }
  41338. if (f < -1 || f > 4) {
  41339. return _utils.throwError.call(this, 'n must be -1 (auto) or a number 0 - 4', cb);
  41340. }
  41341. this._filterType = Math.round(f);
  41342. if ((0, _utils.isNodePattern)(cb)) {
  41343. cb.call(this, null, this);
  41344. }
  41345. return this;
  41346. },
  41347. /**
  41348. * Sets the color type used when saving as PNG format
  41349. * @param {number} s color type to use 0, 2, 4, 6.
  41350. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  41351. * @returns {Jimp} this for chaining of methods
  41352. */
  41353. colorType: function colorType(s, cb) {
  41354. if (typeof s !== 'number') {
  41355. return _utils.throwError.call(this, 's must be a number', cb);
  41356. }
  41357. if (s !== 0 && s !== 2 && s !== 4 && s !== 6) {
  41358. return _utils.throwError.call(this, 's must be a number 0, 2, 4, 6.', cb);
  41359. }
  41360. this._colorType = Math.round(s);
  41361. if ((0, _utils.isNodePattern)(cb)) {
  41362. cb.call(this, null, this);
  41363. }
  41364. return this;
  41365. }
  41366. }
  41367. };
  41368. };
  41369. exports["default"] = _default;
  41370. module.exports = exports.default;
  41371. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"pngjs":308}],412:[function(require,module,exports){
  41372. (function (Buffer){
  41373. "use strict";
  41374. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41375. Object.defineProperty(exports, "__esModule", {
  41376. value: true
  41377. });
  41378. exports["default"] = void 0;
  41379. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  41380. var _utif = _interopRequireDefault(require("utif"));
  41381. var MIME_TYPE = 'image/tiff';
  41382. var _default = function _default() {
  41383. return {
  41384. mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['tiff', 'tif']),
  41385. constants: {
  41386. MIME_TIFF: MIME_TYPE
  41387. },
  41388. decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
  41389. var ifds = _utif["default"].decode(data);
  41390. var page = ifds[0];
  41391. _utif["default"].decodeImages(data, ifds);
  41392. var rgba = _utif["default"].toRGBA8(page);
  41393. return {
  41394. data: Buffer.from(rgba),
  41395. width: page.t256[0],
  41396. height: page.t257[0]
  41397. };
  41398. }),
  41399. encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) {
  41400. var tiff = _utif["default"].encodeImage(image.bitmap.data, image.bitmap.width, image.bitmap.height);
  41401. return Buffer.from(tiff);
  41402. })
  41403. };
  41404. };
  41405. exports["default"] = _default;
  41406. module.exports = exports.default;
  41407. }).call(this,require("buffer").Buffer)
  41408. },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"buffer":47,"utif":361}],413:[function(require,module,exports){
  41409. "use strict";
  41410. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41411. Object.defineProperty(exports, "__esModule", {
  41412. value: true
  41413. });
  41414. exports["default"] = void 0;
  41415. var _timm = require("timm");
  41416. var _jpeg = _interopRequireDefault(require("@jimp/jpeg"));
  41417. var _png = _interopRequireDefault(require("@jimp/png"));
  41418. var _bmp = _interopRequireDefault(require("@jimp/bmp"));
  41419. var _tiff = _interopRequireDefault(require("@jimp/tiff"));
  41420. var _gif = _interopRequireDefault(require("@jimp/gif"));
  41421. var _default = function _default() {
  41422. return (0, _timm.mergeDeep)((0, _jpeg["default"])(), (0, _png["default"])(), (0, _bmp["default"])(), (0, _tiff["default"])(), (0, _gif["default"])());
  41423. };
  41424. exports["default"] = _default;
  41425. module.exports = exports.default;
  41426. },{"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/bmp":408,"@jimp/gif":409,"@jimp/jpeg":410,"@jimp/png":411,"@jimp/tiff":412,"timm":356}],414:[function(require,module,exports){
  41427. "use strict";
  41428. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  41429. Object.defineProperty(exports, "__esModule", {
  41430. value: true
  41431. });
  41432. exports.isNodePattern = isNodePattern;
  41433. exports.throwError = throwError;
  41434. exports.scan = scan;
  41435. exports.scanIterator = scanIterator;
  41436. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  41437. require("regenerator-runtime/runtime");
  41438. var _marked =
  41439. /*#__PURE__*/
  41440. _regenerator["default"].mark(scanIterator);
  41441. function isNodePattern(cb) {
  41442. if (typeof cb === 'undefined') {
  41443. return false;
  41444. }
  41445. if (typeof cb !== 'function') {
  41446. throw new TypeError('Callback must be a function');
  41447. }
  41448. return true;
  41449. }
  41450. function throwError(error, cb) {
  41451. if (typeof error === 'string') {
  41452. error = new Error(error);
  41453. }
  41454. if (typeof cb === 'function') {
  41455. return cb.call(this, error);
  41456. }
  41457. throw error;
  41458. }
  41459. function scan(image, x, y, w, h, f) {
  41460. // round input
  41461. x = Math.round(x);
  41462. y = Math.round(y);
  41463. w = Math.round(w);
  41464. h = Math.round(h);
  41465. for (var _y = y; _y < y + h; _y++) {
  41466. for (var _x = x; _x < x + w; _x++) {
  41467. var idx = image.bitmap.width * _y + _x << 2;
  41468. f.call(image, _x, _y, idx);
  41469. }
  41470. }
  41471. return image;
  41472. }
  41473. function scanIterator(image, x, y, w, h) {
  41474. var _y, _x, idx;
  41475. return _regenerator["default"].wrap(function scanIterator$(_context) {
  41476. while (1) {
  41477. switch (_context.prev = _context.next) {
  41478. case 0:
  41479. // round input
  41480. x = Math.round(x);
  41481. y = Math.round(y);
  41482. w = Math.round(w);
  41483. h = Math.round(h);
  41484. _y = y;
  41485. case 5:
  41486. if (!(_y < y + h)) {
  41487. _context.next = 17;
  41488. break;
  41489. }
  41490. _x = x;
  41491. case 7:
  41492. if (!(_x < x + w)) {
  41493. _context.next = 14;
  41494. break;
  41495. }
  41496. idx = image.bitmap.width * _y + _x << 2;
  41497. _context.next = 11;
  41498. return {
  41499. x: _x,
  41500. y: _y,
  41501. idx: idx,
  41502. image: image
  41503. };
  41504. case 11:
  41505. _x++;
  41506. _context.next = 7;
  41507. break;
  41508. case 14:
  41509. _y++;
  41510. _context.next = 5;
  41511. break;
  41512. case 17:
  41513. case "end":
  41514. return _context.stop();
  41515. }
  41516. }
  41517. }, _marked);
  41518. }
  41519. },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/regenerator":21,"regenerator-runtime/runtime":332}]},{},[379])(379)
  41520. });