browser.js 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.png = 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){
  2. (function (Buffer){
  3. 'use strict';
  4. var interlaceUtils = require('./interlace');
  5. var pixelBppMapper = [
  6. // 0 - dummy entry
  7. function() {},
  8. // 1 - L
  9. // 0: 0, 1: 0, 2: 0, 3: 0xff
  10. function(pxData, data, pxPos, rawPos) {
  11. if (rawPos === data.length) {
  12. throw new Error('Ran out of data');
  13. }
  14. var pixel = data[rawPos];
  15. pxData[pxPos] = pixel;
  16. pxData[pxPos + 1] = pixel;
  17. pxData[pxPos + 2] = pixel;
  18. pxData[pxPos + 3] = 0xff;
  19. },
  20. // 2 - LA
  21. // 0: 0, 1: 0, 2: 0, 3: 1
  22. function(pxData, data, pxPos, rawPos) {
  23. if (rawPos + 1 >= data.length) {
  24. throw new Error('Ran out of data');
  25. }
  26. var pixel = data[rawPos];
  27. pxData[pxPos] = pixel;
  28. pxData[pxPos + 1] = pixel;
  29. pxData[pxPos + 2] = pixel;
  30. pxData[pxPos + 3] = data[rawPos + 1];
  31. },
  32. // 3 - RGB
  33. // 0: 0, 1: 1, 2: 2, 3: 0xff
  34. function(pxData, data, pxPos, rawPos) {
  35. if (rawPos + 2 >= data.length) {
  36. throw new Error('Ran out of data');
  37. }
  38. pxData[pxPos] = data[rawPos];
  39. pxData[pxPos + 1] = data[rawPos + 1];
  40. pxData[pxPos + 2] = data[rawPos + 2];
  41. pxData[pxPos + 3] = 0xff;
  42. },
  43. // 4 - RGBA
  44. // 0: 0, 1: 1, 2: 2, 3: 3
  45. function(pxData, data, pxPos, rawPos) {
  46. if (rawPos + 3 >= data.length) {
  47. throw new Error('Ran out of data');
  48. }
  49. pxData[pxPos] = data[rawPos];
  50. pxData[pxPos + 1] = data[rawPos + 1];
  51. pxData[pxPos + 2] = data[rawPos + 2];
  52. pxData[pxPos + 3] = data[rawPos + 3];
  53. }
  54. ];
  55. var pixelBppCustomMapper = [
  56. // 0 - dummy entry
  57. function() {},
  58. // 1 - L
  59. // 0: 0, 1: 0, 2: 0, 3: 0xff
  60. function(pxData, pixelData, pxPos, maxBit) {
  61. var pixel = pixelData[0];
  62. pxData[pxPos] = pixel;
  63. pxData[pxPos + 1] = pixel;
  64. pxData[pxPos + 2] = pixel;
  65. pxData[pxPos + 3] = maxBit;
  66. },
  67. // 2 - LA
  68. // 0: 0, 1: 0, 2: 0, 3: 1
  69. function(pxData, pixelData, pxPos) {
  70. var pixel = pixelData[0];
  71. pxData[pxPos] = pixel;
  72. pxData[pxPos + 1] = pixel;
  73. pxData[pxPos + 2] = pixel;
  74. pxData[pxPos + 3] = pixelData[1];
  75. },
  76. // 3 - RGB
  77. // 0: 0, 1: 1, 2: 2, 3: 0xff
  78. function(pxData, pixelData, pxPos, maxBit) {
  79. pxData[pxPos] = pixelData[0];
  80. pxData[pxPos + 1] = pixelData[1];
  81. pxData[pxPos + 2] = pixelData[2];
  82. pxData[pxPos + 3] = maxBit;
  83. },
  84. // 4 - RGBA
  85. // 0: 0, 1: 1, 2: 2, 3: 3
  86. function(pxData, pixelData, pxPos) {
  87. pxData[pxPos] = pixelData[0];
  88. pxData[pxPos + 1] = pixelData[1];
  89. pxData[pxPos + 2] = pixelData[2];
  90. pxData[pxPos + 3] = pixelData[3];
  91. }
  92. ];
  93. function bitRetriever(data, depth) {
  94. var leftOver = [];
  95. var i = 0;
  96. function split() {
  97. if (i === data.length) {
  98. throw new Error('Ran out of data');
  99. }
  100. var byte = data[i];
  101. i++;
  102. var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
  103. switch (depth) {
  104. default:
  105. throw new Error('unrecognised depth');
  106. case 16:
  107. byte2 = data[i];
  108. i++;
  109. leftOver.push(((byte << 8) + byte2));
  110. break;
  111. case 4:
  112. byte2 = byte & 0x0f;
  113. byte1 = byte >> 4;
  114. leftOver.push(byte1, byte2);
  115. break;
  116. case 2:
  117. byte4 = byte & 3;
  118. byte3 = byte >> 2 & 3;
  119. byte2 = byte >> 4 & 3;
  120. byte1 = byte >> 6 & 3;
  121. leftOver.push(byte1, byte2, byte3, byte4);
  122. break;
  123. case 1:
  124. byte8 = byte & 1;
  125. byte7 = byte >> 1 & 1;
  126. byte6 = byte >> 2 & 1;
  127. byte5 = byte >> 3 & 1;
  128. byte4 = byte >> 4 & 1;
  129. byte3 = byte >> 5 & 1;
  130. byte2 = byte >> 6 & 1;
  131. byte1 = byte >> 7 & 1;
  132. leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
  133. break;
  134. }
  135. }
  136. return {
  137. get: function(count) {
  138. while (leftOver.length < count) {
  139. split();
  140. }
  141. var returner = leftOver.slice(0, count);
  142. leftOver = leftOver.slice(count);
  143. return returner;
  144. },
  145. resetAfterLine: function() {
  146. leftOver.length = 0;
  147. },
  148. end: function() {
  149. if (i !== data.length) {
  150. throw new Error('extra data found');
  151. }
  152. }
  153. };
  154. }
  155. function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
  156. var imageWidth = image.width;
  157. var imageHeight = image.height;
  158. var imagePass = image.index;
  159. for (var y = 0; y < imageHeight; y++) {
  160. for (var x = 0; x < imageWidth; x++) {
  161. var pxPos = getPxPos(x, y, imagePass);
  162. pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
  163. rawPos += bpp; //eslint-disable-line no-param-reassign
  164. }
  165. }
  166. return rawPos;
  167. }
  168. function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
  169. var imageWidth = image.width;
  170. var imageHeight = image.height;
  171. var imagePass = image.index;
  172. for (var y = 0; y < imageHeight; y++) {
  173. for (var x = 0; x < imageWidth; x++) {
  174. var pixelData = bits.get(bpp);
  175. var pxPos = getPxPos(x, y, imagePass);
  176. pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
  177. }
  178. bits.resetAfterLine();
  179. }
  180. }
  181. exports.dataToBitMap = function(data, bitmapInfo) {
  182. var width = bitmapInfo.width;
  183. var height = bitmapInfo.height;
  184. var depth = bitmapInfo.depth;
  185. var bpp = bitmapInfo.bpp;
  186. var interlace = bitmapInfo.interlace;
  187. if (depth !== 8) {
  188. var bits = bitRetriever(data, depth);
  189. }
  190. var pxData;
  191. if (depth <= 8) {
  192. pxData = new Buffer(width * height * 4);
  193. }
  194. else {
  195. pxData = new Uint16Array(width * height * 4);
  196. }
  197. var maxBit = Math.pow(2, depth) - 1;
  198. var rawPos = 0;
  199. var images;
  200. var getPxPos;
  201. if (interlace) {
  202. images = interlaceUtils.getImagePasses(width, height);
  203. getPxPos = interlaceUtils.getInterlaceIterator(width, height);
  204. }
  205. else {
  206. var nonInterlacedPxPos = 0;
  207. getPxPos = function() {
  208. var returner = nonInterlacedPxPos;
  209. nonInterlacedPxPos += 4;
  210. return returner;
  211. };
  212. images = [{ width: width, height: height }];
  213. }
  214. for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
  215. if (depth === 8) {
  216. rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
  217. }
  218. else {
  219. mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
  220. }
  221. }
  222. if (depth === 8) {
  223. if (rawPos !== data.length) {
  224. throw new Error('extra data found');
  225. }
  226. }
  227. else {
  228. bits.end();
  229. }
  230. return pxData;
  231. };
  232. }).call(this,require("buffer").Buffer)
  233. },{"./interlace":11,"buffer":32}],2:[function(require,module,exports){
  234. (function (Buffer){
  235. 'use strict';
  236. var constants = require('./constants');
  237. module.exports = function(dataIn, width, height, options) {
  238. var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
  239. if (options.colorType === options.inputColorType) {
  240. var bigEndian = (function() {
  241. var buffer = new ArrayBuffer(2);
  242. new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
  243. // Int16Array uses the platform's endianness.
  244. return new Int16Array(buffer)[0] !== 256;
  245. })();
  246. // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
  247. if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
  248. return dataIn;
  249. }
  250. }
  251. // map to a UInt16 array if data is 16bit, fix endianness below
  252. var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
  253. var maxValue = 255;
  254. var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
  255. if (inBpp === 4 && !options.inputHasAlpha) {
  256. inBpp = 3;
  257. }
  258. var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
  259. if (options.bitDepth === 16) {
  260. maxValue = 65535;
  261. outBpp *= 2;
  262. }
  263. var outData = new Buffer(width * height * outBpp);
  264. var inIndex = 0;
  265. var outIndex = 0;
  266. var bgColor = options.bgColor || {};
  267. if (bgColor.red === undefined) {
  268. bgColor.red = maxValue;
  269. }
  270. if (bgColor.green === undefined) {
  271. bgColor.green = maxValue;
  272. }
  273. if (bgColor.blue === undefined) {
  274. bgColor.blue = maxValue;
  275. }
  276. function getRGBA() {
  277. var red;
  278. var green;
  279. var blue;
  280. var alpha = maxValue;
  281. switch (options.inputColorType) {
  282. case constants.COLORTYPE_COLOR_ALPHA:
  283. alpha = data[inIndex + 3];
  284. red = data[inIndex];
  285. green = data[inIndex + 1];
  286. blue = data[inIndex + 2];
  287. break;
  288. case constants.COLORTYPE_COLOR:
  289. red = data[inIndex];
  290. green = data[inIndex + 1];
  291. blue = data[inIndex + 2];
  292. break;
  293. case constants.COLORTYPE_ALPHA:
  294. alpha = data[inIndex + 1];
  295. red = data[inIndex];
  296. green = red;
  297. blue = red;
  298. break;
  299. case constants.COLORTYPE_GRAYSCALE:
  300. red = data[inIndex];
  301. green = red;
  302. blue = red;
  303. break;
  304. default:
  305. throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
  306. }
  307. if (options.inputHasAlpha) {
  308. if (!outHasAlpha) {
  309. alpha /= maxValue;
  310. red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
  311. green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
  312. blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
  313. }
  314. }
  315. return { red: red, green: green, blue: blue, alpha: alpha };
  316. }
  317. for (var y = 0; y < height; y++) {
  318. for (var x = 0; x < width; x++) {
  319. var rgba = getRGBA(data, inIndex);
  320. switch (options.colorType) {
  321. case constants.COLORTYPE_COLOR_ALPHA:
  322. case constants.COLORTYPE_COLOR:
  323. if (options.bitDepth === 8) {
  324. outData[outIndex] = rgba.red;
  325. outData[outIndex + 1] = rgba.green;
  326. outData[outIndex + 2] = rgba.blue;
  327. if (outHasAlpha) {
  328. outData[outIndex + 3] = rgba.alpha;
  329. }
  330. }
  331. else {
  332. outData.writeUInt16BE(rgba.red, outIndex);
  333. outData.writeUInt16BE(rgba.green, outIndex + 2);
  334. outData.writeUInt16BE(rgba.blue, outIndex + 4);
  335. if (outHasAlpha) {
  336. outData.writeUInt16BE(rgba.alpha, outIndex + 6);
  337. }
  338. }
  339. break;
  340. case constants.COLORTYPE_ALPHA:
  341. case constants.COLORTYPE_GRAYSCALE:
  342. // Convert to grayscale and alpha
  343. var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
  344. if (options.bitDepth === 8) {
  345. outData[outIndex] = grayscale;
  346. if (outHasAlpha) {
  347. outData[outIndex + 1] = rgba.alpha;
  348. }
  349. }
  350. else {
  351. outData.writeUInt16BE(grayscale, outIndex);
  352. if (outHasAlpha) {
  353. outData.writeUInt16BE(rgba.alpha, outIndex + 2);
  354. }
  355. }
  356. break;
  357. default:
  358. throw new Error('unrecognised color Type ' + options.colorType);
  359. }
  360. inIndex += inBpp;
  361. outIndex += outBpp;
  362. }
  363. }
  364. return outData;
  365. };
  366. }).call(this,require("buffer").Buffer)
  367. },{"./constants":4,"buffer":32}],3:[function(require,module,exports){
  368. (function (process,Buffer){
  369. 'use strict';
  370. var util = require('util');
  371. var Stream = require('stream');
  372. var ChunkStream = module.exports = function() {
  373. Stream.call(this);
  374. this._buffers = [];
  375. this._buffered = 0;
  376. this._reads = [];
  377. this._paused = false;
  378. this._encoding = 'utf8';
  379. this.writable = true;
  380. };
  381. util.inherits(ChunkStream, Stream);
  382. ChunkStream.prototype.read = function(length, callback) {
  383. this._reads.push({
  384. length: Math.abs(length), // if length < 0 then at most this length
  385. allowLess: length < 0,
  386. func: callback
  387. });
  388. process.nextTick(function() {
  389. this._process();
  390. // its paused and there is not enought data then ask for more
  391. if (this._paused && this._reads.length > 0) {
  392. this._paused = false;
  393. this.emit('drain');
  394. }
  395. }.bind(this));
  396. };
  397. ChunkStream.prototype.write = function(data, encoding) {
  398. if (!this.writable) {
  399. this.emit('error', new Error('Stream not writable'));
  400. return false;
  401. }
  402. var dataBuffer;
  403. if (Buffer.isBuffer(data)) {
  404. dataBuffer = data;
  405. }
  406. else {
  407. dataBuffer = new Buffer(data, encoding || this._encoding);
  408. }
  409. this._buffers.push(dataBuffer);
  410. this._buffered += dataBuffer.length;
  411. this._process();
  412. // ok if there are no more read requests
  413. if (this._reads && this._reads.length === 0) {
  414. this._paused = true;
  415. }
  416. return this.writable && !this._paused;
  417. };
  418. ChunkStream.prototype.end = function(data, encoding) {
  419. if (data) {
  420. this.write(data, encoding);
  421. }
  422. this.writable = false;
  423. // already destroyed
  424. if (!this._buffers) {
  425. return;
  426. }
  427. // enqueue or handle end
  428. if (this._buffers.length === 0) {
  429. this._end();
  430. }
  431. else {
  432. this._buffers.push(null);
  433. this._process();
  434. }
  435. };
  436. ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
  437. ChunkStream.prototype._end = function() {
  438. if (this._reads.length > 0) {
  439. this.emit('error',
  440. new Error('Unexpected end of input')
  441. );
  442. }
  443. this.destroy();
  444. };
  445. ChunkStream.prototype.destroy = function() {
  446. if (!this._buffers) {
  447. return;
  448. }
  449. this.writable = false;
  450. this._reads = null;
  451. this._buffers = null;
  452. this.emit('close');
  453. };
  454. ChunkStream.prototype._processReadAllowingLess = function(read) {
  455. // ok there is any data so that we can satisfy this request
  456. this._reads.shift(); // == read
  457. // first we need to peek into first buffer
  458. var smallerBuf = this._buffers[0];
  459. // ok there is more data than we need
  460. if (smallerBuf.length > read.length) {
  461. this._buffered -= read.length;
  462. this._buffers[0] = smallerBuf.slice(read.length);
  463. read.func.call(this, smallerBuf.slice(0, read.length));
  464. }
  465. else {
  466. // ok this is less than maximum length so use it all
  467. this._buffered -= smallerBuf.length;
  468. this._buffers.shift(); // == smallerBuf
  469. read.func.call(this, smallerBuf);
  470. }
  471. };
  472. ChunkStream.prototype._processRead = function(read) {
  473. this._reads.shift(); // == read
  474. var pos = 0;
  475. var count = 0;
  476. var data = new Buffer(read.length);
  477. // create buffer for all data
  478. while (pos < read.length) {
  479. var buf = this._buffers[count++];
  480. var len = Math.min(buf.length, read.length - pos);
  481. buf.copy(data, pos, 0, len);
  482. pos += len;
  483. // last buffer wasn't used all so just slice it and leave
  484. if (len !== buf.length) {
  485. this._buffers[--count] = buf.slice(len);
  486. }
  487. }
  488. // remove all used buffers
  489. if (count > 0) {
  490. this._buffers.splice(0, count);
  491. }
  492. this._buffered -= read.length;
  493. read.func.call(this, data);
  494. };
  495. ChunkStream.prototype._process = function() {
  496. try {
  497. // as long as there is any data and read requests
  498. while (this._buffered > 0 && this._reads && this._reads.length > 0) {
  499. var read = this._reads[0];
  500. // read any data (but no more than length)
  501. if (read.allowLess) {
  502. this._processReadAllowingLess(read);
  503. }
  504. else if (this._buffered >= read.length) {
  505. // ok we can meet some expectations
  506. this._processRead(read);
  507. }
  508. else {
  509. // not enought data to satisfy first request in queue
  510. // so we need to wait for more
  511. break;
  512. }
  513. }
  514. if (this._buffers && !this.writable) {
  515. this._end();
  516. }
  517. }
  518. catch (ex) {
  519. this.emit('error', ex);
  520. }
  521. };
  522. }).call(this,require('_process'),require("buffer").Buffer)
  523. },{"_process":51,"buffer":32,"stream":64,"util":69}],4:[function(require,module,exports){
  524. 'use strict';
  525. module.exports = {
  526. PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
  527. TYPE_IHDR: 0x49484452,
  528. TYPE_IEND: 0x49454e44,
  529. TYPE_IDAT: 0x49444154,
  530. TYPE_PLTE: 0x504c5445,
  531. TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
  532. TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
  533. // color-type bits
  534. COLORTYPE_GRAYSCALE: 0,
  535. COLORTYPE_PALETTE: 1,
  536. COLORTYPE_COLOR: 2,
  537. COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
  538. // color-type combinations
  539. COLORTYPE_PALETTE_COLOR: 3,
  540. COLORTYPE_COLOR_ALPHA: 6,
  541. COLORTYPE_TO_BPP_MAP: {
  542. 0: 1,
  543. 2: 3,
  544. 3: 1,
  545. 4: 2,
  546. 6: 4
  547. },
  548. GAMMA_DIVISION: 100000
  549. };
  550. },{}],5:[function(require,module,exports){
  551. 'use strict';
  552. var crcTable = [];
  553. (function() {
  554. for (var i = 0; i < 256; i++) {
  555. var currentCrc = i;
  556. for (var j = 0; j < 8; j++) {
  557. if (currentCrc & 1) {
  558. currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
  559. }
  560. else {
  561. currentCrc = currentCrc >>> 1;
  562. }
  563. }
  564. crcTable[i] = currentCrc;
  565. }
  566. }());
  567. var CrcCalculator = module.exports = function() {
  568. this._crc = -1;
  569. };
  570. CrcCalculator.prototype.write = function(data) {
  571. for (var i = 0; i < data.length; i++) {
  572. this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
  573. }
  574. return true;
  575. };
  576. CrcCalculator.prototype.crc32 = function() {
  577. return this._crc ^ -1;
  578. };
  579. CrcCalculator.crc32 = function(buf) {
  580. var crc = -1;
  581. for (var i = 0; i < buf.length; i++) {
  582. crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
  583. }
  584. return crc ^ -1;
  585. };
  586. },{}],6:[function(require,module,exports){
  587. (function (Buffer){
  588. 'use strict';
  589. var paethPredictor = require('./paeth-predictor');
  590. function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
  591. for (var x = 0; x < byteWidth; x++) {
  592. rawData[rawPos + x] = pxData[pxPos + x];
  593. }
  594. }
  595. function filterSumNone(pxData, pxPos, byteWidth) {
  596. var sum = 0;
  597. var length = pxPos + byteWidth;
  598. for (var i = pxPos; i < length; i++) {
  599. sum += Math.abs(pxData[i]);
  600. }
  601. return sum;
  602. }
  603. function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  604. for (var x = 0; x < byteWidth; x++) {
  605. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  606. var val = pxData[pxPos + x] - left;
  607. rawData[rawPos + x] = val;
  608. }
  609. }
  610. function filterSumSub(pxData, pxPos, byteWidth, bpp) {
  611. var sum = 0;
  612. for (var x = 0; x < byteWidth; x++) {
  613. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  614. var val = pxData[pxPos + x] - left;
  615. sum += Math.abs(val);
  616. }
  617. return sum;
  618. }
  619. function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
  620. for (var x = 0; x < byteWidth; x++) {
  621. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  622. var val = pxData[pxPos + x] - up;
  623. rawData[rawPos + x] = val;
  624. }
  625. }
  626. function filterSumUp(pxData, pxPos, byteWidth) {
  627. var sum = 0;
  628. var length = pxPos + byteWidth;
  629. for (var x = pxPos; x < length; x++) {
  630. var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
  631. var val = pxData[x] - up;
  632. sum += Math.abs(val);
  633. }
  634. return sum;
  635. }
  636. function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  637. for (var x = 0; x < byteWidth; x++) {
  638. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  639. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  640. var val = pxData[pxPos + x] - ((left + up) >> 1);
  641. rawData[rawPos + x] = val;
  642. }
  643. }
  644. function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
  645. var sum = 0;
  646. for (var x = 0; x < byteWidth; x++) {
  647. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  648. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  649. var val = pxData[pxPos + x] - ((left + up) >> 1);
  650. sum += Math.abs(val);
  651. }
  652. return sum;
  653. }
  654. function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  655. for (var x = 0; x < byteWidth; x++) {
  656. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  657. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  658. var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  659. var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  660. rawData[rawPos + x] = val;
  661. }
  662. }
  663. function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
  664. var sum = 0;
  665. for (var x = 0; x < byteWidth; x++) {
  666. var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  667. var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  668. var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  669. var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  670. sum += Math.abs(val);
  671. }
  672. return sum;
  673. }
  674. var filters = {
  675. 0: filterNone,
  676. 1: filterSub,
  677. 2: filterUp,
  678. 3: filterAvg,
  679. 4: filterPaeth
  680. };
  681. var filterSums = {
  682. 0: filterSumNone,
  683. 1: filterSumSub,
  684. 2: filterSumUp,
  685. 3: filterSumAvg,
  686. 4: filterSumPaeth
  687. };
  688. module.exports = function(pxData, width, height, options, bpp) {
  689. var filterTypes;
  690. if (!('filterType' in options) || options.filterType === -1) {
  691. filterTypes = [0, 1, 2, 3, 4];
  692. }
  693. else if (typeof options.filterType === 'number') {
  694. filterTypes = [options.filterType];
  695. }
  696. else {
  697. throw new Error('unrecognised filter types');
  698. }
  699. if (options.bitDepth === 16) {
  700. bpp *= 2;
  701. }
  702. var byteWidth = width * bpp;
  703. var rawPos = 0;
  704. var pxPos = 0;
  705. var rawData = new Buffer((byteWidth + 1) * height);
  706. var sel = filterTypes[0];
  707. for (var y = 0; y < height; y++) {
  708. if (filterTypes.length > 1) {
  709. // find best filter for this line (with lowest sum of values)
  710. var min = Infinity;
  711. for (var i = 0; i < filterTypes.length; i++) {
  712. var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
  713. if (sum < min) {
  714. sel = filterTypes[i];
  715. min = sum;
  716. }
  717. }
  718. }
  719. rawData[rawPos] = sel;
  720. rawPos++;
  721. filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
  722. rawPos += byteWidth;
  723. pxPos += byteWidth;
  724. }
  725. return rawData;
  726. };
  727. }).call(this,require("buffer").Buffer)
  728. },{"./paeth-predictor":15,"buffer":32}],7:[function(require,module,exports){
  729. (function (Buffer){
  730. 'use strict';
  731. var util = require('util');
  732. var ChunkStream = require('./chunkstream');
  733. var Filter = require('./filter-parse');
  734. var FilterAsync = module.exports = function(bitmapInfo) {
  735. ChunkStream.call(this);
  736. var buffers = [];
  737. var that = this;
  738. this._filter = new Filter(bitmapInfo, {
  739. read: this.read.bind(this),
  740. write: function(buffer) {
  741. buffers.push(buffer);
  742. },
  743. complete: function() {
  744. that.emit('complete', Buffer.concat(buffers));
  745. }
  746. });
  747. this._filter.start();
  748. };
  749. util.inherits(FilterAsync, ChunkStream);
  750. }).call(this,require("buffer").Buffer)
  751. },{"./chunkstream":3,"./filter-parse":9,"buffer":32,"util":69}],8:[function(require,module,exports){
  752. (function (Buffer){
  753. 'use strict';
  754. var SyncReader = require('./sync-reader');
  755. var Filter = require('./filter-parse');
  756. exports.process = function(inBuffer, bitmapInfo) {
  757. var outBuffers = [];
  758. var reader = new SyncReader(inBuffer);
  759. var filter = new Filter(bitmapInfo, {
  760. read: reader.read.bind(reader),
  761. write: function(bufferPart) {
  762. outBuffers.push(bufferPart);
  763. },
  764. complete: function() {
  765. }
  766. });
  767. filter.start();
  768. reader.process();
  769. return Buffer.concat(outBuffers);
  770. };
  771. }).call(this,require("buffer").Buffer)
  772. },{"./filter-parse":9,"./sync-reader":22,"buffer":32}],9:[function(require,module,exports){
  773. (function (Buffer){
  774. 'use strict';
  775. var interlaceUtils = require('./interlace');
  776. var paethPredictor = require('./paeth-predictor');
  777. function getByteWidth(width, bpp, depth) {
  778. var byteWidth = width * bpp;
  779. if (depth !== 8) {
  780. byteWidth = Math.ceil(byteWidth / (8 / depth));
  781. }
  782. return byteWidth;
  783. }
  784. var Filter = module.exports = function(bitmapInfo, dependencies) {
  785. var width = bitmapInfo.width;
  786. var height = bitmapInfo.height;
  787. var interlace = bitmapInfo.interlace;
  788. var bpp = bitmapInfo.bpp;
  789. var depth = bitmapInfo.depth;
  790. this.read = dependencies.read;
  791. this.write = dependencies.write;
  792. this.complete = dependencies.complete;
  793. this._imageIndex = 0;
  794. this._images = [];
  795. if (interlace) {
  796. var passes = interlaceUtils.getImagePasses(width, height);
  797. for (var i = 0; i < passes.length; i++) {
  798. this._images.push({
  799. byteWidth: getByteWidth(passes[i].width, bpp, depth),
  800. height: passes[i].height,
  801. lineIndex: 0
  802. });
  803. }
  804. }
  805. else {
  806. this._images.push({
  807. byteWidth: getByteWidth(width, bpp, depth),
  808. height: height,
  809. lineIndex: 0
  810. });
  811. }
  812. // when filtering the line we look at the pixel to the left
  813. // the spec also says it is done on a byte level regardless of the number of pixels
  814. // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
  815. // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
  816. if (depth === 8) {
  817. this._xComparison = bpp;
  818. }
  819. else if (depth === 16) {
  820. this._xComparison = bpp * 2;
  821. }
  822. else {
  823. this._xComparison = 1;
  824. }
  825. };
  826. Filter.prototype.start = function() {
  827. this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
  828. };
  829. Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
  830. var xComparison = this._xComparison;
  831. var xBiggerThan = xComparison - 1;
  832. for (var x = 0; x < byteWidth; x++) {
  833. var rawByte = rawData[1 + x];
  834. var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  835. unfilteredLine[x] = rawByte + f1Left;
  836. }
  837. };
  838. Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
  839. var lastLine = this._lastLine;
  840. for (var x = 0; x < byteWidth; x++) {
  841. var rawByte = rawData[1 + x];
  842. var f2Up = lastLine ? lastLine[x] : 0;
  843. unfilteredLine[x] = rawByte + f2Up;
  844. }
  845. };
  846. Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
  847. var xComparison = this._xComparison;
  848. var xBiggerThan = xComparison - 1;
  849. var lastLine = this._lastLine;
  850. for (var x = 0; x < byteWidth; x++) {
  851. var rawByte = rawData[1 + x];
  852. var f3Up = lastLine ? lastLine[x] : 0;
  853. var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  854. var f3Add = Math.floor((f3Left + f3Up) / 2);
  855. unfilteredLine[x] = rawByte + f3Add;
  856. }
  857. };
  858. Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
  859. var xComparison = this._xComparison;
  860. var xBiggerThan = xComparison - 1;
  861. var lastLine = this._lastLine;
  862. for (var x = 0; x < byteWidth; x++) {
  863. var rawByte = rawData[1 + x];
  864. var f4Up = lastLine ? lastLine[x] : 0;
  865. var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  866. var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
  867. var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
  868. unfilteredLine[x] = rawByte + f4Add;
  869. }
  870. };
  871. Filter.prototype._reverseFilterLine = function(rawData) {
  872. var filter = rawData[0];
  873. var unfilteredLine;
  874. var currentImage = this._images[this._imageIndex];
  875. var byteWidth = currentImage.byteWidth;
  876. if (filter === 0) {
  877. unfilteredLine = rawData.slice(1, byteWidth + 1);
  878. }
  879. else {
  880. unfilteredLine = new Buffer(byteWidth);
  881. switch (filter) {
  882. case 1:
  883. this._unFilterType1(rawData, unfilteredLine, byteWidth);
  884. break;
  885. case 2:
  886. this._unFilterType2(rawData, unfilteredLine, byteWidth);
  887. break;
  888. case 3:
  889. this._unFilterType3(rawData, unfilteredLine, byteWidth);
  890. break;
  891. case 4:
  892. this._unFilterType4(rawData, unfilteredLine, byteWidth);
  893. break;
  894. default:
  895. throw new Error('Unrecognised filter type - ' + filter);
  896. }
  897. }
  898. this.write(unfilteredLine);
  899. currentImage.lineIndex++;
  900. if (currentImage.lineIndex >= currentImage.height) {
  901. this._lastLine = null;
  902. this._imageIndex++;
  903. currentImage = this._images[this._imageIndex];
  904. }
  905. else {
  906. this._lastLine = unfilteredLine;
  907. }
  908. if (currentImage) {
  909. // read, using the byte width that may be from the new current image
  910. this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
  911. }
  912. else {
  913. this._lastLine = null;
  914. this.complete();
  915. }
  916. };
  917. }).call(this,require("buffer").Buffer)
  918. },{"./interlace":11,"./paeth-predictor":15,"buffer":32}],10:[function(require,module,exports){
  919. (function (Buffer){
  920. 'use strict';
  921. function dePalette(indata, outdata, width, height, palette) {
  922. var pxPos = 0;
  923. // use values from palette
  924. for (var y = 0; y < height; y++) {
  925. for (var x = 0; x < width; x++) {
  926. var color = palette[indata[pxPos]];
  927. if (!color) {
  928. throw new Error('index ' + indata[pxPos] + ' not in palette');
  929. }
  930. for (var i = 0; i < 4; i++) {
  931. outdata[pxPos + i] = color[i];
  932. }
  933. pxPos += 4;
  934. }
  935. }
  936. }
  937. function replaceTransparentColor(indata, outdata, width, height, transColor) {
  938. var pxPos = 0;
  939. for (var y = 0; y < height; y++) {
  940. for (var x = 0; x < width; x++) {
  941. var makeTrans = false;
  942. if (transColor.length === 1) {
  943. if (transColor[0] === indata[pxPos]) {
  944. makeTrans = true;
  945. }
  946. }
  947. else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
  948. makeTrans = true;
  949. }
  950. if (makeTrans) {
  951. for (var i = 0; i < 4; i++) {
  952. outdata[pxPos + i] = 0;
  953. }
  954. }
  955. pxPos += 4;
  956. }
  957. }
  958. }
  959. function scaleDepth(indata, outdata, width, height, depth) {
  960. var maxOutSample = 255;
  961. var maxInSample = Math.pow(2, depth) - 1;
  962. var pxPos = 0;
  963. for (var y = 0; y < height; y++) {
  964. for (var x = 0; x < width; x++) {
  965. for (var i = 0; i < 4; i++) {
  966. outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
  967. }
  968. pxPos += 4;
  969. }
  970. }
  971. }
  972. module.exports = function(indata, imageData) {
  973. var depth = imageData.depth;
  974. var width = imageData.width;
  975. var height = imageData.height;
  976. var colorType = imageData.colorType;
  977. var transColor = imageData.transColor;
  978. var palette = imageData.palette;
  979. var outdata = indata; // only different for 16 bits
  980. if (colorType === 3) { // paletted
  981. dePalette(indata, outdata, width, height, palette);
  982. }
  983. else {
  984. if (transColor) {
  985. replaceTransparentColor(indata, outdata, width, height, transColor);
  986. }
  987. // if it needs scaling
  988. if (depth !== 8) {
  989. // if we need to change the buffer size
  990. if (depth === 16) {
  991. outdata = new Buffer(width * height * 4);
  992. }
  993. scaleDepth(indata, outdata, width, height, depth);
  994. }
  995. }
  996. return outdata;
  997. };
  998. }).call(this,require("buffer").Buffer)
  999. },{"buffer":32}],11:[function(require,module,exports){
  1000. 'use strict';
  1001. // Adam 7
  1002. // 0 1 2 3 4 5 6 7
  1003. // 0 x 6 4 6 x 6 4 6
  1004. // 1 7 7 7 7 7 7 7 7
  1005. // 2 5 6 5 6 5 6 5 6
  1006. // 3 7 7 7 7 7 7 7 7
  1007. // 4 3 6 4 6 3 6 4 6
  1008. // 5 7 7 7 7 7 7 7 7
  1009. // 6 5 6 5 6 5 6 5 6
  1010. // 7 7 7 7 7 7 7 7 7
  1011. var imagePasses = [
  1012. { // pass 1 - 1px
  1013. x: [0],
  1014. y: [0]
  1015. },
  1016. { // pass 2 - 1px
  1017. x: [4],
  1018. y: [0]
  1019. },
  1020. { // pass 3 - 2px
  1021. x: [0, 4],
  1022. y: [4]
  1023. },
  1024. { // pass 4 - 4px
  1025. x: [2, 6],
  1026. y: [0, 4]
  1027. },
  1028. { // pass 5 - 8px
  1029. x: [0, 2, 4, 6],
  1030. y: [2, 6]
  1031. },
  1032. { // pass 6 - 16px
  1033. x: [1, 3, 5, 7],
  1034. y: [0, 2, 4, 6]
  1035. },
  1036. { // pass 7 - 32px
  1037. x: [0, 1, 2, 3, 4, 5, 6, 7],
  1038. y: [1, 3, 5, 7]
  1039. }
  1040. ];
  1041. exports.getImagePasses = function(width, height) {
  1042. var images = [];
  1043. var xLeftOver = width % 8;
  1044. var yLeftOver = height % 8;
  1045. var xRepeats = (width - xLeftOver) / 8;
  1046. var yRepeats = (height - yLeftOver) / 8;
  1047. for (var i = 0; i < imagePasses.length; i++) {
  1048. var pass = imagePasses[i];
  1049. var passWidth = xRepeats * pass.x.length;
  1050. var passHeight = yRepeats * pass.y.length;
  1051. for (var j = 0; j < pass.x.length; j++) {
  1052. if (pass.x[j] < xLeftOver) {
  1053. passWidth++;
  1054. }
  1055. else {
  1056. break;
  1057. }
  1058. }
  1059. for (j = 0; j < pass.y.length; j++) {
  1060. if (pass.y[j] < yLeftOver) {
  1061. passHeight++;
  1062. }
  1063. else {
  1064. break;
  1065. }
  1066. }
  1067. if (passWidth > 0 && passHeight > 0) {
  1068. images.push({ width: passWidth, height: passHeight, index: i });
  1069. }
  1070. }
  1071. return images;
  1072. };
  1073. exports.getInterlaceIterator = function(width) {
  1074. return function(x, y, pass) {
  1075. var outerXLeftOver = x % imagePasses[pass].x.length;
  1076. var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
  1077. var outerYLeftOver = y % imagePasses[pass].y.length;
  1078. var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
  1079. return (outerX * 4) + (outerY * width * 4);
  1080. };
  1081. };
  1082. },{}],12:[function(require,module,exports){
  1083. (function (Buffer){
  1084. 'use strict';
  1085. var util = require('util');
  1086. var Stream = require('stream');
  1087. var constants = require('./constants');
  1088. var Packer = require('./packer');
  1089. var PackerAsync = module.exports = function(opt) {
  1090. Stream.call(this);
  1091. var options = opt || {};
  1092. this._packer = new Packer(options);
  1093. this._deflate = this._packer.createDeflate();
  1094. this.readable = true;
  1095. };
  1096. util.inherits(PackerAsync, Stream);
  1097. PackerAsync.prototype.pack = function(data, width, height, gamma) {
  1098. // Signature
  1099. this.emit('data', new Buffer(constants.PNG_SIGNATURE));
  1100. this.emit('data', this._packer.packIHDR(width, height));
  1101. if (gamma) {
  1102. this.emit('data', this._packer.packGAMA(gamma));
  1103. }
  1104. var filteredData = this._packer.filterData(data, width, height);
  1105. // compress it
  1106. this._deflate.on('error', this.emit.bind(this, 'error'));
  1107. this._deflate.on('data', function(compressedData) {
  1108. this.emit('data', this._packer.packIDAT(compressedData));
  1109. }.bind(this));
  1110. this._deflate.on('end', function() {
  1111. this.emit('data', this._packer.packIEND());
  1112. this.emit('end');
  1113. }.bind(this));
  1114. this._deflate.end(filteredData);
  1115. };
  1116. }).call(this,require("buffer").Buffer)
  1117. },{"./constants":4,"./packer":14,"buffer":32,"stream":64,"util":69}],13:[function(require,module,exports){
  1118. (function (Buffer){
  1119. 'use strict';
  1120. var hasSyncZlib = true;
  1121. var zlib = require('zlib');
  1122. if (!zlib.deflateSync) {
  1123. hasSyncZlib = false;
  1124. }
  1125. var constants = require('./constants');
  1126. var Packer = require('./packer');
  1127. module.exports = function(metaData, opt) {
  1128. if (!hasSyncZlib) {
  1129. throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
  1130. }
  1131. var options = opt || {};
  1132. var packer = new Packer(options);
  1133. var chunks = [];
  1134. // Signature
  1135. chunks.push(new Buffer(constants.PNG_SIGNATURE));
  1136. // Header
  1137. chunks.push(packer.packIHDR(metaData.width, metaData.height));
  1138. if (metaData.gamma) {
  1139. chunks.push(packer.packGAMA(metaData.gamma));
  1140. }
  1141. var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
  1142. // compress it
  1143. var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
  1144. filteredData = null;
  1145. if (!compressedData || !compressedData.length) {
  1146. throw new Error('bad png - invalid compressed data response');
  1147. }
  1148. chunks.push(packer.packIDAT(compressedData));
  1149. // End
  1150. chunks.push(packer.packIEND());
  1151. return Buffer.concat(chunks);
  1152. };
  1153. }).call(this,require("buffer").Buffer)
  1154. },{"./constants":4,"./packer":14,"buffer":32,"zlib":30}],14:[function(require,module,exports){
  1155. (function (Buffer){
  1156. 'use strict';
  1157. var constants = require('./constants');
  1158. var CrcStream = require('./crc');
  1159. var bitPacker = require('./bitpacker');
  1160. var filter = require('./filter-pack');
  1161. var zlib = require('zlib');
  1162. var Packer = module.exports = function(options) {
  1163. this._options = options;
  1164. options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
  1165. options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
  1166. options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
  1167. options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
  1168. options.deflateFactory = options.deflateFactory || zlib.createDeflate;
  1169. options.bitDepth = options.bitDepth || 8;
  1170. // This is outputColorType
  1171. options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
  1172. options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
  1173. if ([
  1174. constants.COLORTYPE_GRAYSCALE,
  1175. constants.COLORTYPE_COLOR,
  1176. constants.COLORTYPE_COLOR_ALPHA,
  1177. constants.COLORTYPE_ALPHA
  1178. ].indexOf(options.colorType) === -1) {
  1179. throw new Error('option color type:' + options.colorType + ' is not supported at present');
  1180. }
  1181. if ([
  1182. constants.COLORTYPE_GRAYSCALE,
  1183. constants.COLORTYPE_COLOR,
  1184. constants.COLORTYPE_COLOR_ALPHA,
  1185. constants.COLORTYPE_ALPHA
  1186. ].indexOf(options.inputColorType) === -1) {
  1187. throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
  1188. }
  1189. if (options.bitDepth !== 8 && options.bitDepth !== 16) {
  1190. throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
  1191. }
  1192. };
  1193. Packer.prototype.getDeflateOptions = function() {
  1194. return {
  1195. chunkSize: this._options.deflateChunkSize,
  1196. level: this._options.deflateLevel,
  1197. strategy: this._options.deflateStrategy
  1198. };
  1199. };
  1200. Packer.prototype.createDeflate = function() {
  1201. return this._options.deflateFactory(this.getDeflateOptions());
  1202. };
  1203. Packer.prototype.filterData = function(data, width, height) {
  1204. // convert to correct format for filtering (e.g. right bpp and bit depth)
  1205. var packedData = bitPacker(data, width, height, this._options);
  1206. // filter pixel data
  1207. var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
  1208. var filteredData = filter(packedData, width, height, this._options, bpp);
  1209. return filteredData;
  1210. };
  1211. Packer.prototype._packChunk = function(type, data) {
  1212. var len = (data ? data.length : 0);
  1213. var buf = new Buffer(len + 12);
  1214. buf.writeUInt32BE(len, 0);
  1215. buf.writeUInt32BE(type, 4);
  1216. if (data) {
  1217. data.copy(buf, 8);
  1218. }
  1219. buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
  1220. return buf;
  1221. };
  1222. Packer.prototype.packGAMA = function(gamma) {
  1223. var buf = new Buffer(4);
  1224. buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
  1225. return this._packChunk(constants.TYPE_gAMA, buf);
  1226. };
  1227. Packer.prototype.packIHDR = function(width, height) {
  1228. var buf = new Buffer(13);
  1229. buf.writeUInt32BE(width, 0);
  1230. buf.writeUInt32BE(height, 4);
  1231. buf[8] = this._options.bitDepth; // Bit depth
  1232. buf[9] = this._options.colorType; // colorType
  1233. buf[10] = 0; // compression
  1234. buf[11] = 0; // filter
  1235. buf[12] = 0; // interlace
  1236. return this._packChunk(constants.TYPE_IHDR, buf);
  1237. };
  1238. Packer.prototype.packIDAT = function(data) {
  1239. return this._packChunk(constants.TYPE_IDAT, data);
  1240. };
  1241. Packer.prototype.packIEND = function() {
  1242. return this._packChunk(constants.TYPE_IEND, null);
  1243. };
  1244. }).call(this,require("buffer").Buffer)
  1245. },{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":32,"zlib":30}],15:[function(require,module,exports){
  1246. 'use strict';
  1247. module.exports = function paethPredictor(left, above, upLeft) {
  1248. var paeth = left + above - upLeft;
  1249. var pLeft = Math.abs(paeth - left);
  1250. var pAbove = Math.abs(paeth - above);
  1251. var pUpLeft = Math.abs(paeth - upLeft);
  1252. if (pLeft <= pAbove && pLeft <= pUpLeft) {
  1253. return left;
  1254. }
  1255. if (pAbove <= pUpLeft) {
  1256. return above;
  1257. }
  1258. return upLeft;
  1259. };
  1260. },{}],16:[function(require,module,exports){
  1261. 'use strict';
  1262. var util = require('util');
  1263. var zlib = require('zlib');
  1264. var ChunkStream = require('./chunkstream');
  1265. var FilterAsync = require('./filter-parse-async');
  1266. var Parser = require('./parser');
  1267. var bitmapper = require('./bitmapper');
  1268. var formatNormaliser = require('./format-normaliser');
  1269. var ParserAsync = module.exports = function(options) {
  1270. ChunkStream.call(this);
  1271. this._parser = new Parser(options, {
  1272. read: this.read.bind(this),
  1273. error: this._handleError.bind(this),
  1274. metadata: this._handleMetaData.bind(this),
  1275. gamma: this.emit.bind(this, 'gamma'),
  1276. palette: this._handlePalette.bind(this),
  1277. transColor: this._handleTransColor.bind(this),
  1278. finished: this._finished.bind(this),
  1279. inflateData: this._inflateData.bind(this),
  1280. simpleTransparency: this._simpleTransparency.bind(this),
  1281. headersFinished: this._headersFinished.bind(this)
  1282. });
  1283. this._options = options;
  1284. this.writable = true;
  1285. this._parser.start();
  1286. };
  1287. util.inherits(ParserAsync, ChunkStream);
  1288. ParserAsync.prototype._handleError = function(err) {
  1289. this.emit('error', err);
  1290. this.writable = false;
  1291. this.destroy();
  1292. if (this._inflate && this._inflate.destroy) {
  1293. this._inflate.destroy();
  1294. }
  1295. if (this._filter) {
  1296. this._filter.destroy();
  1297. // For backward compatibility with Node 7 and below.
  1298. // Suppress errors due to _inflate calling write() even after
  1299. // it's destroy()'ed.
  1300. this._filter.on('error', function() {});
  1301. }
  1302. this.errord = true;
  1303. };
  1304. ParserAsync.prototype._inflateData = function(data) {
  1305. if (!this._inflate) {
  1306. if (this._bitmapInfo.interlace) {
  1307. this._inflate = zlib.createInflate();
  1308. this._inflate.on('error', this.emit.bind(this, 'error'));
  1309. this._filter.on('complete', this._complete.bind(this));
  1310. this._inflate.pipe(this._filter);
  1311. }
  1312. else {
  1313. var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
  1314. var imageSize = rowSize * this._bitmapInfo.height;
  1315. var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
  1316. this._inflate = zlib.createInflate({ chunkSize: chunkSize });
  1317. var leftToInflate = imageSize;
  1318. var emitError = this.emit.bind(this, 'error');
  1319. this._inflate.on('error', function(err) {
  1320. if (!leftToInflate) {
  1321. return;
  1322. }
  1323. emitError(err);
  1324. });
  1325. this._filter.on('complete', this._complete.bind(this));
  1326. var filterWrite = this._filter.write.bind(this._filter);
  1327. this._inflate.on('data', function(chunk) {
  1328. if (!leftToInflate) {
  1329. return;
  1330. }
  1331. if (chunk.length > leftToInflate) {
  1332. chunk = chunk.slice(0, leftToInflate);
  1333. }
  1334. leftToInflate -= chunk.length;
  1335. filterWrite(chunk);
  1336. });
  1337. this._inflate.on('end', this._filter.end.bind(this._filter));
  1338. }
  1339. }
  1340. this._inflate.write(data);
  1341. };
  1342. ParserAsync.prototype._handleMetaData = function(metaData) {
  1343. this._metaData = metaData;
  1344. this._bitmapInfo = Object.create(metaData);
  1345. this._filter = new FilterAsync(this._bitmapInfo);
  1346. };
  1347. ParserAsync.prototype._handleTransColor = function(transColor) {
  1348. this._bitmapInfo.transColor = transColor;
  1349. };
  1350. ParserAsync.prototype._handlePalette = function(palette) {
  1351. this._bitmapInfo.palette = palette;
  1352. };
  1353. ParserAsync.prototype._simpleTransparency = function() {
  1354. this._metaData.alpha = true;
  1355. };
  1356. ParserAsync.prototype._headersFinished = function() {
  1357. // Up until this point, we don't know if we have a tRNS chunk (alpha)
  1358. // so we can't emit metadata any earlier
  1359. this.emit('metadata', this._metaData);
  1360. };
  1361. ParserAsync.prototype._finished = function() {
  1362. if (this.errord) {
  1363. return;
  1364. }
  1365. if (!this._inflate) {
  1366. this.emit('error', 'No Inflate block');
  1367. }
  1368. else {
  1369. // no more data to inflate
  1370. this._inflate.end();
  1371. }
  1372. this.destroySoon();
  1373. };
  1374. ParserAsync.prototype._complete = function(filteredData) {
  1375. if (this.errord) {
  1376. return;
  1377. }
  1378. try {
  1379. var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
  1380. var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
  1381. bitmapData = null;
  1382. }
  1383. catch (ex) {
  1384. this._handleError(ex);
  1385. return;
  1386. }
  1387. this.emit('parsed', normalisedBitmapData);
  1388. };
  1389. },{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":69,"zlib":30}],17:[function(require,module,exports){
  1390. (function (Buffer){
  1391. 'use strict';
  1392. var hasSyncZlib = true;
  1393. var zlib = require('zlib');
  1394. var inflateSync = require('./sync-inflate');
  1395. if (!zlib.deflateSync) {
  1396. hasSyncZlib = false;
  1397. }
  1398. var SyncReader = require('./sync-reader');
  1399. var FilterSync = require('./filter-parse-sync');
  1400. var Parser = require('./parser');
  1401. var bitmapper = require('./bitmapper');
  1402. var formatNormaliser = require('./format-normaliser');
  1403. module.exports = function(buffer, options) {
  1404. if (!hasSyncZlib) {
  1405. throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
  1406. }
  1407. var err;
  1408. function handleError(_err_) {
  1409. err = _err_;
  1410. }
  1411. var metaData;
  1412. function handleMetaData(_metaData_) {
  1413. metaData = _metaData_;
  1414. }
  1415. function handleTransColor(transColor) {
  1416. metaData.transColor = transColor;
  1417. }
  1418. function handlePalette(palette) {
  1419. metaData.palette = palette;
  1420. }
  1421. function handleSimpleTransparency() {
  1422. metaData.alpha = true;
  1423. }
  1424. var gamma;
  1425. function handleGamma(_gamma_) {
  1426. gamma = _gamma_;
  1427. }
  1428. var inflateDataList = [];
  1429. function handleInflateData(inflatedData) {
  1430. inflateDataList.push(inflatedData);
  1431. }
  1432. var reader = new SyncReader(buffer);
  1433. var parser = new Parser(options, {
  1434. read: reader.read.bind(reader),
  1435. error: handleError,
  1436. metadata: handleMetaData,
  1437. gamma: handleGamma,
  1438. palette: handlePalette,
  1439. transColor: handleTransColor,
  1440. inflateData: handleInflateData,
  1441. simpleTransparency: handleSimpleTransparency
  1442. });
  1443. parser.start();
  1444. reader.process();
  1445. if (err) {
  1446. throw err;
  1447. }
  1448. //join together the inflate datas
  1449. var inflateData = Buffer.concat(inflateDataList);
  1450. inflateDataList.length = 0;
  1451. var inflatedData;
  1452. if (metaData.interlace) {
  1453. inflatedData = zlib.inflateSync(inflateData);
  1454. }
  1455. else {
  1456. var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
  1457. var imageSize = rowSize * metaData.height;
  1458. inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
  1459. }
  1460. inflateData = null;
  1461. if (!inflatedData || !inflatedData.length) {
  1462. throw new Error('bad png - invalid inflate data response');
  1463. }
  1464. var unfilteredData = FilterSync.process(inflatedData, metaData);
  1465. inflateData = null;
  1466. var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
  1467. unfilteredData = null;
  1468. var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
  1469. metaData.data = normalisedBitmapData;
  1470. metaData.gamma = gamma || 0;
  1471. return metaData;
  1472. };
  1473. }).call(this,require("buffer").Buffer)
  1474. },{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":32,"zlib":30}],18:[function(require,module,exports){
  1475. (function (Buffer){
  1476. 'use strict';
  1477. var constants = require('./constants');
  1478. var CrcCalculator = require('./crc');
  1479. var Parser = module.exports = function(options, dependencies) {
  1480. this._options = options;
  1481. options.checkCRC = options.checkCRC !== false;
  1482. this._hasIHDR = false;
  1483. this._hasIEND = false;
  1484. this._emittedHeadersFinished = false;
  1485. // input flags/metadata
  1486. this._palette = [];
  1487. this._colorType = 0;
  1488. this._chunks = {};
  1489. this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
  1490. this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
  1491. this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
  1492. this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
  1493. this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
  1494. this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
  1495. this.read = dependencies.read;
  1496. this.error = dependencies.error;
  1497. this.metadata = dependencies.metadata;
  1498. this.gamma = dependencies.gamma;
  1499. this.transColor = dependencies.transColor;
  1500. this.palette = dependencies.palette;
  1501. this.parsed = dependencies.parsed;
  1502. this.inflateData = dependencies.inflateData;
  1503. this.finished = dependencies.finished;
  1504. this.simpleTransparency = dependencies.simpleTransparency;
  1505. this.headersFinished = dependencies.headersFinished || function() {};
  1506. };
  1507. Parser.prototype.start = function() {
  1508. this.read(constants.PNG_SIGNATURE.length,
  1509. this._parseSignature.bind(this)
  1510. );
  1511. };
  1512. Parser.prototype._parseSignature = function(data) {
  1513. var signature = constants.PNG_SIGNATURE;
  1514. for (var i = 0; i < signature.length; i++) {
  1515. if (data[i] !== signature[i]) {
  1516. this.error(new Error('Invalid file signature'));
  1517. return;
  1518. }
  1519. }
  1520. this.read(8, this._parseChunkBegin.bind(this));
  1521. };
  1522. Parser.prototype._parseChunkBegin = function(data) {
  1523. // chunk content length
  1524. var length = data.readUInt32BE(0);
  1525. // chunk type
  1526. var type = data.readUInt32BE(4);
  1527. var name = '';
  1528. for (var i = 4; i < 8; i++) {
  1529. name += String.fromCharCode(data[i]);
  1530. }
  1531. //console.log('chunk ', name, length);
  1532. // chunk flags
  1533. var ancillary = Boolean(data[4] & 0x20); // or critical
  1534. // priv = Boolean(data[5] & 0x20), // or public
  1535. // safeToCopy = Boolean(data[7] & 0x20); // or unsafe
  1536. if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
  1537. this.error(new Error('Expected IHDR on beggining'));
  1538. return;
  1539. }
  1540. this._crc = new CrcCalculator();
  1541. this._crc.write(new Buffer(name));
  1542. if (this._chunks[type]) {
  1543. return this._chunks[type](length);
  1544. }
  1545. if (!ancillary) {
  1546. this.error(new Error('Unsupported critical chunk type ' + name));
  1547. return;
  1548. }
  1549. this.read(length + 4, this._skipChunk.bind(this));
  1550. };
  1551. Parser.prototype._skipChunk = function(/*data*/) {
  1552. this.read(8, this._parseChunkBegin.bind(this));
  1553. };
  1554. Parser.prototype._handleChunkEnd = function() {
  1555. this.read(4, this._parseChunkEnd.bind(this));
  1556. };
  1557. Parser.prototype._parseChunkEnd = function(data) {
  1558. var fileCrc = data.readInt32BE(0);
  1559. var calcCrc = this._crc.crc32();
  1560. // check CRC
  1561. if (this._options.checkCRC && calcCrc !== fileCrc) {
  1562. this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
  1563. return;
  1564. }
  1565. if (!this._hasIEND) {
  1566. this.read(8, this._parseChunkBegin.bind(this));
  1567. }
  1568. };
  1569. Parser.prototype._handleIHDR = function(length) {
  1570. this.read(length, this._parseIHDR.bind(this));
  1571. };
  1572. Parser.prototype._parseIHDR = function(data) {
  1573. this._crc.write(data);
  1574. var width = data.readUInt32BE(0);
  1575. var height = data.readUInt32BE(4);
  1576. var depth = data[8];
  1577. var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
  1578. var compr = data[10];
  1579. var filter = data[11];
  1580. var interlace = data[12];
  1581. // console.log(' width', width, 'height', height,
  1582. // 'depth', depth, 'colorType', colorType,
  1583. // 'compr', compr, 'filter', filter, 'interlace', interlace
  1584. // );
  1585. if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
  1586. this.error(new Error('Unsupported bit depth ' + depth));
  1587. return;
  1588. }
  1589. if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
  1590. this.error(new Error('Unsupported color type'));
  1591. return;
  1592. }
  1593. if (compr !== 0) {
  1594. this.error(new Error('Unsupported compression method'));
  1595. return;
  1596. }
  1597. if (filter !== 0) {
  1598. this.error(new Error('Unsupported filter method'));
  1599. return;
  1600. }
  1601. if (interlace !== 0 && interlace !== 1) {
  1602. this.error(new Error('Unsupported interlace method'));
  1603. return;
  1604. }
  1605. this._colorType = colorType;
  1606. var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
  1607. this._hasIHDR = true;
  1608. this.metadata({
  1609. width: width,
  1610. height: height,
  1611. depth: depth,
  1612. interlace: Boolean(interlace),
  1613. palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
  1614. color: Boolean(colorType & constants.COLORTYPE_COLOR),
  1615. alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
  1616. bpp: bpp,
  1617. colorType: colorType
  1618. });
  1619. this._handleChunkEnd();
  1620. };
  1621. Parser.prototype._handlePLTE = function(length) {
  1622. this.read(length, this._parsePLTE.bind(this));
  1623. };
  1624. Parser.prototype._parsePLTE = function(data) {
  1625. this._crc.write(data);
  1626. var entries = Math.floor(data.length / 3);
  1627. // console.log('Palette:', entries);
  1628. for (var i = 0; i < entries; i++) {
  1629. this._palette.push([
  1630. data[i * 3],
  1631. data[i * 3 + 1],
  1632. data[i * 3 + 2],
  1633. 0xff
  1634. ]);
  1635. }
  1636. this.palette(this._palette);
  1637. this._handleChunkEnd();
  1638. };
  1639. Parser.prototype._handleTRNS = function(length) {
  1640. this.simpleTransparency();
  1641. this.read(length, this._parseTRNS.bind(this));
  1642. };
  1643. Parser.prototype._parseTRNS = function(data) {
  1644. this._crc.write(data);
  1645. // palette
  1646. if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
  1647. if (this._palette.length === 0) {
  1648. this.error(new Error('Transparency chunk must be after palette'));
  1649. return;
  1650. }
  1651. if (data.length > this._palette.length) {
  1652. this.error(new Error('More transparent colors than palette size'));
  1653. return;
  1654. }
  1655. for (var i = 0; i < data.length; i++) {
  1656. this._palette[i][3] = data[i];
  1657. }
  1658. this.palette(this._palette);
  1659. }
  1660. // for colorType 0 (grayscale) and 2 (rgb)
  1661. // there might be one gray/color defined as transparent
  1662. if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
  1663. // grey, 2 bytes
  1664. this.transColor([data.readUInt16BE(0)]);
  1665. }
  1666. if (this._colorType === constants.COLORTYPE_COLOR) {
  1667. this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
  1668. }
  1669. this._handleChunkEnd();
  1670. };
  1671. Parser.prototype._handleGAMA = function(length) {
  1672. this.read(length, this._parseGAMA.bind(this));
  1673. };
  1674. Parser.prototype._parseGAMA = function(data) {
  1675. this._crc.write(data);
  1676. this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
  1677. this._handleChunkEnd();
  1678. };
  1679. Parser.prototype._handleIDAT = function(length) {
  1680. if (!this._emittedHeadersFinished) {
  1681. this._emittedHeadersFinished = true;
  1682. this.headersFinished();
  1683. }
  1684. this.read(-length, this._parseIDAT.bind(this, length));
  1685. };
  1686. Parser.prototype._parseIDAT = function(length, data) {
  1687. this._crc.write(data);
  1688. if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
  1689. throw new Error('Expected palette not found');
  1690. }
  1691. this.inflateData(data);
  1692. var leftOverLength = length - data.length;
  1693. if (leftOverLength > 0) {
  1694. this._handleIDAT(leftOverLength);
  1695. }
  1696. else {
  1697. this._handleChunkEnd();
  1698. }
  1699. };
  1700. Parser.prototype._handleIEND = function(length) {
  1701. this.read(length, this._parseIEND.bind(this));
  1702. };
  1703. Parser.prototype._parseIEND = function(data) {
  1704. this._crc.write(data);
  1705. this._hasIEND = true;
  1706. this._handleChunkEnd();
  1707. if (this.finished) {
  1708. this.finished();
  1709. }
  1710. };
  1711. }).call(this,require("buffer").Buffer)
  1712. },{"./constants":4,"./crc":5,"buffer":32}],19:[function(require,module,exports){
  1713. 'use strict';
  1714. var parse = require('./parser-sync');
  1715. var pack = require('./packer-sync');
  1716. exports.read = function(buffer, options) {
  1717. return parse(buffer, options || {});
  1718. };
  1719. exports.write = function(png, options) {
  1720. return pack(png, options);
  1721. };
  1722. },{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){
  1723. (function (process,Buffer){
  1724. 'use strict';
  1725. var util = require('util');
  1726. var Stream = require('stream');
  1727. var Parser = require('./parser-async');
  1728. var Packer = require('./packer-async');
  1729. var PNGSync = require('./png-sync');
  1730. var PNG = exports.PNG = function(options) {
  1731. Stream.call(this);
  1732. options = options || {}; // eslint-disable-line no-param-reassign
  1733. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  1734. this.width = options.width | 0;
  1735. this.height = options.height | 0;
  1736. this.data = this.width > 0 && this.height > 0 ?
  1737. new Buffer(4 * this.width * this.height) : null;
  1738. if (options.fill && this.data) {
  1739. this.data.fill(0);
  1740. }
  1741. this.gamma = 0;
  1742. this.readable = this.writable = true;
  1743. this._parser = new Parser(options);
  1744. this._parser.on('error', this.emit.bind(this, 'error'));
  1745. this._parser.on('close', this._handleClose.bind(this));
  1746. this._parser.on('metadata', this._metadata.bind(this));
  1747. this._parser.on('gamma', this._gamma.bind(this));
  1748. this._parser.on('parsed', function(data) {
  1749. this.data = data;
  1750. this.emit('parsed', data);
  1751. }.bind(this));
  1752. this._packer = new Packer(options);
  1753. this._packer.on('data', this.emit.bind(this, 'data'));
  1754. this._packer.on('end', this.emit.bind(this, 'end'));
  1755. this._parser.on('close', this._handleClose.bind(this));
  1756. this._packer.on('error', this.emit.bind(this, 'error'));
  1757. };
  1758. util.inherits(PNG, Stream);
  1759. PNG.sync = PNGSync;
  1760. PNG.prototype.pack = function() {
  1761. if (!this.data || !this.data.length) {
  1762. this.emit('error', 'No data provided');
  1763. return this;
  1764. }
  1765. process.nextTick(function() {
  1766. this._packer.pack(this.data, this.width, this.height, this.gamma);
  1767. }.bind(this));
  1768. return this;
  1769. };
  1770. PNG.prototype.parse = function(data, callback) {
  1771. if (callback) {
  1772. var onParsed, onError;
  1773. onParsed = function(parsedData) {
  1774. this.removeListener('error', onError);
  1775. this.data = parsedData;
  1776. callback(null, this);
  1777. }.bind(this);
  1778. onError = function(err) {
  1779. this.removeListener('parsed', onParsed);
  1780. callback(err, null);
  1781. }.bind(this);
  1782. this.once('parsed', onParsed);
  1783. this.once('error', onError);
  1784. }
  1785. this.end(data);
  1786. return this;
  1787. };
  1788. PNG.prototype.write = function(data) {
  1789. this._parser.write(data);
  1790. return true;
  1791. };
  1792. PNG.prototype.end = function(data) {
  1793. this._parser.end(data);
  1794. };
  1795. PNG.prototype._metadata = function(metadata) {
  1796. this.width = metadata.width;
  1797. this.height = metadata.height;
  1798. this.emit('metadata', metadata);
  1799. };
  1800. PNG.prototype._gamma = function(gamma) {
  1801. this.gamma = gamma;
  1802. };
  1803. PNG.prototype._handleClose = function() {
  1804. if (!this._parser.writable && !this._packer.readable) {
  1805. this.emit('close');
  1806. }
  1807. };
  1808. PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
  1809. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  1810. /* eslint-disable no-param-reassign */
  1811. srcX |= 0;
  1812. srcY |= 0;
  1813. width |= 0;
  1814. height |= 0;
  1815. deltaX |= 0;
  1816. deltaY |= 0;
  1817. /* eslint-enable no-param-reassign */
  1818. if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
  1819. throw new Error('bitblt reading outside image');
  1820. }
  1821. if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
  1822. throw new Error('bitblt writing outside image');
  1823. }
  1824. for (var y = 0; y < height; y++) {
  1825. src.data.copy(dst.data,
  1826. ((deltaY + y) * dst.width + deltaX) << 2,
  1827. ((srcY + y) * src.width + srcX) << 2,
  1828. ((srcY + y) * src.width + srcX + width) << 2
  1829. );
  1830. }
  1831. };
  1832. PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
  1833. PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
  1834. return this;
  1835. };
  1836. PNG.adjustGamma = function(src) {
  1837. if (src.gamma) {
  1838. for (var y = 0; y < src.height; y++) {
  1839. for (var x = 0; x < src.width; x++) {
  1840. var idx = (src.width * y + x) << 2;
  1841. for (var i = 0; i < 3; i++) {
  1842. var sample = src.data[idx + i] / 255;
  1843. sample = Math.pow(sample, 1 / 2.2 / src.gamma);
  1844. src.data[idx + i] = Math.round(sample * 255);
  1845. }
  1846. }
  1847. }
  1848. src.gamma = 0;
  1849. }
  1850. };
  1851. PNG.prototype.adjustGamma = function() {
  1852. PNG.adjustGamma(this);
  1853. };
  1854. }).call(this,require('_process'),require("buffer").Buffer)
  1855. },{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":51,"buffer":32,"stream":64,"util":69}],21:[function(require,module,exports){
  1856. (function (process,Buffer){
  1857. 'use strict';
  1858. var assert = require('assert').ok;
  1859. var zlib = require('zlib');
  1860. var util = require('util');
  1861. var kMaxLength = require('buffer').kMaxLength;
  1862. function Inflate(opts) {
  1863. if (!(this instanceof Inflate)) {
  1864. return new Inflate(opts);
  1865. }
  1866. if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
  1867. opts.chunkSize = zlib.Z_MIN_CHUNK;
  1868. }
  1869. zlib.Inflate.call(this, opts);
  1870. // Node 8 --> 9 compatibility check
  1871. this._offset = this._offset === undefined ? this._outOffset : this._offset;
  1872. this._buffer = this._buffer || this._outBuffer;
  1873. if (opts && opts.maxLength != null) {
  1874. this._maxLength = opts.maxLength;
  1875. }
  1876. }
  1877. function createInflate(opts) {
  1878. return new Inflate(opts);
  1879. }
  1880. function _close(engine, callback) {
  1881. if (callback) {
  1882. process.nextTick(callback);
  1883. }
  1884. // Caller may invoke .close after a zlib error (which will null _handle).
  1885. if (!engine._handle) {
  1886. return;
  1887. }
  1888. engine._handle.close();
  1889. engine._handle = null;
  1890. }
  1891. Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
  1892. if (typeof asyncCb === 'function') {
  1893. return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
  1894. }
  1895. var self = this;
  1896. var availInBefore = chunk && chunk.length;
  1897. var availOutBefore = this._chunkSize - this._offset;
  1898. var leftToInflate = this._maxLength;
  1899. var inOff = 0;
  1900. var buffers = [];
  1901. var nread = 0;
  1902. var error;
  1903. this.on('error', function(err) {
  1904. error = err;
  1905. });
  1906. function handleChunk(availInAfter, availOutAfter) {
  1907. if (self._hadError) {
  1908. return;
  1909. }
  1910. var have = availOutBefore - availOutAfter;
  1911. assert(have >= 0, 'have should not go down');
  1912. if (have > 0) {
  1913. var out = self._buffer.slice(self._offset, self._offset + have);
  1914. self._offset += have;
  1915. if (out.length > leftToInflate) {
  1916. out = out.slice(0, leftToInflate);
  1917. }
  1918. buffers.push(out);
  1919. nread += out.length;
  1920. leftToInflate -= out.length;
  1921. if (leftToInflate === 0) {
  1922. return false;
  1923. }
  1924. }
  1925. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  1926. availOutBefore = self._chunkSize;
  1927. self._offset = 0;
  1928. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  1929. }
  1930. if (availOutAfter === 0) {
  1931. inOff += (availInBefore - availInAfter);
  1932. availInBefore = availInAfter;
  1933. return true;
  1934. }
  1935. return false;
  1936. }
  1937. assert(this._handle, 'zlib binding closed');
  1938. do {
  1939. var res = this._handle.writeSync(flushFlag,
  1940. chunk, // in
  1941. inOff, // in_off
  1942. availInBefore, // in_len
  1943. this._buffer, // out
  1944. this._offset, //out_off
  1945. availOutBefore); // out_len
  1946. // Node 8 --> 9 compatibility check
  1947. res = res || this._writeState;
  1948. } while (!this._hadError && handleChunk(res[0], res[1]));
  1949. if (this._hadError) {
  1950. throw error;
  1951. }
  1952. if (nread >= kMaxLength) {
  1953. _close(this);
  1954. throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
  1955. }
  1956. var buf = Buffer.concat(buffers, nread);
  1957. _close(this);
  1958. return buf;
  1959. };
  1960. util.inherits(Inflate, zlib.Inflate);
  1961. function zlibBufferSync(engine, buffer) {
  1962. if (typeof buffer === 'string') {
  1963. buffer = Buffer.from(buffer);
  1964. }
  1965. if (!(buffer instanceof Buffer)) {
  1966. throw new TypeError('Not a string or buffer');
  1967. }
  1968. var flushFlag = engine._finishFlushFlag;
  1969. if (flushFlag == null) {
  1970. flushFlag = zlib.Z_FINISH;
  1971. }
  1972. return engine._processChunk(buffer, flushFlag);
  1973. }
  1974. function inflateSync(buffer, opts) {
  1975. return zlibBufferSync(new Inflate(opts), buffer);
  1976. }
  1977. module.exports = exports = inflateSync;
  1978. exports.Inflate = Inflate;
  1979. exports.createInflate = createInflate;
  1980. exports.inflateSync = inflateSync;
  1981. }).call(this,require('_process'),require("buffer").Buffer)
  1982. },{"_process":51,"assert":23,"buffer":32,"util":69,"zlib":30}],22:[function(require,module,exports){
  1983. 'use strict';
  1984. var SyncReader = module.exports = function(buffer) {
  1985. this._buffer = buffer;
  1986. this._reads = [];
  1987. };
  1988. SyncReader.prototype.read = function(length, callback) {
  1989. this._reads.push({
  1990. length: Math.abs(length), // if length < 0 then at most this length
  1991. allowLess: length < 0,
  1992. func: callback
  1993. });
  1994. };
  1995. SyncReader.prototype.process = function() {
  1996. // as long as there is any data and read requests
  1997. while (this._reads.length > 0 && this._buffer.length) {
  1998. var read = this._reads[0];
  1999. if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
  2000. // ok there is any data so that we can satisfy this request
  2001. this._reads.shift(); // == read
  2002. var buf = this._buffer;
  2003. this._buffer = buf.slice(read.length);
  2004. read.func.call(this, buf.slice(0, read.length));
  2005. }
  2006. else {
  2007. break;
  2008. }
  2009. }
  2010. if (this._reads.length > 0) {
  2011. return new Error('There are some read requests waitng on finished stream');
  2012. }
  2013. if (this._buffer.length > 0) {
  2014. return new Error('unrecognised content at end of stream');
  2015. }
  2016. };
  2017. },{}],23:[function(require,module,exports){
  2018. (function (global){
  2019. 'use strict';
  2020. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  2021. // original notice:
  2022. /*!
  2023. * The buffer module from node.js, for the browser.
  2024. *
  2025. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2026. * @license MIT
  2027. */
  2028. function compare(a, b) {
  2029. if (a === b) {
  2030. return 0;
  2031. }
  2032. var x = a.length;
  2033. var y = b.length;
  2034. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2035. if (a[i] !== b[i]) {
  2036. x = a[i];
  2037. y = b[i];
  2038. break;
  2039. }
  2040. }
  2041. if (x < y) {
  2042. return -1;
  2043. }
  2044. if (y < x) {
  2045. return 1;
  2046. }
  2047. return 0;
  2048. }
  2049. function isBuffer(b) {
  2050. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  2051. return global.Buffer.isBuffer(b);
  2052. }
  2053. return !!(b != null && b._isBuffer);
  2054. }
  2055. // based on node assert, original notice:
  2056. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  2057. //
  2058. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  2059. //
  2060. // Originally from narwhal.js (http://narwhaljs.org)
  2061. // Copyright (c) 2009 Thomas Robinson <280north.com>
  2062. //
  2063. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2064. // of this software and associated documentation files (the 'Software'), to
  2065. // deal in the Software without restriction, including without limitation the
  2066. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  2067. // sell copies of the Software, and to permit persons to whom the Software is
  2068. // furnished to do so, subject to the following conditions:
  2069. //
  2070. // The above copyright notice and this permission notice shall be included in
  2071. // all copies or substantial portions of the Software.
  2072. //
  2073. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2074. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2075. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2076. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  2077. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  2078. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2079. var util = require('util/');
  2080. var hasOwn = Object.prototype.hasOwnProperty;
  2081. var pSlice = Array.prototype.slice;
  2082. var functionsHaveNames = (function () {
  2083. return function foo() {}.name === 'foo';
  2084. }());
  2085. function pToString (obj) {
  2086. return Object.prototype.toString.call(obj);
  2087. }
  2088. function isView(arrbuf) {
  2089. if (isBuffer(arrbuf)) {
  2090. return false;
  2091. }
  2092. if (typeof global.ArrayBuffer !== 'function') {
  2093. return false;
  2094. }
  2095. if (typeof ArrayBuffer.isView === 'function') {
  2096. return ArrayBuffer.isView(arrbuf);
  2097. }
  2098. if (!arrbuf) {
  2099. return false;
  2100. }
  2101. if (arrbuf instanceof DataView) {
  2102. return true;
  2103. }
  2104. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  2105. return true;
  2106. }
  2107. return false;
  2108. }
  2109. // 1. The assert module provides functions that throw
  2110. // AssertionError's when particular conditions are not met. The
  2111. // assert module must conform to the following interface.
  2112. var assert = module.exports = ok;
  2113. // 2. The AssertionError is defined in assert.
  2114. // new assert.AssertionError({ message: message,
  2115. // actual: actual,
  2116. // expected: expected })
  2117. var regex = /\s*function\s+([^\(\s]*)\s*/;
  2118. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  2119. function getName(func) {
  2120. if (!util.isFunction(func)) {
  2121. return;
  2122. }
  2123. if (functionsHaveNames) {
  2124. return func.name;
  2125. }
  2126. var str = func.toString();
  2127. var match = str.match(regex);
  2128. return match && match[1];
  2129. }
  2130. assert.AssertionError = function AssertionError(options) {
  2131. this.name = 'AssertionError';
  2132. this.actual = options.actual;
  2133. this.expected = options.expected;
  2134. this.operator = options.operator;
  2135. if (options.message) {
  2136. this.message = options.message;
  2137. this.generatedMessage = false;
  2138. } else {
  2139. this.message = getMessage(this);
  2140. this.generatedMessage = true;
  2141. }
  2142. var stackStartFunction = options.stackStartFunction || fail;
  2143. if (Error.captureStackTrace) {
  2144. Error.captureStackTrace(this, stackStartFunction);
  2145. } else {
  2146. // non v8 browsers so we can have a stacktrace
  2147. var err = new Error();
  2148. if (err.stack) {
  2149. var out = err.stack;
  2150. // try to strip useless frames
  2151. var fn_name = getName(stackStartFunction);
  2152. var idx = out.indexOf('\n' + fn_name);
  2153. if (idx >= 0) {
  2154. // once we have located the function frame
  2155. // we need to strip out everything before it (and its line)
  2156. var next_line = out.indexOf('\n', idx + 1);
  2157. out = out.substring(next_line + 1);
  2158. }
  2159. this.stack = out;
  2160. }
  2161. }
  2162. };
  2163. // assert.AssertionError instanceof Error
  2164. util.inherits(assert.AssertionError, Error);
  2165. function truncate(s, n) {
  2166. if (typeof s === 'string') {
  2167. return s.length < n ? s : s.slice(0, n);
  2168. } else {
  2169. return s;
  2170. }
  2171. }
  2172. function inspect(something) {
  2173. if (functionsHaveNames || !util.isFunction(something)) {
  2174. return util.inspect(something);
  2175. }
  2176. var rawname = getName(something);
  2177. var name = rawname ? ': ' + rawname : '';
  2178. return '[Function' + name + ']';
  2179. }
  2180. function getMessage(self) {
  2181. return truncate(inspect(self.actual), 128) + ' ' +
  2182. self.operator + ' ' +
  2183. truncate(inspect(self.expected), 128);
  2184. }
  2185. // At present only the three keys mentioned above are used and
  2186. // understood by the spec. Implementations or sub modules can pass
  2187. // other keys to the AssertionError's constructor - they will be
  2188. // ignored.
  2189. // 3. All of the following functions must throw an AssertionError
  2190. // when a corresponding condition is not met, with a message that
  2191. // may be undefined if not provided. All assertion methods provide
  2192. // both the actual and expected values to the assertion error for
  2193. // display purposes.
  2194. function fail(actual, expected, message, operator, stackStartFunction) {
  2195. throw new assert.AssertionError({
  2196. message: message,
  2197. actual: actual,
  2198. expected: expected,
  2199. operator: operator,
  2200. stackStartFunction: stackStartFunction
  2201. });
  2202. }
  2203. // EXTENSION! allows for well behaved errors defined elsewhere.
  2204. assert.fail = fail;
  2205. // 4. Pure assertion tests whether a value is truthy, as determined
  2206. // by !!guard.
  2207. // assert.ok(guard, message_opt);
  2208. // This statement is equivalent to assert.equal(true, !!guard,
  2209. // message_opt);. To test strictly for the value true, use
  2210. // assert.strictEqual(true, guard, message_opt);.
  2211. function ok(value, message) {
  2212. if (!value) fail(value, true, message, '==', assert.ok);
  2213. }
  2214. assert.ok = ok;
  2215. // 5. The equality assertion tests shallow, coercive equality with
  2216. // ==.
  2217. // assert.equal(actual, expected, message_opt);
  2218. assert.equal = function equal(actual, expected, message) {
  2219. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  2220. };
  2221. // 6. The non-equality assertion tests for whether two objects are not equal
  2222. // with != assert.notEqual(actual, expected, message_opt);
  2223. assert.notEqual = function notEqual(actual, expected, message) {
  2224. if (actual == expected) {
  2225. fail(actual, expected, message, '!=', assert.notEqual);
  2226. }
  2227. };
  2228. // 7. The equivalence assertion tests a deep equality relation.
  2229. // assert.deepEqual(actual, expected, message_opt);
  2230. assert.deepEqual = function deepEqual(actual, expected, message) {
  2231. if (!_deepEqual(actual, expected, false)) {
  2232. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  2233. }
  2234. };
  2235. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  2236. if (!_deepEqual(actual, expected, true)) {
  2237. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  2238. }
  2239. };
  2240. function _deepEqual(actual, expected, strict, memos) {
  2241. // 7.1. All identical values are equivalent, as determined by ===.
  2242. if (actual === expected) {
  2243. return true;
  2244. } else if (isBuffer(actual) && isBuffer(expected)) {
  2245. return compare(actual, expected) === 0;
  2246. // 7.2. If the expected value is a Date object, the actual value is
  2247. // equivalent if it is also a Date object that refers to the same time.
  2248. } else if (util.isDate(actual) && util.isDate(expected)) {
  2249. return actual.getTime() === expected.getTime();
  2250. // 7.3 If the expected value is a RegExp object, the actual value is
  2251. // equivalent if it is also a RegExp object with the same source and
  2252. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  2253. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  2254. return actual.source === expected.source &&
  2255. actual.global === expected.global &&
  2256. actual.multiline === expected.multiline &&
  2257. actual.lastIndex === expected.lastIndex &&
  2258. actual.ignoreCase === expected.ignoreCase;
  2259. // 7.4. Other pairs that do not both pass typeof value == 'object',
  2260. // equivalence is determined by ==.
  2261. } else if ((actual === null || typeof actual !== 'object') &&
  2262. (expected === null || typeof expected !== 'object')) {
  2263. return strict ? actual === expected : actual == expected;
  2264. // If both values are instances of typed arrays, wrap their underlying
  2265. // ArrayBuffers in a Buffer each to increase performance
  2266. // This optimization requires the arrays to have the same type as checked by
  2267. // Object.prototype.toString (aka pToString). Never perform binary
  2268. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  2269. // bit patterns are not identical.
  2270. } else if (isView(actual) && isView(expected) &&
  2271. pToString(actual) === pToString(expected) &&
  2272. !(actual instanceof Float32Array ||
  2273. actual instanceof Float64Array)) {
  2274. return compare(new Uint8Array(actual.buffer),
  2275. new Uint8Array(expected.buffer)) === 0;
  2276. // 7.5 For all other Object pairs, including Array objects, equivalence is
  2277. // determined by having the same number of owned properties (as verified
  2278. // with Object.prototype.hasOwnProperty.call), the same set of keys
  2279. // (although not necessarily the same order), equivalent values for every
  2280. // corresponding key, and an identical 'prototype' property. Note: this
  2281. // accounts for both named and indexed properties on Arrays.
  2282. } else if (isBuffer(actual) !== isBuffer(expected)) {
  2283. return false;
  2284. } else {
  2285. memos = memos || {actual: [], expected: []};
  2286. var actualIndex = memos.actual.indexOf(actual);
  2287. if (actualIndex !== -1) {
  2288. if (actualIndex === memos.expected.indexOf(expected)) {
  2289. return true;
  2290. }
  2291. }
  2292. memos.actual.push(actual);
  2293. memos.expected.push(expected);
  2294. return objEquiv(actual, expected, strict, memos);
  2295. }
  2296. }
  2297. function isArguments(object) {
  2298. return Object.prototype.toString.call(object) == '[object Arguments]';
  2299. }
  2300. function objEquiv(a, b, strict, actualVisitedObjects) {
  2301. if (a === null || a === undefined || b === null || b === undefined)
  2302. return false;
  2303. // if one is a primitive, the other must be same
  2304. if (util.isPrimitive(a) || util.isPrimitive(b))
  2305. return a === b;
  2306. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  2307. return false;
  2308. var aIsArgs = isArguments(a);
  2309. var bIsArgs = isArguments(b);
  2310. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  2311. return false;
  2312. if (aIsArgs) {
  2313. a = pSlice.call(a);
  2314. b = pSlice.call(b);
  2315. return _deepEqual(a, b, strict);
  2316. }
  2317. var ka = objectKeys(a);
  2318. var kb = objectKeys(b);
  2319. var key, i;
  2320. // having the same number of owned properties (keys incorporates
  2321. // hasOwnProperty)
  2322. if (ka.length !== kb.length)
  2323. return false;
  2324. //the same set of keys (although not necessarily the same order),
  2325. ka.sort();
  2326. kb.sort();
  2327. //~~~cheap key test
  2328. for (i = ka.length - 1; i >= 0; i--) {
  2329. if (ka[i] !== kb[i])
  2330. return false;
  2331. }
  2332. //equivalent values for every corresponding key, and
  2333. //~~~possibly expensive deep test
  2334. for (i = ka.length - 1; i >= 0; i--) {
  2335. key = ka[i];
  2336. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  2337. return false;
  2338. }
  2339. return true;
  2340. }
  2341. // 8. The non-equivalence assertion tests for any deep inequality.
  2342. // assert.notDeepEqual(actual, expected, message_opt);
  2343. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  2344. if (_deepEqual(actual, expected, false)) {
  2345. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  2346. }
  2347. };
  2348. assert.notDeepStrictEqual = notDeepStrictEqual;
  2349. function notDeepStrictEqual(actual, expected, message) {
  2350. if (_deepEqual(actual, expected, true)) {
  2351. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  2352. }
  2353. }
  2354. // 9. The strict equality assertion tests strict equality, as determined by ===.
  2355. // assert.strictEqual(actual, expected, message_opt);
  2356. assert.strictEqual = function strictEqual(actual, expected, message) {
  2357. if (actual !== expected) {
  2358. fail(actual, expected, message, '===', assert.strictEqual);
  2359. }
  2360. };
  2361. // 10. The strict non-equality assertion tests for strict inequality, as
  2362. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  2363. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  2364. if (actual === expected) {
  2365. fail(actual, expected, message, '!==', assert.notStrictEqual);
  2366. }
  2367. };
  2368. function expectedException(actual, expected) {
  2369. if (!actual || !expected) {
  2370. return false;
  2371. }
  2372. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  2373. return expected.test(actual);
  2374. }
  2375. try {
  2376. if (actual instanceof expected) {
  2377. return true;
  2378. }
  2379. } catch (e) {
  2380. // Ignore. The instanceof check doesn't work for arrow functions.
  2381. }
  2382. if (Error.isPrototypeOf(expected)) {
  2383. return false;
  2384. }
  2385. return expected.call({}, actual) === true;
  2386. }
  2387. function _tryBlock(block) {
  2388. var error;
  2389. try {
  2390. block();
  2391. } catch (e) {
  2392. error = e;
  2393. }
  2394. return error;
  2395. }
  2396. function _throws(shouldThrow, block, expected, message) {
  2397. var actual;
  2398. if (typeof block !== 'function') {
  2399. throw new TypeError('"block" argument must be a function');
  2400. }
  2401. if (typeof expected === 'string') {
  2402. message = expected;
  2403. expected = null;
  2404. }
  2405. actual = _tryBlock(block);
  2406. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  2407. (message ? ' ' + message : '.');
  2408. if (shouldThrow && !actual) {
  2409. fail(actual, expected, 'Missing expected exception' + message);
  2410. }
  2411. var userProvidedMessage = typeof message === 'string';
  2412. var isUnwantedException = !shouldThrow && util.isError(actual);
  2413. var isUnexpectedException = !shouldThrow && actual && !expected;
  2414. if ((isUnwantedException &&
  2415. userProvidedMessage &&
  2416. expectedException(actual, expected)) ||
  2417. isUnexpectedException) {
  2418. fail(actual, expected, 'Got unwanted exception' + message);
  2419. }
  2420. if ((shouldThrow && actual && expected &&
  2421. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  2422. throw actual;
  2423. }
  2424. }
  2425. // 11. Expected to throw an error:
  2426. // assert.throws(block, Error_opt, message_opt);
  2427. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  2428. _throws(true, block, error, message);
  2429. };
  2430. // EXTENSION! This is annoying to write outside this module.
  2431. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  2432. _throws(false, block, error, message);
  2433. };
  2434. assert.ifError = function(err) { if (err) throw err; };
  2435. var objectKeys = Object.keys || function (obj) {
  2436. var keys = [];
  2437. for (var key in obj) {
  2438. if (hasOwn.call(obj, key)) keys.push(key);
  2439. }
  2440. return keys;
  2441. };
  2442. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2443. },{"util/":26}],24:[function(require,module,exports){
  2444. if (typeof Object.create === 'function') {
  2445. // implementation from standard node.js 'util' module
  2446. module.exports = function inherits(ctor, superCtor) {
  2447. ctor.super_ = superCtor
  2448. ctor.prototype = Object.create(superCtor.prototype, {
  2449. constructor: {
  2450. value: ctor,
  2451. enumerable: false,
  2452. writable: true,
  2453. configurable: true
  2454. }
  2455. });
  2456. };
  2457. } else {
  2458. // old school shim for old browsers
  2459. module.exports = function inherits(ctor, superCtor) {
  2460. ctor.super_ = superCtor
  2461. var TempCtor = function () {}
  2462. TempCtor.prototype = superCtor.prototype
  2463. ctor.prototype = new TempCtor()
  2464. ctor.prototype.constructor = ctor
  2465. }
  2466. }
  2467. },{}],25:[function(require,module,exports){
  2468. module.exports = function isBuffer(arg) {
  2469. return arg && typeof arg === 'object'
  2470. && typeof arg.copy === 'function'
  2471. && typeof arg.fill === 'function'
  2472. && typeof arg.readUInt8 === 'function';
  2473. }
  2474. },{}],26:[function(require,module,exports){
  2475. (function (process,global){
  2476. // Copyright Joyent, Inc. and other Node contributors.
  2477. //
  2478. // Permission is hereby granted, free of charge, to any person obtaining a
  2479. // copy of this software and associated documentation files (the
  2480. // "Software"), to deal in the Software without restriction, including
  2481. // without limitation the rights to use, copy, modify, merge, publish,
  2482. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2483. // persons to whom the Software is furnished to do so, subject to the
  2484. // following conditions:
  2485. //
  2486. // The above copyright notice and this permission notice shall be included
  2487. // in all copies or substantial portions of the Software.
  2488. //
  2489. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2490. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2491. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2492. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2493. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2494. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2495. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2496. var formatRegExp = /%[sdj%]/g;
  2497. exports.format = function(f) {
  2498. if (!isString(f)) {
  2499. var objects = [];
  2500. for (var i = 0; i < arguments.length; i++) {
  2501. objects.push(inspect(arguments[i]));
  2502. }
  2503. return objects.join(' ');
  2504. }
  2505. var i = 1;
  2506. var args = arguments;
  2507. var len = args.length;
  2508. var str = String(f).replace(formatRegExp, function(x) {
  2509. if (x === '%%') return '%';
  2510. if (i >= len) return x;
  2511. switch (x) {
  2512. case '%s': return String(args[i++]);
  2513. case '%d': return Number(args[i++]);
  2514. case '%j':
  2515. try {
  2516. return JSON.stringify(args[i++]);
  2517. } catch (_) {
  2518. return '[Circular]';
  2519. }
  2520. default:
  2521. return x;
  2522. }
  2523. });
  2524. for (var x = args[i]; i < len; x = args[++i]) {
  2525. if (isNull(x) || !isObject(x)) {
  2526. str += ' ' + x;
  2527. } else {
  2528. str += ' ' + inspect(x);
  2529. }
  2530. }
  2531. return str;
  2532. };
  2533. // Mark that a method should not be used.
  2534. // Returns a modified function which warns once by default.
  2535. // If --no-deprecation is set, then it is a no-op.
  2536. exports.deprecate = function(fn, msg) {
  2537. // Allow for deprecating things in the process of starting up.
  2538. if (isUndefined(global.process)) {
  2539. return function() {
  2540. return exports.deprecate(fn, msg).apply(this, arguments);
  2541. };
  2542. }
  2543. if (process.noDeprecation === true) {
  2544. return fn;
  2545. }
  2546. var warned = false;
  2547. function deprecated() {
  2548. if (!warned) {
  2549. if (process.throwDeprecation) {
  2550. throw new Error(msg);
  2551. } else if (process.traceDeprecation) {
  2552. console.trace(msg);
  2553. } else {
  2554. console.error(msg);
  2555. }
  2556. warned = true;
  2557. }
  2558. return fn.apply(this, arguments);
  2559. }
  2560. return deprecated;
  2561. };
  2562. var debugs = {};
  2563. var debugEnviron;
  2564. exports.debuglog = function(set) {
  2565. if (isUndefined(debugEnviron))
  2566. debugEnviron = process.env.NODE_DEBUG || '';
  2567. set = set.toUpperCase();
  2568. if (!debugs[set]) {
  2569. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  2570. var pid = process.pid;
  2571. debugs[set] = function() {
  2572. var msg = exports.format.apply(exports, arguments);
  2573. console.error('%s %d: %s', set, pid, msg);
  2574. };
  2575. } else {
  2576. debugs[set] = function() {};
  2577. }
  2578. }
  2579. return debugs[set];
  2580. };
  2581. /**
  2582. * Echos the value of a value. Trys to print the value out
  2583. * in the best way possible given the different types.
  2584. *
  2585. * @param {Object} obj The object to print out.
  2586. * @param {Object} opts Optional options object that alters the output.
  2587. */
  2588. /* legacy: obj, showHidden, depth, colors*/
  2589. function inspect(obj, opts) {
  2590. // default options
  2591. var ctx = {
  2592. seen: [],
  2593. stylize: stylizeNoColor
  2594. };
  2595. // legacy...
  2596. if (arguments.length >= 3) ctx.depth = arguments[2];
  2597. if (arguments.length >= 4) ctx.colors = arguments[3];
  2598. if (isBoolean(opts)) {
  2599. // legacy...
  2600. ctx.showHidden = opts;
  2601. } else if (opts) {
  2602. // got an "options" object
  2603. exports._extend(ctx, opts);
  2604. }
  2605. // set default options
  2606. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  2607. if (isUndefined(ctx.depth)) ctx.depth = 2;
  2608. if (isUndefined(ctx.colors)) ctx.colors = false;
  2609. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  2610. if (ctx.colors) ctx.stylize = stylizeWithColor;
  2611. return formatValue(ctx, obj, ctx.depth);
  2612. }
  2613. exports.inspect = inspect;
  2614. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  2615. inspect.colors = {
  2616. 'bold' : [1, 22],
  2617. 'italic' : [3, 23],
  2618. 'underline' : [4, 24],
  2619. 'inverse' : [7, 27],
  2620. 'white' : [37, 39],
  2621. 'grey' : [90, 39],
  2622. 'black' : [30, 39],
  2623. 'blue' : [34, 39],
  2624. 'cyan' : [36, 39],
  2625. 'green' : [32, 39],
  2626. 'magenta' : [35, 39],
  2627. 'red' : [31, 39],
  2628. 'yellow' : [33, 39]
  2629. };
  2630. // Don't use 'blue' not visible on cmd.exe
  2631. inspect.styles = {
  2632. 'special': 'cyan',
  2633. 'number': 'yellow',
  2634. 'boolean': 'yellow',
  2635. 'undefined': 'grey',
  2636. 'null': 'bold',
  2637. 'string': 'green',
  2638. 'date': 'magenta',
  2639. // "name": intentionally not styling
  2640. 'regexp': 'red'
  2641. };
  2642. function stylizeWithColor(str, styleType) {
  2643. var style = inspect.styles[styleType];
  2644. if (style) {
  2645. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  2646. '\u001b[' + inspect.colors[style][1] + 'm';
  2647. } else {
  2648. return str;
  2649. }
  2650. }
  2651. function stylizeNoColor(str, styleType) {
  2652. return str;
  2653. }
  2654. function arrayToHash(array) {
  2655. var hash = {};
  2656. array.forEach(function(val, idx) {
  2657. hash[val] = true;
  2658. });
  2659. return hash;
  2660. }
  2661. function formatValue(ctx, value, recurseTimes) {
  2662. // Provide a hook for user-specified inspect functions.
  2663. // Check that value is an object with an inspect function on it
  2664. if (ctx.customInspect &&
  2665. value &&
  2666. isFunction(value.inspect) &&
  2667. // Filter out the util module, it's inspect function is special
  2668. value.inspect !== exports.inspect &&
  2669. // Also filter out any prototype objects using the circular check.
  2670. !(value.constructor && value.constructor.prototype === value)) {
  2671. var ret = value.inspect(recurseTimes, ctx);
  2672. if (!isString(ret)) {
  2673. ret = formatValue(ctx, ret, recurseTimes);
  2674. }
  2675. return ret;
  2676. }
  2677. // Primitive types cannot have properties
  2678. var primitive = formatPrimitive(ctx, value);
  2679. if (primitive) {
  2680. return primitive;
  2681. }
  2682. // Look up the keys of the object.
  2683. var keys = Object.keys(value);
  2684. var visibleKeys = arrayToHash(keys);
  2685. if (ctx.showHidden) {
  2686. keys = Object.getOwnPropertyNames(value);
  2687. }
  2688. // IE doesn't make error fields non-enumerable
  2689. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  2690. if (isError(value)
  2691. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  2692. return formatError(value);
  2693. }
  2694. // Some type of object without properties can be shortcutted.
  2695. if (keys.length === 0) {
  2696. if (isFunction(value)) {
  2697. var name = value.name ? ': ' + value.name : '';
  2698. return ctx.stylize('[Function' + name + ']', 'special');
  2699. }
  2700. if (isRegExp(value)) {
  2701. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2702. }
  2703. if (isDate(value)) {
  2704. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  2705. }
  2706. if (isError(value)) {
  2707. return formatError(value);
  2708. }
  2709. }
  2710. var base = '', array = false, braces = ['{', '}'];
  2711. // Make Array say that they are Array
  2712. if (isArray(value)) {
  2713. array = true;
  2714. braces = ['[', ']'];
  2715. }
  2716. // Make functions say that they are functions
  2717. if (isFunction(value)) {
  2718. var n = value.name ? ': ' + value.name : '';
  2719. base = ' [Function' + n + ']';
  2720. }
  2721. // Make RegExps say that they are RegExps
  2722. if (isRegExp(value)) {
  2723. base = ' ' + RegExp.prototype.toString.call(value);
  2724. }
  2725. // Make dates with properties first say the date
  2726. if (isDate(value)) {
  2727. base = ' ' + Date.prototype.toUTCString.call(value);
  2728. }
  2729. // Make error with message first say the error
  2730. if (isError(value)) {
  2731. base = ' ' + formatError(value);
  2732. }
  2733. if (keys.length === 0 && (!array || value.length == 0)) {
  2734. return braces[0] + base + braces[1];
  2735. }
  2736. if (recurseTimes < 0) {
  2737. if (isRegExp(value)) {
  2738. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2739. } else {
  2740. return ctx.stylize('[Object]', 'special');
  2741. }
  2742. }
  2743. ctx.seen.push(value);
  2744. var output;
  2745. if (array) {
  2746. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  2747. } else {
  2748. output = keys.map(function(key) {
  2749. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  2750. });
  2751. }
  2752. ctx.seen.pop();
  2753. return reduceToSingleString(output, base, braces);
  2754. }
  2755. function formatPrimitive(ctx, value) {
  2756. if (isUndefined(value))
  2757. return ctx.stylize('undefined', 'undefined');
  2758. if (isString(value)) {
  2759. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  2760. .replace(/'/g, "\\'")
  2761. .replace(/\\"/g, '"') + '\'';
  2762. return ctx.stylize(simple, 'string');
  2763. }
  2764. if (isNumber(value))
  2765. return ctx.stylize('' + value, 'number');
  2766. if (isBoolean(value))
  2767. return ctx.stylize('' + value, 'boolean');
  2768. // For some reason typeof null is "object", so special case here.
  2769. if (isNull(value))
  2770. return ctx.stylize('null', 'null');
  2771. }
  2772. function formatError(value) {
  2773. return '[' + Error.prototype.toString.call(value) + ']';
  2774. }
  2775. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  2776. var output = [];
  2777. for (var i = 0, l = value.length; i < l; ++i) {
  2778. if (hasOwnProperty(value, String(i))) {
  2779. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2780. String(i), true));
  2781. } else {
  2782. output.push('');
  2783. }
  2784. }
  2785. keys.forEach(function(key) {
  2786. if (!key.match(/^\d+$/)) {
  2787. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2788. key, true));
  2789. }
  2790. });
  2791. return output;
  2792. }
  2793. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  2794. var name, str, desc;
  2795. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  2796. if (desc.get) {
  2797. if (desc.set) {
  2798. str = ctx.stylize('[Getter/Setter]', 'special');
  2799. } else {
  2800. str = ctx.stylize('[Getter]', 'special');
  2801. }
  2802. } else {
  2803. if (desc.set) {
  2804. str = ctx.stylize('[Setter]', 'special');
  2805. }
  2806. }
  2807. if (!hasOwnProperty(visibleKeys, key)) {
  2808. name = '[' + key + ']';
  2809. }
  2810. if (!str) {
  2811. if (ctx.seen.indexOf(desc.value) < 0) {
  2812. if (isNull(recurseTimes)) {
  2813. str = formatValue(ctx, desc.value, null);
  2814. } else {
  2815. str = formatValue(ctx, desc.value, recurseTimes - 1);
  2816. }
  2817. if (str.indexOf('\n') > -1) {
  2818. if (array) {
  2819. str = str.split('\n').map(function(line) {
  2820. return ' ' + line;
  2821. }).join('\n').substr(2);
  2822. } else {
  2823. str = '\n' + str.split('\n').map(function(line) {
  2824. return ' ' + line;
  2825. }).join('\n');
  2826. }
  2827. }
  2828. } else {
  2829. str = ctx.stylize('[Circular]', 'special');
  2830. }
  2831. }
  2832. if (isUndefined(name)) {
  2833. if (array && key.match(/^\d+$/)) {
  2834. return str;
  2835. }
  2836. name = JSON.stringify('' + key);
  2837. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  2838. name = name.substr(1, name.length - 2);
  2839. name = ctx.stylize(name, 'name');
  2840. } else {
  2841. name = name.replace(/'/g, "\\'")
  2842. .replace(/\\"/g, '"')
  2843. .replace(/(^"|"$)/g, "'");
  2844. name = ctx.stylize(name, 'string');
  2845. }
  2846. }
  2847. return name + ': ' + str;
  2848. }
  2849. function reduceToSingleString(output, base, braces) {
  2850. var numLinesEst = 0;
  2851. var length = output.reduce(function(prev, cur) {
  2852. numLinesEst++;
  2853. if (cur.indexOf('\n') >= 0) numLinesEst++;
  2854. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  2855. }, 0);
  2856. if (length > 60) {
  2857. return braces[0] +
  2858. (base === '' ? '' : base + '\n ') +
  2859. ' ' +
  2860. output.join(',\n ') +
  2861. ' ' +
  2862. braces[1];
  2863. }
  2864. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  2865. }
  2866. // NOTE: These type checking functions intentionally don't use `instanceof`
  2867. // because it is fragile and can be easily faked with `Object.create()`.
  2868. function isArray(ar) {
  2869. return Array.isArray(ar);
  2870. }
  2871. exports.isArray = isArray;
  2872. function isBoolean(arg) {
  2873. return typeof arg === 'boolean';
  2874. }
  2875. exports.isBoolean = isBoolean;
  2876. function isNull(arg) {
  2877. return arg === null;
  2878. }
  2879. exports.isNull = isNull;
  2880. function isNullOrUndefined(arg) {
  2881. return arg == null;
  2882. }
  2883. exports.isNullOrUndefined = isNullOrUndefined;
  2884. function isNumber(arg) {
  2885. return typeof arg === 'number';
  2886. }
  2887. exports.isNumber = isNumber;
  2888. function isString(arg) {
  2889. return typeof arg === 'string';
  2890. }
  2891. exports.isString = isString;
  2892. function isSymbol(arg) {
  2893. return typeof arg === 'symbol';
  2894. }
  2895. exports.isSymbol = isSymbol;
  2896. function isUndefined(arg) {
  2897. return arg === void 0;
  2898. }
  2899. exports.isUndefined = isUndefined;
  2900. function isRegExp(re) {
  2901. return isObject(re) && objectToString(re) === '[object RegExp]';
  2902. }
  2903. exports.isRegExp = isRegExp;
  2904. function isObject(arg) {
  2905. return typeof arg === 'object' && arg !== null;
  2906. }
  2907. exports.isObject = isObject;
  2908. function isDate(d) {
  2909. return isObject(d) && objectToString(d) === '[object Date]';
  2910. }
  2911. exports.isDate = isDate;
  2912. function isError(e) {
  2913. return isObject(e) &&
  2914. (objectToString(e) === '[object Error]' || e instanceof Error);
  2915. }
  2916. exports.isError = isError;
  2917. function isFunction(arg) {
  2918. return typeof arg === 'function';
  2919. }
  2920. exports.isFunction = isFunction;
  2921. function isPrimitive(arg) {
  2922. return arg === null ||
  2923. typeof arg === 'boolean' ||
  2924. typeof arg === 'number' ||
  2925. typeof arg === 'string' ||
  2926. typeof arg === 'symbol' || // ES6 symbol
  2927. typeof arg === 'undefined';
  2928. }
  2929. exports.isPrimitive = isPrimitive;
  2930. exports.isBuffer = require('./support/isBuffer');
  2931. function objectToString(o) {
  2932. return Object.prototype.toString.call(o);
  2933. }
  2934. function pad(n) {
  2935. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  2936. }
  2937. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  2938. 'Oct', 'Nov', 'Dec'];
  2939. // 26 Feb 16:19:34
  2940. function timestamp() {
  2941. var d = new Date();
  2942. var time = [pad(d.getHours()),
  2943. pad(d.getMinutes()),
  2944. pad(d.getSeconds())].join(':');
  2945. return [d.getDate(), months[d.getMonth()], time].join(' ');
  2946. }
  2947. // log is just a thin wrapper to console.log that prepends a timestamp
  2948. exports.log = function() {
  2949. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  2950. };
  2951. /**
  2952. * Inherit the prototype methods from one constructor into another.
  2953. *
  2954. * The Function.prototype.inherits from lang.js rewritten as a standalone
  2955. * function (not on Function.prototype). NOTE: If this file is to be loaded
  2956. * during bootstrapping this function needs to be rewritten using some native
  2957. * functions as prototype setup using normal JavaScript does not work as
  2958. * expected during bootstrapping (see mirror.js in r114903).
  2959. *
  2960. * @param {function} ctor Constructor function which needs to inherit the
  2961. * prototype.
  2962. * @param {function} superCtor Constructor function to inherit prototype from.
  2963. */
  2964. exports.inherits = require('inherits');
  2965. exports._extend = function(origin, add) {
  2966. // Don't do anything if add isn't an object
  2967. if (!add || !isObject(add)) return origin;
  2968. var keys = Object.keys(add);
  2969. var i = keys.length;
  2970. while (i--) {
  2971. origin[keys[i]] = add[keys[i]];
  2972. }
  2973. return origin;
  2974. };
  2975. function hasOwnProperty(obj, prop) {
  2976. return Object.prototype.hasOwnProperty.call(obj, prop);
  2977. }
  2978. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2979. },{"./support/isBuffer":25,"_process":51,"inherits":24}],27:[function(require,module,exports){
  2980. 'use strict'
  2981. exports.byteLength = byteLength
  2982. exports.toByteArray = toByteArray
  2983. exports.fromByteArray = fromByteArray
  2984. var lookup = []
  2985. var revLookup = []
  2986. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2987. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2988. for (var i = 0, len = code.length; i < len; ++i) {
  2989. lookup[i] = code[i]
  2990. revLookup[code.charCodeAt(i)] = i
  2991. }
  2992. // Support decoding URL-safe base64 strings, as Node.js does.
  2993. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2994. revLookup['-'.charCodeAt(0)] = 62
  2995. revLookup['_'.charCodeAt(0)] = 63
  2996. function getLens (b64) {
  2997. var len = b64.length
  2998. if (len % 4 > 0) {
  2999. throw new Error('Invalid string. Length must be a multiple of 4')
  3000. }
  3001. // Trim off extra bytes after placeholder bytes are found
  3002. // See: https://github.com/beatgammit/base64-js/issues/42
  3003. var validLen = b64.indexOf('=')
  3004. if (validLen === -1) validLen = len
  3005. var placeHoldersLen = validLen === len
  3006. ? 0
  3007. : 4 - (validLen % 4)
  3008. return [validLen, placeHoldersLen]
  3009. }
  3010. // base64 is 4/3 + up to two characters of the original data
  3011. function byteLength (b64) {
  3012. var lens = getLens(b64)
  3013. var validLen = lens[0]
  3014. var placeHoldersLen = lens[1]
  3015. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  3016. }
  3017. function _byteLength (b64, validLen, placeHoldersLen) {
  3018. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  3019. }
  3020. function toByteArray (b64) {
  3021. var tmp
  3022. var lens = getLens(b64)
  3023. var validLen = lens[0]
  3024. var placeHoldersLen = lens[1]
  3025. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  3026. var curByte = 0
  3027. // if there are placeholders, only get up to the last complete 4 chars
  3028. var len = placeHoldersLen > 0
  3029. ? validLen - 4
  3030. : validLen
  3031. for (var i = 0; i < len; i += 4) {
  3032. tmp =
  3033. (revLookup[b64.charCodeAt(i)] << 18) |
  3034. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  3035. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  3036. revLookup[b64.charCodeAt(i + 3)]
  3037. arr[curByte++] = (tmp >> 16) & 0xFF
  3038. arr[curByte++] = (tmp >> 8) & 0xFF
  3039. arr[curByte++] = tmp & 0xFF
  3040. }
  3041. if (placeHoldersLen === 2) {
  3042. tmp =
  3043. (revLookup[b64.charCodeAt(i)] << 2) |
  3044. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  3045. arr[curByte++] = tmp & 0xFF
  3046. }
  3047. if (placeHoldersLen === 1) {
  3048. tmp =
  3049. (revLookup[b64.charCodeAt(i)] << 10) |
  3050. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  3051. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  3052. arr[curByte++] = (tmp >> 8) & 0xFF
  3053. arr[curByte++] = tmp & 0xFF
  3054. }
  3055. return arr
  3056. }
  3057. function tripletToBase64 (num) {
  3058. return lookup[num >> 18 & 0x3F] +
  3059. lookup[num >> 12 & 0x3F] +
  3060. lookup[num >> 6 & 0x3F] +
  3061. lookup[num & 0x3F]
  3062. }
  3063. function encodeChunk (uint8, start, end) {
  3064. var tmp
  3065. var output = []
  3066. for (var i = start; i < end; i += 3) {
  3067. tmp =
  3068. ((uint8[i] << 16) & 0xFF0000) +
  3069. ((uint8[i + 1] << 8) & 0xFF00) +
  3070. (uint8[i + 2] & 0xFF)
  3071. output.push(tripletToBase64(tmp))
  3072. }
  3073. return output.join('')
  3074. }
  3075. function fromByteArray (uint8) {
  3076. var tmp
  3077. var len = uint8.length
  3078. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  3079. var parts = []
  3080. var maxChunkLength = 16383 // must be multiple of 3
  3081. // go through the array every three bytes, we'll deal with trailing stuff later
  3082. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  3083. parts.push(encodeChunk(
  3084. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  3085. ))
  3086. }
  3087. // pad the end with zeros, but make sure to not forget the extra bytes
  3088. if (extraBytes === 1) {
  3089. tmp = uint8[len - 1]
  3090. parts.push(
  3091. lookup[tmp >> 2] +
  3092. lookup[(tmp << 4) & 0x3F] +
  3093. '=='
  3094. )
  3095. } else if (extraBytes === 2) {
  3096. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  3097. parts.push(
  3098. lookup[tmp >> 10] +
  3099. lookup[(tmp >> 4) & 0x3F] +
  3100. lookup[(tmp << 2) & 0x3F] +
  3101. '='
  3102. )
  3103. }
  3104. return parts.join('')
  3105. }
  3106. },{}],28:[function(require,module,exports){
  3107. },{}],29:[function(require,module,exports){
  3108. (function (process,Buffer){
  3109. 'use strict';
  3110. /* eslint camelcase: "off" */
  3111. var assert = require('assert');
  3112. var Zstream = require('pako/lib/zlib/zstream');
  3113. var zlib_deflate = require('pako/lib/zlib/deflate.js');
  3114. var zlib_inflate = require('pako/lib/zlib/inflate.js');
  3115. var constants = require('pako/lib/zlib/constants');
  3116. for (var key in constants) {
  3117. exports[key] = constants[key];
  3118. }
  3119. // zlib modes
  3120. exports.NONE = 0;
  3121. exports.DEFLATE = 1;
  3122. exports.INFLATE = 2;
  3123. exports.GZIP = 3;
  3124. exports.GUNZIP = 4;
  3125. exports.DEFLATERAW = 5;
  3126. exports.INFLATERAW = 6;
  3127. exports.UNZIP = 7;
  3128. var GZIP_HEADER_ID1 = 0x1f;
  3129. var GZIP_HEADER_ID2 = 0x8b;
  3130. /**
  3131. * Emulate Node's zlib C++ layer for use by the JS layer in index.js
  3132. */
  3133. function Zlib(mode) {
  3134. if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
  3135. throw new TypeError('Bad argument');
  3136. }
  3137. this.dictionary = null;
  3138. this.err = 0;
  3139. this.flush = 0;
  3140. this.init_done = false;
  3141. this.level = 0;
  3142. this.memLevel = 0;
  3143. this.mode = mode;
  3144. this.strategy = 0;
  3145. this.windowBits = 0;
  3146. this.write_in_progress = false;
  3147. this.pending_close = false;
  3148. this.gzip_id_bytes_read = 0;
  3149. }
  3150. Zlib.prototype.close = function () {
  3151. if (this.write_in_progress) {
  3152. this.pending_close = true;
  3153. return;
  3154. }
  3155. this.pending_close = false;
  3156. assert(this.init_done, 'close before init');
  3157. assert(this.mode <= exports.UNZIP);
  3158. if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
  3159. zlib_deflate.deflateEnd(this.strm);
  3160. } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
  3161. zlib_inflate.inflateEnd(this.strm);
  3162. }
  3163. this.mode = exports.NONE;
  3164. this.dictionary = null;
  3165. };
  3166. Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  3167. return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
  3168. };
  3169. Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  3170. return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
  3171. };
  3172. Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  3173. assert.equal(arguments.length, 8);
  3174. assert(this.init_done, 'write before init');
  3175. assert(this.mode !== exports.NONE, 'already finalized');
  3176. assert.equal(false, this.write_in_progress, 'write already in progress');
  3177. assert.equal(false, this.pending_close, 'close is pending');
  3178. this.write_in_progress = true;
  3179. assert.equal(false, flush === undefined, 'must provide flush value');
  3180. this.write_in_progress = true;
  3181. 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) {
  3182. throw new Error('Invalid flush value');
  3183. }
  3184. if (input == null) {
  3185. input = Buffer.alloc(0);
  3186. in_len = 0;
  3187. in_off = 0;
  3188. }
  3189. this.strm.avail_in = in_len;
  3190. this.strm.input = input;
  3191. this.strm.next_in = in_off;
  3192. this.strm.avail_out = out_len;
  3193. this.strm.output = out;
  3194. this.strm.next_out = out_off;
  3195. this.flush = flush;
  3196. if (!async) {
  3197. // sync version
  3198. this._process();
  3199. if (this._checkError()) {
  3200. return this._afterSync();
  3201. }
  3202. return;
  3203. }
  3204. // async version
  3205. var self = this;
  3206. process.nextTick(function () {
  3207. self._process();
  3208. self._after();
  3209. });
  3210. return this;
  3211. };
  3212. Zlib.prototype._afterSync = function () {
  3213. var avail_out = this.strm.avail_out;
  3214. var avail_in = this.strm.avail_in;
  3215. this.write_in_progress = false;
  3216. return [avail_in, avail_out];
  3217. };
  3218. Zlib.prototype._process = function () {
  3219. var next_expected_header_byte = null;
  3220. // If the avail_out is left at 0, then it means that it ran out
  3221. // of room. If there was avail_out left over, then it means
  3222. // that all of the input was consumed.
  3223. switch (this.mode) {
  3224. case exports.DEFLATE:
  3225. case exports.GZIP:
  3226. case exports.DEFLATERAW:
  3227. this.err = zlib_deflate.deflate(this.strm, this.flush);
  3228. break;
  3229. case exports.UNZIP:
  3230. if (this.strm.avail_in > 0) {
  3231. next_expected_header_byte = this.strm.next_in;
  3232. }
  3233. switch (this.gzip_id_bytes_read) {
  3234. case 0:
  3235. if (next_expected_header_byte === null) {
  3236. break;
  3237. }
  3238. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
  3239. this.gzip_id_bytes_read = 1;
  3240. next_expected_header_byte++;
  3241. if (this.strm.avail_in === 1) {
  3242. // The only available byte was already read.
  3243. break;
  3244. }
  3245. } else {
  3246. this.mode = exports.INFLATE;
  3247. break;
  3248. }
  3249. // fallthrough
  3250. case 1:
  3251. if (next_expected_header_byte === null) {
  3252. break;
  3253. }
  3254. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
  3255. this.gzip_id_bytes_read = 2;
  3256. this.mode = exports.GUNZIP;
  3257. } else {
  3258. // There is no actual difference between INFLATE and INFLATERAW
  3259. // (after initialization).
  3260. this.mode = exports.INFLATE;
  3261. }
  3262. break;
  3263. default:
  3264. throw new Error('invalid number of gzip magic number bytes read');
  3265. }
  3266. // fallthrough
  3267. case exports.INFLATE:
  3268. case exports.GUNZIP:
  3269. case exports.INFLATERAW:
  3270. this.err = zlib_inflate.inflate(this.strm, this.flush
  3271. // If data was encoded with dictionary
  3272. );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
  3273. // Load it
  3274. this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
  3275. if (this.err === exports.Z_OK) {
  3276. // And try to decode again
  3277. this.err = zlib_inflate.inflate(this.strm, this.flush);
  3278. } else if (this.err === exports.Z_DATA_ERROR) {
  3279. // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
  3280. // Make it possible for After() to tell a bad dictionary from bad
  3281. // input.
  3282. this.err = exports.Z_NEED_DICT;
  3283. }
  3284. }
  3285. while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
  3286. // Bytes remain in input buffer. Perhaps this is another compressed
  3287. // member in the same archive, or just trailing garbage.
  3288. // Trailing zero bytes are okay, though, since they are frequently
  3289. // used for padding.
  3290. this.reset();
  3291. this.err = zlib_inflate.inflate(this.strm, this.flush);
  3292. }
  3293. break;
  3294. default:
  3295. throw new Error('Unknown mode ' + this.mode);
  3296. }
  3297. };
  3298. Zlib.prototype._checkError = function () {
  3299. // Acceptable error states depend on the type of zlib stream.
  3300. switch (this.err) {
  3301. case exports.Z_OK:
  3302. case exports.Z_BUF_ERROR:
  3303. if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
  3304. this._error('unexpected end of file');
  3305. return false;
  3306. }
  3307. break;
  3308. case exports.Z_STREAM_END:
  3309. // normal statuses, not fatal
  3310. break;
  3311. case exports.Z_NEED_DICT:
  3312. if (this.dictionary == null) {
  3313. this._error('Missing dictionary');
  3314. } else {
  3315. this._error('Bad dictionary');
  3316. }
  3317. return false;
  3318. default:
  3319. // something else.
  3320. this._error('Zlib error');
  3321. return false;
  3322. }
  3323. return true;
  3324. };
  3325. Zlib.prototype._after = function () {
  3326. if (!this._checkError()) {
  3327. return;
  3328. }
  3329. var avail_out = this.strm.avail_out;
  3330. var avail_in = this.strm.avail_in;
  3331. this.write_in_progress = false;
  3332. // call the write() cb
  3333. this.callback(avail_in, avail_out);
  3334. if (this.pending_close) {
  3335. this.close();
  3336. }
  3337. };
  3338. Zlib.prototype._error = function (message) {
  3339. if (this.strm.msg) {
  3340. message = this.strm.msg;
  3341. }
  3342. this.onerror(message, this.err
  3343. // no hope of rescue.
  3344. );this.write_in_progress = false;
  3345. if (this.pending_close) {
  3346. this.close();
  3347. }
  3348. };
  3349. Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  3350. assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
  3351. assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  3352. assert(level >= -1 && level <= 9, 'invalid compression level');
  3353. assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
  3354. 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');
  3355. this._init(level, windowBits, memLevel, strategy, dictionary);
  3356. this._setDictionary();
  3357. };
  3358. Zlib.prototype.params = function () {
  3359. throw new Error('deflateParams Not supported');
  3360. };
  3361. Zlib.prototype.reset = function () {
  3362. this._reset();
  3363. this._setDictionary();
  3364. };
  3365. Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  3366. this.level = level;
  3367. this.windowBits = windowBits;
  3368. this.memLevel = memLevel;
  3369. this.strategy = strategy;
  3370. this.flush = exports.Z_NO_FLUSH;
  3371. this.err = exports.Z_OK;
  3372. if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
  3373. this.windowBits += 16;
  3374. }
  3375. if (this.mode === exports.UNZIP) {
  3376. this.windowBits += 32;
  3377. }
  3378. if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
  3379. this.windowBits = -1 * this.windowBits;
  3380. }
  3381. this.strm = new Zstream();
  3382. switch (this.mode) {
  3383. case exports.DEFLATE:
  3384. case exports.GZIP:
  3385. case exports.DEFLATERAW:
  3386. this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
  3387. break;
  3388. case exports.INFLATE:
  3389. case exports.GUNZIP:
  3390. case exports.INFLATERAW:
  3391. case exports.UNZIP:
  3392. this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
  3393. break;
  3394. default:
  3395. throw new Error('Unknown mode ' + this.mode);
  3396. }
  3397. if (this.err !== exports.Z_OK) {
  3398. this._error('Init error');
  3399. }
  3400. this.dictionary = dictionary;
  3401. this.write_in_progress = false;
  3402. this.init_done = true;
  3403. };
  3404. Zlib.prototype._setDictionary = function () {
  3405. if (this.dictionary == null) {
  3406. return;
  3407. }
  3408. this.err = exports.Z_OK;
  3409. switch (this.mode) {
  3410. case exports.DEFLATE:
  3411. case exports.DEFLATERAW:
  3412. this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
  3413. break;
  3414. default:
  3415. break;
  3416. }
  3417. if (this.err !== exports.Z_OK) {
  3418. this._error('Failed to set dictionary');
  3419. }
  3420. };
  3421. Zlib.prototype._reset = function () {
  3422. this.err = exports.Z_OK;
  3423. switch (this.mode) {
  3424. case exports.DEFLATE:
  3425. case exports.DEFLATERAW:
  3426. case exports.GZIP:
  3427. this.err = zlib_deflate.deflateReset(this.strm);
  3428. break;
  3429. case exports.INFLATE:
  3430. case exports.INFLATERAW:
  3431. case exports.GUNZIP:
  3432. this.err = zlib_inflate.inflateReset(this.strm);
  3433. break;
  3434. default:
  3435. break;
  3436. }
  3437. if (this.err !== exports.Z_OK) {
  3438. this._error('Failed to reset stream');
  3439. }
  3440. };
  3441. exports.Zlib = Zlib;
  3442. }).call(this,require('_process'),require("buffer").Buffer)
  3443. },{"_process":51,"assert":23,"buffer":32,"pako/lib/zlib/constants":41,"pako/lib/zlib/deflate.js":43,"pako/lib/zlib/inflate.js":45,"pako/lib/zlib/zstream":49}],30:[function(require,module,exports){
  3444. (function (process){
  3445. 'use strict';
  3446. var Buffer = require('buffer').Buffer;
  3447. var Transform = require('stream').Transform;
  3448. var binding = require('./binding');
  3449. var util = require('util');
  3450. var assert = require('assert').ok;
  3451. var kMaxLength = require('buffer').kMaxLength;
  3452. var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
  3453. // zlib doesn't provide these, so kludge them in following the same
  3454. // const naming scheme zlib uses.
  3455. binding.Z_MIN_WINDOWBITS = 8;
  3456. binding.Z_MAX_WINDOWBITS = 15;
  3457. binding.Z_DEFAULT_WINDOWBITS = 15;
  3458. // fewer than 64 bytes per chunk is stupid.
  3459. // technically it could work with as few as 8, but even 64 bytes
  3460. // is absurdly low. Usually a MB or more is best.
  3461. binding.Z_MIN_CHUNK = 64;
  3462. binding.Z_MAX_CHUNK = Infinity;
  3463. binding.Z_DEFAULT_CHUNK = 16 * 1024;
  3464. binding.Z_MIN_MEMLEVEL = 1;
  3465. binding.Z_MAX_MEMLEVEL = 9;
  3466. binding.Z_DEFAULT_MEMLEVEL = 8;
  3467. binding.Z_MIN_LEVEL = -1;
  3468. binding.Z_MAX_LEVEL = 9;
  3469. binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
  3470. // expose all the zlib constants
  3471. var bkeys = Object.keys(binding);
  3472. for (var bk = 0; bk < bkeys.length; bk++) {
  3473. var bkey = bkeys[bk];
  3474. if (bkey.match(/^Z/)) {
  3475. Object.defineProperty(exports, bkey, {
  3476. enumerable: true, value: binding[bkey], writable: false
  3477. });
  3478. }
  3479. }
  3480. // translation table for return codes.
  3481. var codes = {
  3482. Z_OK: binding.Z_OK,
  3483. Z_STREAM_END: binding.Z_STREAM_END,
  3484. Z_NEED_DICT: binding.Z_NEED_DICT,
  3485. Z_ERRNO: binding.Z_ERRNO,
  3486. Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  3487. Z_DATA_ERROR: binding.Z_DATA_ERROR,
  3488. Z_MEM_ERROR: binding.Z_MEM_ERROR,
  3489. Z_BUF_ERROR: binding.Z_BUF_ERROR,
  3490. Z_VERSION_ERROR: binding.Z_VERSION_ERROR
  3491. };
  3492. var ckeys = Object.keys(codes);
  3493. for (var ck = 0; ck < ckeys.length; ck++) {
  3494. var ckey = ckeys[ck];
  3495. codes[codes[ckey]] = ckey;
  3496. }
  3497. Object.defineProperty(exports, 'codes', {
  3498. enumerable: true, value: Object.freeze(codes), writable: false
  3499. });
  3500. exports.Deflate = Deflate;
  3501. exports.Inflate = Inflate;
  3502. exports.Gzip = Gzip;
  3503. exports.Gunzip = Gunzip;
  3504. exports.DeflateRaw = DeflateRaw;
  3505. exports.InflateRaw = InflateRaw;
  3506. exports.Unzip = Unzip;
  3507. exports.createDeflate = function (o) {
  3508. return new Deflate(o);
  3509. };
  3510. exports.createInflate = function (o) {
  3511. return new Inflate(o);
  3512. };
  3513. exports.createDeflateRaw = function (o) {
  3514. return new DeflateRaw(o);
  3515. };
  3516. exports.createInflateRaw = function (o) {
  3517. return new InflateRaw(o);
  3518. };
  3519. exports.createGzip = function (o) {
  3520. return new Gzip(o);
  3521. };
  3522. exports.createGunzip = function (o) {
  3523. return new Gunzip(o);
  3524. };
  3525. exports.createUnzip = function (o) {
  3526. return new Unzip(o);
  3527. };
  3528. // Convenience methods.
  3529. // compress/decompress a string or buffer in one step.
  3530. exports.deflate = function (buffer, opts, callback) {
  3531. if (typeof opts === 'function') {
  3532. callback = opts;
  3533. opts = {};
  3534. }
  3535. return zlibBuffer(new Deflate(opts), buffer, callback);
  3536. };
  3537. exports.deflateSync = function (buffer, opts) {
  3538. return zlibBufferSync(new Deflate(opts), buffer);
  3539. };
  3540. exports.gzip = function (buffer, opts, callback) {
  3541. if (typeof opts === 'function') {
  3542. callback = opts;
  3543. opts = {};
  3544. }
  3545. return zlibBuffer(new Gzip(opts), buffer, callback);
  3546. };
  3547. exports.gzipSync = function (buffer, opts) {
  3548. return zlibBufferSync(new Gzip(opts), buffer);
  3549. };
  3550. exports.deflateRaw = function (buffer, opts, callback) {
  3551. if (typeof opts === 'function') {
  3552. callback = opts;
  3553. opts = {};
  3554. }
  3555. return zlibBuffer(new DeflateRaw(opts), buffer, callback);
  3556. };
  3557. exports.deflateRawSync = function (buffer, opts) {
  3558. return zlibBufferSync(new DeflateRaw(opts), buffer);
  3559. };
  3560. exports.unzip = function (buffer, opts, callback) {
  3561. if (typeof opts === 'function') {
  3562. callback = opts;
  3563. opts = {};
  3564. }
  3565. return zlibBuffer(new Unzip(opts), buffer, callback);
  3566. };
  3567. exports.unzipSync = function (buffer, opts) {
  3568. return zlibBufferSync(new Unzip(opts), buffer);
  3569. };
  3570. exports.inflate = function (buffer, opts, callback) {
  3571. if (typeof opts === 'function') {
  3572. callback = opts;
  3573. opts = {};
  3574. }
  3575. return zlibBuffer(new Inflate(opts), buffer, callback);
  3576. };
  3577. exports.inflateSync = function (buffer, opts) {
  3578. return zlibBufferSync(new Inflate(opts), buffer);
  3579. };
  3580. exports.gunzip = function (buffer, opts, callback) {
  3581. if (typeof opts === 'function') {
  3582. callback = opts;
  3583. opts = {};
  3584. }
  3585. return zlibBuffer(new Gunzip(opts), buffer, callback);
  3586. };
  3587. exports.gunzipSync = function (buffer, opts) {
  3588. return zlibBufferSync(new Gunzip(opts), buffer);
  3589. };
  3590. exports.inflateRaw = function (buffer, opts, callback) {
  3591. if (typeof opts === 'function') {
  3592. callback = opts;
  3593. opts = {};
  3594. }
  3595. return zlibBuffer(new InflateRaw(opts), buffer, callback);
  3596. };
  3597. exports.inflateRawSync = function (buffer, opts) {
  3598. return zlibBufferSync(new InflateRaw(opts), buffer);
  3599. };
  3600. function zlibBuffer(engine, buffer, callback) {
  3601. var buffers = [];
  3602. var nread = 0;
  3603. engine.on('error', onError);
  3604. engine.on('end', onEnd);
  3605. engine.end(buffer);
  3606. flow();
  3607. function flow() {
  3608. var chunk;
  3609. while (null !== (chunk = engine.read())) {
  3610. buffers.push(chunk);
  3611. nread += chunk.length;
  3612. }
  3613. engine.once('readable', flow);
  3614. }
  3615. function onError(err) {
  3616. engine.removeListener('end', onEnd);
  3617. engine.removeListener('readable', flow);
  3618. callback(err);
  3619. }
  3620. function onEnd() {
  3621. var buf;
  3622. var err = null;
  3623. if (nread >= kMaxLength) {
  3624. err = new RangeError(kRangeErrorMessage);
  3625. } else {
  3626. buf = Buffer.concat(buffers, nread);
  3627. }
  3628. buffers = [];
  3629. engine.close();
  3630. callback(err, buf);
  3631. }
  3632. }
  3633. function zlibBufferSync(engine, buffer) {
  3634. if (typeof buffer === 'string') buffer = Buffer.from(buffer);
  3635. if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
  3636. var flushFlag = engine._finishFlushFlag;
  3637. return engine._processChunk(buffer, flushFlag);
  3638. }
  3639. // generic zlib
  3640. // minimal 2-byte header
  3641. function Deflate(opts) {
  3642. if (!(this instanceof Deflate)) return new Deflate(opts);
  3643. Zlib.call(this, opts, binding.DEFLATE);
  3644. }
  3645. function Inflate(opts) {
  3646. if (!(this instanceof Inflate)) return new Inflate(opts);
  3647. Zlib.call(this, opts, binding.INFLATE);
  3648. }
  3649. // gzip - bigger header, same deflate compression
  3650. function Gzip(opts) {
  3651. if (!(this instanceof Gzip)) return new Gzip(opts);
  3652. Zlib.call(this, opts, binding.GZIP);
  3653. }
  3654. function Gunzip(opts) {
  3655. if (!(this instanceof Gunzip)) return new Gunzip(opts);
  3656. Zlib.call(this, opts, binding.GUNZIP);
  3657. }
  3658. // raw - no header
  3659. function DeflateRaw(opts) {
  3660. if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  3661. Zlib.call(this, opts, binding.DEFLATERAW);
  3662. }
  3663. function InflateRaw(opts) {
  3664. if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  3665. Zlib.call(this, opts, binding.INFLATERAW);
  3666. }
  3667. // auto-detect header.
  3668. function Unzip(opts) {
  3669. if (!(this instanceof Unzip)) return new Unzip(opts);
  3670. Zlib.call(this, opts, binding.UNZIP);
  3671. }
  3672. function isValidFlushFlag(flag) {
  3673. 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;
  3674. }
  3675. // the Zlib class they all inherit from
  3676. // This thing manages the queue of requests, and returns
  3677. // true or false if there is anything in the queue when
  3678. // you call the .write() method.
  3679. function Zlib(opts, mode) {
  3680. var _this = this;
  3681. this._opts = opts = opts || {};
  3682. this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
  3683. Transform.call(this, opts);
  3684. if (opts.flush && !isValidFlushFlag(opts.flush)) {
  3685. throw new Error('Invalid flush flag: ' + opts.flush);
  3686. }
  3687. if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
  3688. throw new Error('Invalid flush flag: ' + opts.finishFlush);
  3689. }
  3690. this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  3691. this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
  3692. if (opts.chunkSize) {
  3693. if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
  3694. throw new Error('Invalid chunk size: ' + opts.chunkSize);
  3695. }
  3696. }
  3697. if (opts.windowBits) {
  3698. if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
  3699. throw new Error('Invalid windowBits: ' + opts.windowBits);
  3700. }
  3701. }
  3702. if (opts.level) {
  3703. if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
  3704. throw new Error('Invalid compression level: ' + opts.level);
  3705. }
  3706. }
  3707. if (opts.memLevel) {
  3708. if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
  3709. throw new Error('Invalid memLevel: ' + opts.memLevel);
  3710. }
  3711. }
  3712. if (opts.strategy) {
  3713. 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) {
  3714. throw new Error('Invalid strategy: ' + opts.strategy);
  3715. }
  3716. }
  3717. if (opts.dictionary) {
  3718. if (!Buffer.isBuffer(opts.dictionary)) {
  3719. throw new Error('Invalid dictionary: it should be a Buffer instance');
  3720. }
  3721. }
  3722. this._handle = new binding.Zlib(mode);
  3723. var self = this;
  3724. this._hadError = false;
  3725. this._handle.onerror = function (message, errno) {
  3726. // there is no way to cleanly recover.
  3727. // continuing only obscures problems.
  3728. _close(self);
  3729. self._hadError = true;
  3730. var error = new Error(message);
  3731. error.errno = errno;
  3732. error.code = exports.codes[errno];
  3733. self.emit('error', error);
  3734. };
  3735. var level = exports.Z_DEFAULT_COMPRESSION;
  3736. if (typeof opts.level === 'number') level = opts.level;
  3737. var strategy = exports.Z_DEFAULT_STRATEGY;
  3738. if (typeof opts.strategy === 'number') strategy = opts.strategy;
  3739. this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
  3740. this._buffer = Buffer.allocUnsafe(this._chunkSize);
  3741. this._offset = 0;
  3742. this._level = level;
  3743. this._strategy = strategy;
  3744. this.once('end', this.close);
  3745. Object.defineProperty(this, '_closed', {
  3746. get: function () {
  3747. return !_this._handle;
  3748. },
  3749. configurable: true,
  3750. enumerable: true
  3751. });
  3752. }
  3753. util.inherits(Zlib, Transform);
  3754. Zlib.prototype.params = function (level, strategy, callback) {
  3755. if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
  3756. throw new RangeError('Invalid compression level: ' + level);
  3757. }
  3758. if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
  3759. throw new TypeError('Invalid strategy: ' + strategy);
  3760. }
  3761. if (this._level !== level || this._strategy !== strategy) {
  3762. var self = this;
  3763. this.flush(binding.Z_SYNC_FLUSH, function () {
  3764. assert(self._handle, 'zlib binding closed');
  3765. self._handle.params(level, strategy);
  3766. if (!self._hadError) {
  3767. self._level = level;
  3768. self._strategy = strategy;
  3769. if (callback) callback();
  3770. }
  3771. });
  3772. } else {
  3773. process.nextTick(callback);
  3774. }
  3775. };
  3776. Zlib.prototype.reset = function () {
  3777. assert(this._handle, 'zlib binding closed');
  3778. return this._handle.reset();
  3779. };
  3780. // This is the _flush function called by the transform class,
  3781. // internally, when the last chunk has been written.
  3782. Zlib.prototype._flush = function (callback) {
  3783. this._transform(Buffer.alloc(0), '', callback);
  3784. };
  3785. Zlib.prototype.flush = function (kind, callback) {
  3786. var _this2 = this;
  3787. var ws = this._writableState;
  3788. if (typeof kind === 'function' || kind === undefined && !callback) {
  3789. callback = kind;
  3790. kind = binding.Z_FULL_FLUSH;
  3791. }
  3792. if (ws.ended) {
  3793. if (callback) process.nextTick(callback);
  3794. } else if (ws.ending) {
  3795. if (callback) this.once('end', callback);
  3796. } else if (ws.needDrain) {
  3797. if (callback) {
  3798. this.once('drain', function () {
  3799. return _this2.flush(kind, callback);
  3800. });
  3801. }
  3802. } else {
  3803. this._flushFlag = kind;
  3804. this.write(Buffer.alloc(0), '', callback);
  3805. }
  3806. };
  3807. Zlib.prototype.close = function (callback) {
  3808. _close(this, callback);
  3809. process.nextTick(emitCloseNT, this);
  3810. };
  3811. function _close(engine, callback) {
  3812. if (callback) process.nextTick(callback);
  3813. // Caller may invoke .close after a zlib error (which will null _handle).
  3814. if (!engine._handle) return;
  3815. engine._handle.close();
  3816. engine._handle = null;
  3817. }
  3818. function emitCloseNT(self) {
  3819. self.emit('close');
  3820. }
  3821. Zlib.prototype._transform = function (chunk, encoding, cb) {
  3822. var flushFlag;
  3823. var ws = this._writableState;
  3824. var ending = ws.ending || ws.ended;
  3825. var last = ending && (!chunk || ws.length === chunk.length);
  3826. if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
  3827. if (!this._handle) return cb(new Error('zlib binding closed'));
  3828. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  3829. // (or whatever flag was provided using opts.finishFlush).
  3830. // If it's explicitly flushing at some other time, then we use
  3831. // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  3832. // goodness.
  3833. if (last) flushFlag = this._finishFlushFlag;else {
  3834. flushFlag = this._flushFlag;
  3835. // once we've flushed the last of the queue, stop flushing and
  3836. // go back to the normal behavior.
  3837. if (chunk.length >= ws.length) {
  3838. this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
  3839. }
  3840. }
  3841. this._processChunk(chunk, flushFlag, cb);
  3842. };
  3843. Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  3844. var availInBefore = chunk && chunk.length;
  3845. var availOutBefore = this._chunkSize - this._offset;
  3846. var inOff = 0;
  3847. var self = this;
  3848. var async = typeof cb === 'function';
  3849. if (!async) {
  3850. var buffers = [];
  3851. var nread = 0;
  3852. var error;
  3853. this.on('error', function (er) {
  3854. error = er;
  3855. });
  3856. assert(this._handle, 'zlib binding closed');
  3857. do {
  3858. var res = this._handle.writeSync(flushFlag, chunk, // in
  3859. inOff, // in_off
  3860. availInBefore, // in_len
  3861. this._buffer, // out
  3862. this._offset, //out_off
  3863. availOutBefore); // out_len
  3864. } while (!this._hadError && callback(res[0], res[1]));
  3865. if (this._hadError) {
  3866. throw error;
  3867. }
  3868. if (nread >= kMaxLength) {
  3869. _close(this);
  3870. throw new RangeError(kRangeErrorMessage);
  3871. }
  3872. var buf = Buffer.concat(buffers, nread);
  3873. _close(this);
  3874. return buf;
  3875. }
  3876. assert(this._handle, 'zlib binding closed');
  3877. var req = this._handle.write(flushFlag, chunk, // in
  3878. inOff, // in_off
  3879. availInBefore, // in_len
  3880. this._buffer, // out
  3881. this._offset, //out_off
  3882. availOutBefore); // out_len
  3883. req.buffer = chunk;
  3884. req.callback = callback;
  3885. function callback(availInAfter, availOutAfter) {
  3886. // When the callback is used in an async write, the callback's
  3887. // context is the `req` object that was created. The req object
  3888. // is === this._handle, and that's why it's important to null
  3889. // out the values after they are done being used. `this._handle`
  3890. // can stay in memory longer than the callback and buffer are needed.
  3891. if (this) {
  3892. this.buffer = null;
  3893. this.callback = null;
  3894. }
  3895. if (self._hadError) return;
  3896. var have = availOutBefore - availOutAfter;
  3897. assert(have >= 0, 'have should not go down');
  3898. if (have > 0) {
  3899. var out = self._buffer.slice(self._offset, self._offset + have);
  3900. self._offset += have;
  3901. // serve some output to the consumer.
  3902. if (async) {
  3903. self.push(out);
  3904. } else {
  3905. buffers.push(out);
  3906. nread += out.length;
  3907. }
  3908. }
  3909. // exhausted the output buffer, or used all the input create a new one.
  3910. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  3911. availOutBefore = self._chunkSize;
  3912. self._offset = 0;
  3913. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  3914. }
  3915. if (availOutAfter === 0) {
  3916. // Not actually done. Need to reprocess.
  3917. // Also, update the availInBefore to the availInAfter value,
  3918. // so that if we have to hit it a third (fourth, etc.) time,
  3919. // it'll have the correct byte counts.
  3920. inOff += availInBefore - availInAfter;
  3921. availInBefore = availInAfter;
  3922. if (!async) return true;
  3923. var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
  3924. newReq.callback = callback; // this same function
  3925. newReq.buffer = chunk;
  3926. return;
  3927. }
  3928. if (!async) return false;
  3929. // finished with the chunk.
  3930. cb();
  3931. }
  3932. };
  3933. util.inherits(Deflate, Zlib);
  3934. util.inherits(Inflate, Zlib);
  3935. util.inherits(Gzip, Zlib);
  3936. util.inherits(Gunzip, Zlib);
  3937. util.inherits(DeflateRaw, Zlib);
  3938. util.inherits(InflateRaw, Zlib);
  3939. util.inherits(Unzip, Zlib);
  3940. }).call(this,require('_process'))
  3941. },{"./binding":29,"_process":51,"assert":23,"buffer":32,"stream":64,"util":69}],31:[function(require,module,exports){
  3942. (function (global){
  3943. 'use strict';
  3944. var buffer = require('buffer');
  3945. var Buffer = buffer.Buffer;
  3946. var SlowBuffer = buffer.SlowBuffer;
  3947. var MAX_LEN = buffer.kMaxLength || 2147483647;
  3948. exports.alloc = function alloc(size, fill, encoding) {
  3949. if (typeof Buffer.alloc === 'function') {
  3950. return Buffer.alloc(size, fill, encoding);
  3951. }
  3952. if (typeof encoding === 'number') {
  3953. throw new TypeError('encoding must not be number');
  3954. }
  3955. if (typeof size !== 'number') {
  3956. throw new TypeError('size must be a number');
  3957. }
  3958. if (size > MAX_LEN) {
  3959. throw new RangeError('size is too large');
  3960. }
  3961. var enc = encoding;
  3962. var _fill = fill;
  3963. if (_fill === undefined) {
  3964. enc = undefined;
  3965. _fill = 0;
  3966. }
  3967. var buf = new Buffer(size);
  3968. if (typeof _fill === 'string') {
  3969. var fillBuf = new Buffer(_fill, enc);
  3970. var flen = fillBuf.length;
  3971. var i = -1;
  3972. while (++i < size) {
  3973. buf[i] = fillBuf[i % flen];
  3974. }
  3975. } else {
  3976. buf.fill(_fill);
  3977. }
  3978. return buf;
  3979. }
  3980. exports.allocUnsafe = function allocUnsafe(size) {
  3981. if (typeof Buffer.allocUnsafe === 'function') {
  3982. return Buffer.allocUnsafe(size);
  3983. }
  3984. if (typeof size !== 'number') {
  3985. throw new TypeError('size must be a number');
  3986. }
  3987. if (size > MAX_LEN) {
  3988. throw new RangeError('size is too large');
  3989. }
  3990. return new Buffer(size);
  3991. }
  3992. exports.from = function from(value, encodingOrOffset, length) {
  3993. if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
  3994. return Buffer.from(value, encodingOrOffset, length);
  3995. }
  3996. if (typeof value === 'number') {
  3997. throw new TypeError('"value" argument must not be a number');
  3998. }
  3999. if (typeof value === 'string') {
  4000. return new Buffer(value, encodingOrOffset);
  4001. }
  4002. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  4003. var offset = encodingOrOffset;
  4004. if (arguments.length === 1) {
  4005. return new Buffer(value);
  4006. }
  4007. if (typeof offset === 'undefined') {
  4008. offset = 0;
  4009. }
  4010. var len = length;
  4011. if (typeof len === 'undefined') {
  4012. len = value.byteLength - offset;
  4013. }
  4014. if (offset >= value.byteLength) {
  4015. throw new RangeError('\'offset\' is out of bounds');
  4016. }
  4017. if (len > value.byteLength - offset) {
  4018. throw new RangeError('\'length\' is out of bounds');
  4019. }
  4020. return new Buffer(value.slice(offset, offset + len));
  4021. }
  4022. if (Buffer.isBuffer(value)) {
  4023. var out = new Buffer(value.length);
  4024. value.copy(out, 0, 0, value.length);
  4025. return out;
  4026. }
  4027. if (value) {
  4028. if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
  4029. return new Buffer(value);
  4030. }
  4031. if (value.type === 'Buffer' && Array.isArray(value.data)) {
  4032. return new Buffer(value.data);
  4033. }
  4034. }
  4035. throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
  4036. }
  4037. exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  4038. if (typeof Buffer.allocUnsafeSlow === 'function') {
  4039. return Buffer.allocUnsafeSlow(size);
  4040. }
  4041. if (typeof size !== 'number') {
  4042. throw new TypeError('size must be a number');
  4043. }
  4044. if (size >= MAX_LEN) {
  4045. throw new RangeError('size is too large');
  4046. }
  4047. return new SlowBuffer(size);
  4048. }
  4049. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4050. },{"buffer":32}],32:[function(require,module,exports){
  4051. (function (Buffer){
  4052. /*!
  4053. * The buffer module from node.js, for the browser.
  4054. *
  4055. * @author Feross Aboukhadijeh <https://feross.org>
  4056. * @license MIT
  4057. */
  4058. /* eslint-disable no-proto */
  4059. 'use strict'
  4060. var base64 = require('base64-js')
  4061. var ieee754 = require('ieee754')
  4062. exports.Buffer = Buffer
  4063. exports.SlowBuffer = SlowBuffer
  4064. exports.INSPECT_MAX_BYTES = 50
  4065. var K_MAX_LENGTH = 0x7fffffff
  4066. exports.kMaxLength = K_MAX_LENGTH
  4067. /**
  4068. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  4069. * === true Use Uint8Array implementation (fastest)
  4070. * === false Print warning and recommend using `buffer` v4.x which has an Object
  4071. * implementation (most compatible, even IE6)
  4072. *
  4073. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  4074. * Opera 11.6+, iOS 4.2+.
  4075. *
  4076. * We report that the browser does not support typed arrays if the are not subclassable
  4077. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  4078. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  4079. * for __proto__ and has a buggy typed array implementation.
  4080. */
  4081. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  4082. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  4083. typeof console.error === 'function') {
  4084. console.error(
  4085. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  4086. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  4087. )
  4088. }
  4089. function typedArraySupport () {
  4090. // Can typed array instances can be augmented?
  4091. try {
  4092. var arr = new Uint8Array(1)
  4093. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  4094. return arr.foo() === 42
  4095. } catch (e) {
  4096. return false
  4097. }
  4098. }
  4099. Object.defineProperty(Buffer.prototype, 'parent', {
  4100. enumerable: true,
  4101. get: function () {
  4102. if (!Buffer.isBuffer(this)) return undefined
  4103. return this.buffer
  4104. }
  4105. })
  4106. Object.defineProperty(Buffer.prototype, 'offset', {
  4107. enumerable: true,
  4108. get: function () {
  4109. if (!Buffer.isBuffer(this)) return undefined
  4110. return this.byteOffset
  4111. }
  4112. })
  4113. function createBuffer (length) {
  4114. if (length > K_MAX_LENGTH) {
  4115. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  4116. }
  4117. // Return an augmented `Uint8Array` instance
  4118. var buf = new Uint8Array(length)
  4119. buf.__proto__ = Buffer.prototype
  4120. return buf
  4121. }
  4122. /**
  4123. * The Buffer constructor returns instances of `Uint8Array` that have their
  4124. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  4125. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  4126. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  4127. * returns a single octet.
  4128. *
  4129. * The `Uint8Array` prototype remains unmodified.
  4130. */
  4131. function Buffer (arg, encodingOrOffset, length) {
  4132. // Common case.
  4133. if (typeof arg === 'number') {
  4134. if (typeof encodingOrOffset === 'string') {
  4135. throw new TypeError(
  4136. 'The "string" argument must be of type string. Received type number'
  4137. )
  4138. }
  4139. return allocUnsafe(arg)
  4140. }
  4141. return from(arg, encodingOrOffset, length)
  4142. }
  4143. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  4144. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  4145. Buffer[Symbol.species] === Buffer) {
  4146. Object.defineProperty(Buffer, Symbol.species, {
  4147. value: null,
  4148. configurable: true,
  4149. enumerable: false,
  4150. writable: false
  4151. })
  4152. }
  4153. Buffer.poolSize = 8192 // not used by this implementation
  4154. function from (value, encodingOrOffset, length) {
  4155. if (typeof value === 'string') {
  4156. return fromString(value, encodingOrOffset)
  4157. }
  4158. if (ArrayBuffer.isView(value)) {
  4159. return fromArrayLike(value)
  4160. }
  4161. if (value == null) {
  4162. throw TypeError(
  4163. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  4164. 'or Array-like Object. Received type ' + (typeof value)
  4165. )
  4166. }
  4167. if (isInstance(value, ArrayBuffer) ||
  4168. (value && isInstance(value.buffer, ArrayBuffer))) {
  4169. return fromArrayBuffer(value, encodingOrOffset, length)
  4170. }
  4171. if (typeof value === 'number') {
  4172. throw new TypeError(
  4173. 'The "value" argument must not be of type number. Received type number'
  4174. )
  4175. }
  4176. var valueOf = value.valueOf && value.valueOf()
  4177. if (valueOf != null && valueOf !== value) {
  4178. return Buffer.from(valueOf, encodingOrOffset, length)
  4179. }
  4180. var b = fromObject(value)
  4181. if (b) return b
  4182. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  4183. typeof value[Symbol.toPrimitive] === 'function') {
  4184. return Buffer.from(
  4185. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  4186. )
  4187. }
  4188. throw new TypeError(
  4189. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  4190. 'or Array-like Object. Received type ' + (typeof value)
  4191. )
  4192. }
  4193. /**
  4194. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  4195. * if value is a number.
  4196. * Buffer.from(str[, encoding])
  4197. * Buffer.from(array)
  4198. * Buffer.from(buffer)
  4199. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  4200. **/
  4201. Buffer.from = function (value, encodingOrOffset, length) {
  4202. return from(value, encodingOrOffset, length)
  4203. }
  4204. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  4205. // https://github.com/feross/buffer/pull/148
  4206. Buffer.prototype.__proto__ = Uint8Array.prototype
  4207. Buffer.__proto__ = Uint8Array
  4208. function assertSize (size) {
  4209. if (typeof size !== 'number') {
  4210. throw new TypeError('"size" argument must be of type number')
  4211. } else if (size < 0) {
  4212. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  4213. }
  4214. }
  4215. function alloc (size, fill, encoding) {
  4216. assertSize(size)
  4217. if (size <= 0) {
  4218. return createBuffer(size)
  4219. }
  4220. if (fill !== undefined) {
  4221. // Only pay attention to encoding if it's a string. This
  4222. // prevents accidentally sending in a number that would
  4223. // be interpretted as a start offset.
  4224. return typeof encoding === 'string'
  4225. ? createBuffer(size).fill(fill, encoding)
  4226. : createBuffer(size).fill(fill)
  4227. }
  4228. return createBuffer(size)
  4229. }
  4230. /**
  4231. * Creates a new filled Buffer instance.
  4232. * alloc(size[, fill[, encoding]])
  4233. **/
  4234. Buffer.alloc = function (size, fill, encoding) {
  4235. return alloc(size, fill, encoding)
  4236. }
  4237. function allocUnsafe (size) {
  4238. assertSize(size)
  4239. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  4240. }
  4241. /**
  4242. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  4243. * */
  4244. Buffer.allocUnsafe = function (size) {
  4245. return allocUnsafe(size)
  4246. }
  4247. /**
  4248. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  4249. */
  4250. Buffer.allocUnsafeSlow = function (size) {
  4251. return allocUnsafe(size)
  4252. }
  4253. function fromString (string, encoding) {
  4254. if (typeof encoding !== 'string' || encoding === '') {
  4255. encoding = 'utf8'
  4256. }
  4257. if (!Buffer.isEncoding(encoding)) {
  4258. throw new TypeError('Unknown encoding: ' + encoding)
  4259. }
  4260. var length = byteLength(string, encoding) | 0
  4261. var buf = createBuffer(length)
  4262. var actual = buf.write(string, encoding)
  4263. if (actual !== length) {
  4264. // Writing a hex string, for example, that contains invalid characters will
  4265. // cause everything after the first invalid character to be ignored. (e.g.
  4266. // 'abxxcd' will be treated as 'ab')
  4267. buf = buf.slice(0, actual)
  4268. }
  4269. return buf
  4270. }
  4271. function fromArrayLike (array) {
  4272. var length = array.length < 0 ? 0 : checked(array.length) | 0
  4273. var buf = createBuffer(length)
  4274. for (var i = 0; i < length; i += 1) {
  4275. buf[i] = array[i] & 255
  4276. }
  4277. return buf
  4278. }
  4279. function fromArrayBuffer (array, byteOffset, length) {
  4280. if (byteOffset < 0 || array.byteLength < byteOffset) {
  4281. throw new RangeError('"offset" is outside of buffer bounds')
  4282. }
  4283. if (array.byteLength < byteOffset + (length || 0)) {
  4284. throw new RangeError('"length" is outside of buffer bounds')
  4285. }
  4286. var buf
  4287. if (byteOffset === undefined && length === undefined) {
  4288. buf = new Uint8Array(array)
  4289. } else if (length === undefined) {
  4290. buf = new Uint8Array(array, byteOffset)
  4291. } else {
  4292. buf = new Uint8Array(array, byteOffset, length)
  4293. }
  4294. // Return an augmented `Uint8Array` instance
  4295. buf.__proto__ = Buffer.prototype
  4296. return buf
  4297. }
  4298. function fromObject (obj) {
  4299. if (Buffer.isBuffer(obj)) {
  4300. var len = checked(obj.length) | 0
  4301. var buf = createBuffer(len)
  4302. if (buf.length === 0) {
  4303. return buf
  4304. }
  4305. obj.copy(buf, 0, 0, len)
  4306. return buf
  4307. }
  4308. if (obj.length !== undefined) {
  4309. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  4310. return createBuffer(0)
  4311. }
  4312. return fromArrayLike(obj)
  4313. }
  4314. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  4315. return fromArrayLike(obj.data)
  4316. }
  4317. }
  4318. function checked (length) {
  4319. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  4320. // length is NaN (which is otherwise coerced to zero.)
  4321. if (length >= K_MAX_LENGTH) {
  4322. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  4323. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  4324. }
  4325. return length | 0
  4326. }
  4327. function SlowBuffer (length) {
  4328. if (+length != length) { // eslint-disable-line eqeqeq
  4329. length = 0
  4330. }
  4331. return Buffer.alloc(+length)
  4332. }
  4333. Buffer.isBuffer = function isBuffer (b) {
  4334. return b != null && b._isBuffer === true &&
  4335. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  4336. }
  4337. Buffer.compare = function compare (a, b) {
  4338. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  4339. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  4340. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  4341. throw new TypeError(
  4342. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  4343. )
  4344. }
  4345. if (a === b) return 0
  4346. var x = a.length
  4347. var y = b.length
  4348. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  4349. if (a[i] !== b[i]) {
  4350. x = a[i]
  4351. y = b[i]
  4352. break
  4353. }
  4354. }
  4355. if (x < y) return -1
  4356. if (y < x) return 1
  4357. return 0
  4358. }
  4359. Buffer.isEncoding = function isEncoding (encoding) {
  4360. switch (String(encoding).toLowerCase()) {
  4361. case 'hex':
  4362. case 'utf8':
  4363. case 'utf-8':
  4364. case 'ascii':
  4365. case 'latin1':
  4366. case 'binary':
  4367. case 'base64':
  4368. case 'ucs2':
  4369. case 'ucs-2':
  4370. case 'utf16le':
  4371. case 'utf-16le':
  4372. return true
  4373. default:
  4374. return false
  4375. }
  4376. }
  4377. Buffer.concat = function concat (list, length) {
  4378. if (!Array.isArray(list)) {
  4379. throw new TypeError('"list" argument must be an Array of Buffers')
  4380. }
  4381. if (list.length === 0) {
  4382. return Buffer.alloc(0)
  4383. }
  4384. var i
  4385. if (length === undefined) {
  4386. length = 0
  4387. for (i = 0; i < list.length; ++i) {
  4388. length += list[i].length
  4389. }
  4390. }
  4391. var buffer = Buffer.allocUnsafe(length)
  4392. var pos = 0
  4393. for (i = 0; i < list.length; ++i) {
  4394. var buf = list[i]
  4395. if (isInstance(buf, Uint8Array)) {
  4396. buf = Buffer.from(buf)
  4397. }
  4398. if (!Buffer.isBuffer(buf)) {
  4399. throw new TypeError('"list" argument must be an Array of Buffers')
  4400. }
  4401. buf.copy(buffer, pos)
  4402. pos += buf.length
  4403. }
  4404. return buffer
  4405. }
  4406. function byteLength (string, encoding) {
  4407. if (Buffer.isBuffer(string)) {
  4408. return string.length
  4409. }
  4410. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  4411. return string.byteLength
  4412. }
  4413. if (typeof string !== 'string') {
  4414. throw new TypeError(
  4415. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  4416. 'Received type ' + typeof string
  4417. )
  4418. }
  4419. var len = string.length
  4420. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  4421. if (!mustMatch && len === 0) return 0
  4422. // Use a for loop to avoid recursion
  4423. var loweredCase = false
  4424. for (;;) {
  4425. switch (encoding) {
  4426. case 'ascii':
  4427. case 'latin1':
  4428. case 'binary':
  4429. return len
  4430. case 'utf8':
  4431. case 'utf-8':
  4432. return utf8ToBytes(string).length
  4433. case 'ucs2':
  4434. case 'ucs-2':
  4435. case 'utf16le':
  4436. case 'utf-16le':
  4437. return len * 2
  4438. case 'hex':
  4439. return len >>> 1
  4440. case 'base64':
  4441. return base64ToBytes(string).length
  4442. default:
  4443. if (loweredCase) {
  4444. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  4445. }
  4446. encoding = ('' + encoding).toLowerCase()
  4447. loweredCase = true
  4448. }
  4449. }
  4450. }
  4451. Buffer.byteLength = byteLength
  4452. function slowToString (encoding, start, end) {
  4453. var loweredCase = false
  4454. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  4455. // property of a typed array.
  4456. // This behaves neither like String nor Uint8Array in that we set start/end
  4457. // to their upper/lower bounds if the value passed is out of range.
  4458. // undefined is handled specially as per ECMA-262 6th Edition,
  4459. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  4460. if (start === undefined || start < 0) {
  4461. start = 0
  4462. }
  4463. // Return early if start > this.length. Done here to prevent potential uint32
  4464. // coercion fail below.
  4465. if (start > this.length) {
  4466. return ''
  4467. }
  4468. if (end === undefined || end > this.length) {
  4469. end = this.length
  4470. }
  4471. if (end <= 0) {
  4472. return ''
  4473. }
  4474. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  4475. end >>>= 0
  4476. start >>>= 0
  4477. if (end <= start) {
  4478. return ''
  4479. }
  4480. if (!encoding) encoding = 'utf8'
  4481. while (true) {
  4482. switch (encoding) {
  4483. case 'hex':
  4484. return hexSlice(this, start, end)
  4485. case 'utf8':
  4486. case 'utf-8':
  4487. return utf8Slice(this, start, end)
  4488. case 'ascii':
  4489. return asciiSlice(this, start, end)
  4490. case 'latin1':
  4491. case 'binary':
  4492. return latin1Slice(this, start, end)
  4493. case 'base64':
  4494. return base64Slice(this, start, end)
  4495. case 'ucs2':
  4496. case 'ucs-2':
  4497. case 'utf16le':
  4498. case 'utf-16le':
  4499. return utf16leSlice(this, start, end)
  4500. default:
  4501. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  4502. encoding = (encoding + '').toLowerCase()
  4503. loweredCase = true
  4504. }
  4505. }
  4506. }
  4507. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  4508. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  4509. // reliably in a browserify context because there could be multiple different
  4510. // copies of the 'buffer' package in use. This method works even for Buffer
  4511. // instances that were created from another copy of the `buffer` package.
  4512. // See: https://github.com/feross/buffer/issues/154
  4513. Buffer.prototype._isBuffer = true
  4514. function swap (b, n, m) {
  4515. var i = b[n]
  4516. b[n] = b[m]
  4517. b[m] = i
  4518. }
  4519. Buffer.prototype.swap16 = function swap16 () {
  4520. var len = this.length
  4521. if (len % 2 !== 0) {
  4522. throw new RangeError('Buffer size must be a multiple of 16-bits')
  4523. }
  4524. for (var i = 0; i < len; i += 2) {
  4525. swap(this, i, i + 1)
  4526. }
  4527. return this
  4528. }
  4529. Buffer.prototype.swap32 = function swap32 () {
  4530. var len = this.length
  4531. if (len % 4 !== 0) {
  4532. throw new RangeError('Buffer size must be a multiple of 32-bits')
  4533. }
  4534. for (var i = 0; i < len; i += 4) {
  4535. swap(this, i, i + 3)
  4536. swap(this, i + 1, i + 2)
  4537. }
  4538. return this
  4539. }
  4540. Buffer.prototype.swap64 = function swap64 () {
  4541. var len = this.length
  4542. if (len % 8 !== 0) {
  4543. throw new RangeError('Buffer size must be a multiple of 64-bits')
  4544. }
  4545. for (var i = 0; i < len; i += 8) {
  4546. swap(this, i, i + 7)
  4547. swap(this, i + 1, i + 6)
  4548. swap(this, i + 2, i + 5)
  4549. swap(this, i + 3, i + 4)
  4550. }
  4551. return this
  4552. }
  4553. Buffer.prototype.toString = function toString () {
  4554. var length = this.length
  4555. if (length === 0) return ''
  4556. if (arguments.length === 0) return utf8Slice(this, 0, length)
  4557. return slowToString.apply(this, arguments)
  4558. }
  4559. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  4560. Buffer.prototype.equals = function equals (b) {
  4561. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  4562. if (this === b) return true
  4563. return Buffer.compare(this, b) === 0
  4564. }
  4565. Buffer.prototype.inspect = function inspect () {
  4566. var str = ''
  4567. var max = exports.INSPECT_MAX_BYTES
  4568. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  4569. if (this.length > max) str += ' ... '
  4570. return '<Buffer ' + str + '>'
  4571. }
  4572. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  4573. if (isInstance(target, Uint8Array)) {
  4574. target = Buffer.from(target, target.offset, target.byteLength)
  4575. }
  4576. if (!Buffer.isBuffer(target)) {
  4577. throw new TypeError(
  4578. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  4579. 'Received type ' + (typeof target)
  4580. )
  4581. }
  4582. if (start === undefined) {
  4583. start = 0
  4584. }
  4585. if (end === undefined) {
  4586. end = target ? target.length : 0
  4587. }
  4588. if (thisStart === undefined) {
  4589. thisStart = 0
  4590. }
  4591. if (thisEnd === undefined) {
  4592. thisEnd = this.length
  4593. }
  4594. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  4595. throw new RangeError('out of range index')
  4596. }
  4597. if (thisStart >= thisEnd && start >= end) {
  4598. return 0
  4599. }
  4600. if (thisStart >= thisEnd) {
  4601. return -1
  4602. }
  4603. if (start >= end) {
  4604. return 1
  4605. }
  4606. start >>>= 0
  4607. end >>>= 0
  4608. thisStart >>>= 0
  4609. thisEnd >>>= 0
  4610. if (this === target) return 0
  4611. var x = thisEnd - thisStart
  4612. var y = end - start
  4613. var len = Math.min(x, y)
  4614. var thisCopy = this.slice(thisStart, thisEnd)
  4615. var targetCopy = target.slice(start, end)
  4616. for (var i = 0; i < len; ++i) {
  4617. if (thisCopy[i] !== targetCopy[i]) {
  4618. x = thisCopy[i]
  4619. y = targetCopy[i]
  4620. break
  4621. }
  4622. }
  4623. if (x < y) return -1
  4624. if (y < x) return 1
  4625. return 0
  4626. }
  4627. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  4628. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  4629. //
  4630. // Arguments:
  4631. // - buffer - a Buffer to search
  4632. // - val - a string, Buffer, or number
  4633. // - byteOffset - an index into `buffer`; will be clamped to an int32
  4634. // - encoding - an optional encoding, relevant is val is a string
  4635. // - dir - true for indexOf, false for lastIndexOf
  4636. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  4637. // Empty buffer means no match
  4638. if (buffer.length === 0) return -1
  4639. // Normalize byteOffset
  4640. if (typeof byteOffset === 'string') {
  4641. encoding = byteOffset
  4642. byteOffset = 0
  4643. } else if (byteOffset > 0x7fffffff) {
  4644. byteOffset = 0x7fffffff
  4645. } else if (byteOffset < -0x80000000) {
  4646. byteOffset = -0x80000000
  4647. }
  4648. byteOffset = +byteOffset // Coerce to Number.
  4649. if (numberIsNaN(byteOffset)) {
  4650. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  4651. byteOffset = dir ? 0 : (buffer.length - 1)
  4652. }
  4653. // Normalize byteOffset: negative offsets start from the end of the buffer
  4654. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  4655. if (byteOffset >= buffer.length) {
  4656. if (dir) return -1
  4657. else byteOffset = buffer.length - 1
  4658. } else if (byteOffset < 0) {
  4659. if (dir) byteOffset = 0
  4660. else return -1
  4661. }
  4662. // Normalize val
  4663. if (typeof val === 'string') {
  4664. val = Buffer.from(val, encoding)
  4665. }
  4666. // Finally, search either indexOf (if dir is true) or lastIndexOf
  4667. if (Buffer.isBuffer(val)) {
  4668. // Special case: looking for empty string/buffer always fails
  4669. if (val.length === 0) {
  4670. return -1
  4671. }
  4672. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  4673. } else if (typeof val === 'number') {
  4674. val = val & 0xFF // Search for a byte value [0-255]
  4675. if (typeof Uint8Array.prototype.indexOf === 'function') {
  4676. if (dir) {
  4677. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  4678. } else {
  4679. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  4680. }
  4681. }
  4682. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  4683. }
  4684. throw new TypeError('val must be string, number or Buffer')
  4685. }
  4686. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  4687. var indexSize = 1
  4688. var arrLength = arr.length
  4689. var valLength = val.length
  4690. if (encoding !== undefined) {
  4691. encoding = String(encoding).toLowerCase()
  4692. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  4693. encoding === 'utf16le' || encoding === 'utf-16le') {
  4694. if (arr.length < 2 || val.length < 2) {
  4695. return -1
  4696. }
  4697. indexSize = 2
  4698. arrLength /= 2
  4699. valLength /= 2
  4700. byteOffset /= 2
  4701. }
  4702. }
  4703. function read (buf, i) {
  4704. if (indexSize === 1) {
  4705. return buf[i]
  4706. } else {
  4707. return buf.readUInt16BE(i * indexSize)
  4708. }
  4709. }
  4710. var i
  4711. if (dir) {
  4712. var foundIndex = -1
  4713. for (i = byteOffset; i < arrLength; i++) {
  4714. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  4715. if (foundIndex === -1) foundIndex = i
  4716. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  4717. } else {
  4718. if (foundIndex !== -1) i -= i - foundIndex
  4719. foundIndex = -1
  4720. }
  4721. }
  4722. } else {
  4723. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  4724. for (i = byteOffset; i >= 0; i--) {
  4725. var found = true
  4726. for (var j = 0; j < valLength; j++) {
  4727. if (read(arr, i + j) !== read(val, j)) {
  4728. found = false
  4729. break
  4730. }
  4731. }
  4732. if (found) return i
  4733. }
  4734. }
  4735. return -1
  4736. }
  4737. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  4738. return this.indexOf(val, byteOffset, encoding) !== -1
  4739. }
  4740. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  4741. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  4742. }
  4743. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  4744. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  4745. }
  4746. function hexWrite (buf, string, offset, length) {
  4747. offset = Number(offset) || 0
  4748. var remaining = buf.length - offset
  4749. if (!length) {
  4750. length = remaining
  4751. } else {
  4752. length = Number(length)
  4753. if (length > remaining) {
  4754. length = remaining
  4755. }
  4756. }
  4757. var strLen = string.length
  4758. if (length > strLen / 2) {
  4759. length = strLen / 2
  4760. }
  4761. for (var i = 0; i < length; ++i) {
  4762. var parsed = parseInt(string.substr(i * 2, 2), 16)
  4763. if (numberIsNaN(parsed)) return i
  4764. buf[offset + i] = parsed
  4765. }
  4766. return i
  4767. }
  4768. function utf8Write (buf, string, offset, length) {
  4769. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  4770. }
  4771. function asciiWrite (buf, string, offset, length) {
  4772. return blitBuffer(asciiToBytes(string), buf, offset, length)
  4773. }
  4774. function latin1Write (buf, string, offset, length) {
  4775. return asciiWrite(buf, string, offset, length)
  4776. }
  4777. function base64Write (buf, string, offset, length) {
  4778. return blitBuffer(base64ToBytes(string), buf, offset, length)
  4779. }
  4780. function ucs2Write (buf, string, offset, length) {
  4781. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  4782. }
  4783. Buffer.prototype.write = function write (string, offset, length, encoding) {
  4784. // Buffer#write(string)
  4785. if (offset === undefined) {
  4786. encoding = 'utf8'
  4787. length = this.length
  4788. offset = 0
  4789. // Buffer#write(string, encoding)
  4790. } else if (length === undefined && typeof offset === 'string') {
  4791. encoding = offset
  4792. length = this.length
  4793. offset = 0
  4794. // Buffer#write(string, offset[, length][, encoding])
  4795. } else if (isFinite(offset)) {
  4796. offset = offset >>> 0
  4797. if (isFinite(length)) {
  4798. length = length >>> 0
  4799. if (encoding === undefined) encoding = 'utf8'
  4800. } else {
  4801. encoding = length
  4802. length = undefined
  4803. }
  4804. } else {
  4805. throw new Error(
  4806. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  4807. )
  4808. }
  4809. var remaining = this.length - offset
  4810. if (length === undefined || length > remaining) length = remaining
  4811. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  4812. throw new RangeError('Attempt to write outside buffer bounds')
  4813. }
  4814. if (!encoding) encoding = 'utf8'
  4815. var loweredCase = false
  4816. for (;;) {
  4817. switch (encoding) {
  4818. case 'hex':
  4819. return hexWrite(this, string, offset, length)
  4820. case 'utf8':
  4821. case 'utf-8':
  4822. return utf8Write(this, string, offset, length)
  4823. case 'ascii':
  4824. return asciiWrite(this, string, offset, length)
  4825. case 'latin1':
  4826. case 'binary':
  4827. return latin1Write(this, string, offset, length)
  4828. case 'base64':
  4829. // Warning: maxLength not taken into account in base64Write
  4830. return base64Write(this, string, offset, length)
  4831. case 'ucs2':
  4832. case 'ucs-2':
  4833. case 'utf16le':
  4834. case 'utf-16le':
  4835. return ucs2Write(this, string, offset, length)
  4836. default:
  4837. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  4838. encoding = ('' + encoding).toLowerCase()
  4839. loweredCase = true
  4840. }
  4841. }
  4842. }
  4843. Buffer.prototype.toJSON = function toJSON () {
  4844. return {
  4845. type: 'Buffer',
  4846. data: Array.prototype.slice.call(this._arr || this, 0)
  4847. }
  4848. }
  4849. function base64Slice (buf, start, end) {
  4850. if (start === 0 && end === buf.length) {
  4851. return base64.fromByteArray(buf)
  4852. } else {
  4853. return base64.fromByteArray(buf.slice(start, end))
  4854. }
  4855. }
  4856. function utf8Slice (buf, start, end) {
  4857. end = Math.min(buf.length, end)
  4858. var res = []
  4859. var i = start
  4860. while (i < end) {
  4861. var firstByte = buf[i]
  4862. var codePoint = null
  4863. var bytesPerSequence = (firstByte > 0xEF) ? 4
  4864. : (firstByte > 0xDF) ? 3
  4865. : (firstByte > 0xBF) ? 2
  4866. : 1
  4867. if (i + bytesPerSequence <= end) {
  4868. var secondByte, thirdByte, fourthByte, tempCodePoint
  4869. switch (bytesPerSequence) {
  4870. case 1:
  4871. if (firstByte < 0x80) {
  4872. codePoint = firstByte
  4873. }
  4874. break
  4875. case 2:
  4876. secondByte = buf[i + 1]
  4877. if ((secondByte & 0xC0) === 0x80) {
  4878. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  4879. if (tempCodePoint > 0x7F) {
  4880. codePoint = tempCodePoint
  4881. }
  4882. }
  4883. break
  4884. case 3:
  4885. secondByte = buf[i + 1]
  4886. thirdByte = buf[i + 2]
  4887. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  4888. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  4889. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  4890. codePoint = tempCodePoint
  4891. }
  4892. }
  4893. break
  4894. case 4:
  4895. secondByte = buf[i + 1]
  4896. thirdByte = buf[i + 2]
  4897. fourthByte = buf[i + 3]
  4898. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  4899. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  4900. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  4901. codePoint = tempCodePoint
  4902. }
  4903. }
  4904. }
  4905. }
  4906. if (codePoint === null) {
  4907. // we did not generate a valid codePoint so insert a
  4908. // replacement char (U+FFFD) and advance only 1 byte
  4909. codePoint = 0xFFFD
  4910. bytesPerSequence = 1
  4911. } else if (codePoint > 0xFFFF) {
  4912. // encode to utf16 (surrogate pair dance)
  4913. codePoint -= 0x10000
  4914. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  4915. codePoint = 0xDC00 | codePoint & 0x3FF
  4916. }
  4917. res.push(codePoint)
  4918. i += bytesPerSequence
  4919. }
  4920. return decodeCodePointsArray(res)
  4921. }
  4922. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  4923. // the lowest limit is Chrome, with 0x10000 args.
  4924. // We go 1 magnitude less, for safety
  4925. var MAX_ARGUMENTS_LENGTH = 0x1000
  4926. function decodeCodePointsArray (codePoints) {
  4927. var len = codePoints.length
  4928. if (len <= MAX_ARGUMENTS_LENGTH) {
  4929. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  4930. }
  4931. // Decode in chunks to avoid "call stack size exceeded".
  4932. var res = ''
  4933. var i = 0
  4934. while (i < len) {
  4935. res += String.fromCharCode.apply(
  4936. String,
  4937. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  4938. )
  4939. }
  4940. return res
  4941. }
  4942. function asciiSlice (buf, start, end) {
  4943. var ret = ''
  4944. end = Math.min(buf.length, end)
  4945. for (var i = start; i < end; ++i) {
  4946. ret += String.fromCharCode(buf[i] & 0x7F)
  4947. }
  4948. return ret
  4949. }
  4950. function latin1Slice (buf, start, end) {
  4951. var ret = ''
  4952. end = Math.min(buf.length, end)
  4953. for (var i = start; i < end; ++i) {
  4954. ret += String.fromCharCode(buf[i])
  4955. }
  4956. return ret
  4957. }
  4958. function hexSlice (buf, start, end) {
  4959. var len = buf.length
  4960. if (!start || start < 0) start = 0
  4961. if (!end || end < 0 || end > len) end = len
  4962. var out = ''
  4963. for (var i = start; i < end; ++i) {
  4964. out += toHex(buf[i])
  4965. }
  4966. return out
  4967. }
  4968. function utf16leSlice (buf, start, end) {
  4969. var bytes = buf.slice(start, end)
  4970. var res = ''
  4971. for (var i = 0; i < bytes.length; i += 2) {
  4972. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  4973. }
  4974. return res
  4975. }
  4976. Buffer.prototype.slice = function slice (start, end) {
  4977. var len = this.length
  4978. start = ~~start
  4979. end = end === undefined ? len : ~~end
  4980. if (start < 0) {
  4981. start += len
  4982. if (start < 0) start = 0
  4983. } else if (start > len) {
  4984. start = len
  4985. }
  4986. if (end < 0) {
  4987. end += len
  4988. if (end < 0) end = 0
  4989. } else if (end > len) {
  4990. end = len
  4991. }
  4992. if (end < start) end = start
  4993. var newBuf = this.subarray(start, end)
  4994. // Return an augmented `Uint8Array` instance
  4995. newBuf.__proto__ = Buffer.prototype
  4996. return newBuf
  4997. }
  4998. /*
  4999. * Need to make sure that buffer isn't trying to write out of bounds.
  5000. */
  5001. function checkOffset (offset, ext, length) {
  5002. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  5003. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  5004. }
  5005. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  5006. offset = offset >>> 0
  5007. byteLength = byteLength >>> 0
  5008. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5009. var val = this[offset]
  5010. var mul = 1
  5011. var i = 0
  5012. while (++i < byteLength && (mul *= 0x100)) {
  5013. val += this[offset + i] * mul
  5014. }
  5015. return val
  5016. }
  5017. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  5018. offset = offset >>> 0
  5019. byteLength = byteLength >>> 0
  5020. if (!noAssert) {
  5021. checkOffset(offset, byteLength, this.length)
  5022. }
  5023. var val = this[offset + --byteLength]
  5024. var mul = 1
  5025. while (byteLength > 0 && (mul *= 0x100)) {
  5026. val += this[offset + --byteLength] * mul
  5027. }
  5028. return val
  5029. }
  5030. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  5031. offset = offset >>> 0
  5032. if (!noAssert) checkOffset(offset, 1, this.length)
  5033. return this[offset]
  5034. }
  5035. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  5036. offset = offset >>> 0
  5037. if (!noAssert) checkOffset(offset, 2, this.length)
  5038. return this[offset] | (this[offset + 1] << 8)
  5039. }
  5040. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  5041. offset = offset >>> 0
  5042. if (!noAssert) checkOffset(offset, 2, this.length)
  5043. return (this[offset] << 8) | this[offset + 1]
  5044. }
  5045. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  5046. offset = offset >>> 0
  5047. if (!noAssert) checkOffset(offset, 4, this.length)
  5048. return ((this[offset]) |
  5049. (this[offset + 1] << 8) |
  5050. (this[offset + 2] << 16)) +
  5051. (this[offset + 3] * 0x1000000)
  5052. }
  5053. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  5054. offset = offset >>> 0
  5055. if (!noAssert) checkOffset(offset, 4, this.length)
  5056. return (this[offset] * 0x1000000) +
  5057. ((this[offset + 1] << 16) |
  5058. (this[offset + 2] << 8) |
  5059. this[offset + 3])
  5060. }
  5061. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  5062. offset = offset >>> 0
  5063. byteLength = byteLength >>> 0
  5064. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5065. var val = this[offset]
  5066. var mul = 1
  5067. var i = 0
  5068. while (++i < byteLength && (mul *= 0x100)) {
  5069. val += this[offset + i] * mul
  5070. }
  5071. mul *= 0x80
  5072. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  5073. return val
  5074. }
  5075. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  5076. offset = offset >>> 0
  5077. byteLength = byteLength >>> 0
  5078. if (!noAssert) checkOffset(offset, byteLength, this.length)
  5079. var i = byteLength
  5080. var mul = 1
  5081. var val = this[offset + --i]
  5082. while (i > 0 && (mul *= 0x100)) {
  5083. val += this[offset + --i] * mul
  5084. }
  5085. mul *= 0x80
  5086. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  5087. return val
  5088. }
  5089. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  5090. offset = offset >>> 0
  5091. if (!noAssert) checkOffset(offset, 1, this.length)
  5092. if (!(this[offset] & 0x80)) return (this[offset])
  5093. return ((0xff - this[offset] + 1) * -1)
  5094. }
  5095. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  5096. offset = offset >>> 0
  5097. if (!noAssert) checkOffset(offset, 2, this.length)
  5098. var val = this[offset] | (this[offset + 1] << 8)
  5099. return (val & 0x8000) ? val | 0xFFFF0000 : val
  5100. }
  5101. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  5102. offset = offset >>> 0
  5103. if (!noAssert) checkOffset(offset, 2, this.length)
  5104. var val = this[offset + 1] | (this[offset] << 8)
  5105. return (val & 0x8000) ? val | 0xFFFF0000 : val
  5106. }
  5107. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  5108. offset = offset >>> 0
  5109. if (!noAssert) checkOffset(offset, 4, this.length)
  5110. return (this[offset]) |
  5111. (this[offset + 1] << 8) |
  5112. (this[offset + 2] << 16) |
  5113. (this[offset + 3] << 24)
  5114. }
  5115. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  5116. offset = offset >>> 0
  5117. if (!noAssert) checkOffset(offset, 4, this.length)
  5118. return (this[offset] << 24) |
  5119. (this[offset + 1] << 16) |
  5120. (this[offset + 2] << 8) |
  5121. (this[offset + 3])
  5122. }
  5123. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  5124. offset = offset >>> 0
  5125. if (!noAssert) checkOffset(offset, 4, this.length)
  5126. return ieee754.read(this, offset, true, 23, 4)
  5127. }
  5128. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  5129. offset = offset >>> 0
  5130. if (!noAssert) checkOffset(offset, 4, this.length)
  5131. return ieee754.read(this, offset, false, 23, 4)
  5132. }
  5133. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  5134. offset = offset >>> 0
  5135. if (!noAssert) checkOffset(offset, 8, this.length)
  5136. return ieee754.read(this, offset, true, 52, 8)
  5137. }
  5138. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  5139. offset = offset >>> 0
  5140. if (!noAssert) checkOffset(offset, 8, this.length)
  5141. return ieee754.read(this, offset, false, 52, 8)
  5142. }
  5143. function checkInt (buf, value, offset, ext, max, min) {
  5144. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  5145. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  5146. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  5147. }
  5148. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  5149. value = +value
  5150. offset = offset >>> 0
  5151. byteLength = byteLength >>> 0
  5152. if (!noAssert) {
  5153. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  5154. checkInt(this, value, offset, byteLength, maxBytes, 0)
  5155. }
  5156. var mul = 1
  5157. var i = 0
  5158. this[offset] = value & 0xFF
  5159. while (++i < byteLength && (mul *= 0x100)) {
  5160. this[offset + i] = (value / mul) & 0xFF
  5161. }
  5162. return offset + byteLength
  5163. }
  5164. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  5165. value = +value
  5166. offset = offset >>> 0
  5167. byteLength = byteLength >>> 0
  5168. if (!noAssert) {
  5169. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  5170. checkInt(this, value, offset, byteLength, maxBytes, 0)
  5171. }
  5172. var i = byteLength - 1
  5173. var mul = 1
  5174. this[offset + i] = value & 0xFF
  5175. while (--i >= 0 && (mul *= 0x100)) {
  5176. this[offset + i] = (value / mul) & 0xFF
  5177. }
  5178. return offset + byteLength
  5179. }
  5180. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  5181. value = +value
  5182. offset = offset >>> 0
  5183. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  5184. this[offset] = (value & 0xff)
  5185. return offset + 1
  5186. }
  5187. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  5188. value = +value
  5189. offset = offset >>> 0
  5190. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  5191. this[offset] = (value & 0xff)
  5192. this[offset + 1] = (value >>> 8)
  5193. return offset + 2
  5194. }
  5195. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  5196. value = +value
  5197. offset = offset >>> 0
  5198. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  5199. this[offset] = (value >>> 8)
  5200. this[offset + 1] = (value & 0xff)
  5201. return offset + 2
  5202. }
  5203. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  5204. value = +value
  5205. offset = offset >>> 0
  5206. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  5207. this[offset + 3] = (value >>> 24)
  5208. this[offset + 2] = (value >>> 16)
  5209. this[offset + 1] = (value >>> 8)
  5210. this[offset] = (value & 0xff)
  5211. return offset + 4
  5212. }
  5213. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  5214. value = +value
  5215. offset = offset >>> 0
  5216. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  5217. this[offset] = (value >>> 24)
  5218. this[offset + 1] = (value >>> 16)
  5219. this[offset + 2] = (value >>> 8)
  5220. this[offset + 3] = (value & 0xff)
  5221. return offset + 4
  5222. }
  5223. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  5224. value = +value
  5225. offset = offset >>> 0
  5226. if (!noAssert) {
  5227. var limit = Math.pow(2, (8 * byteLength) - 1)
  5228. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  5229. }
  5230. var i = 0
  5231. var mul = 1
  5232. var sub = 0
  5233. this[offset] = value & 0xFF
  5234. while (++i < byteLength && (mul *= 0x100)) {
  5235. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  5236. sub = 1
  5237. }
  5238. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  5239. }
  5240. return offset + byteLength
  5241. }
  5242. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  5243. value = +value
  5244. offset = offset >>> 0
  5245. if (!noAssert) {
  5246. var limit = Math.pow(2, (8 * byteLength) - 1)
  5247. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  5248. }
  5249. var i = byteLength - 1
  5250. var mul = 1
  5251. var sub = 0
  5252. this[offset + i] = value & 0xFF
  5253. while (--i >= 0 && (mul *= 0x100)) {
  5254. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  5255. sub = 1
  5256. }
  5257. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  5258. }
  5259. return offset + byteLength
  5260. }
  5261. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  5262. value = +value
  5263. offset = offset >>> 0
  5264. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  5265. if (value < 0) value = 0xff + value + 1
  5266. this[offset] = (value & 0xff)
  5267. return offset + 1
  5268. }
  5269. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  5270. value = +value
  5271. offset = offset >>> 0
  5272. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  5273. this[offset] = (value & 0xff)
  5274. this[offset + 1] = (value >>> 8)
  5275. return offset + 2
  5276. }
  5277. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  5278. value = +value
  5279. offset = offset >>> 0
  5280. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  5281. this[offset] = (value >>> 8)
  5282. this[offset + 1] = (value & 0xff)
  5283. return offset + 2
  5284. }
  5285. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  5286. value = +value
  5287. offset = offset >>> 0
  5288. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  5289. this[offset] = (value & 0xff)
  5290. this[offset + 1] = (value >>> 8)
  5291. this[offset + 2] = (value >>> 16)
  5292. this[offset + 3] = (value >>> 24)
  5293. return offset + 4
  5294. }
  5295. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  5296. value = +value
  5297. offset = offset >>> 0
  5298. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  5299. if (value < 0) value = 0xffffffff + value + 1
  5300. this[offset] = (value >>> 24)
  5301. this[offset + 1] = (value >>> 16)
  5302. this[offset + 2] = (value >>> 8)
  5303. this[offset + 3] = (value & 0xff)
  5304. return offset + 4
  5305. }
  5306. function checkIEEE754 (buf, value, offset, ext, max, min) {
  5307. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  5308. if (offset < 0) throw new RangeError('Index out of range')
  5309. }
  5310. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  5311. value = +value
  5312. offset = offset >>> 0
  5313. if (!noAssert) {
  5314. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  5315. }
  5316. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  5317. return offset + 4
  5318. }
  5319. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  5320. return writeFloat(this, value, offset, true, noAssert)
  5321. }
  5322. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  5323. return writeFloat(this, value, offset, false, noAssert)
  5324. }
  5325. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  5326. value = +value
  5327. offset = offset >>> 0
  5328. if (!noAssert) {
  5329. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  5330. }
  5331. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  5332. return offset + 8
  5333. }
  5334. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  5335. return writeDouble(this, value, offset, true, noAssert)
  5336. }
  5337. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  5338. return writeDouble(this, value, offset, false, noAssert)
  5339. }
  5340. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  5341. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  5342. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  5343. if (!start) start = 0
  5344. if (!end && end !== 0) end = this.length
  5345. if (targetStart >= target.length) targetStart = target.length
  5346. if (!targetStart) targetStart = 0
  5347. if (end > 0 && end < start) end = start
  5348. // Copy 0 bytes; we're done
  5349. if (end === start) return 0
  5350. if (target.length === 0 || this.length === 0) return 0
  5351. // Fatal error conditions
  5352. if (targetStart < 0) {
  5353. throw new RangeError('targetStart out of bounds')
  5354. }
  5355. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  5356. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  5357. // Are we oob?
  5358. if (end > this.length) end = this.length
  5359. if (target.length - targetStart < end - start) {
  5360. end = target.length - targetStart + start
  5361. }
  5362. var len = end - start
  5363. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  5364. // Use built-in when available, missing from IE11
  5365. this.copyWithin(targetStart, start, end)
  5366. } else if (this === target && start < targetStart && targetStart < end) {
  5367. // descending copy from end
  5368. for (var i = len - 1; i >= 0; --i) {
  5369. target[i + targetStart] = this[i + start]
  5370. }
  5371. } else {
  5372. Uint8Array.prototype.set.call(
  5373. target,
  5374. this.subarray(start, end),
  5375. targetStart
  5376. )
  5377. }
  5378. return len
  5379. }
  5380. // Usage:
  5381. // buffer.fill(number[, offset[, end]])
  5382. // buffer.fill(buffer[, offset[, end]])
  5383. // buffer.fill(string[, offset[, end]][, encoding])
  5384. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  5385. // Handle string cases:
  5386. if (typeof val === 'string') {
  5387. if (typeof start === 'string') {
  5388. encoding = start
  5389. start = 0
  5390. end = this.length
  5391. } else if (typeof end === 'string') {
  5392. encoding = end
  5393. end = this.length
  5394. }
  5395. if (encoding !== undefined && typeof encoding !== 'string') {
  5396. throw new TypeError('encoding must be a string')
  5397. }
  5398. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  5399. throw new TypeError('Unknown encoding: ' + encoding)
  5400. }
  5401. if (val.length === 1) {
  5402. var code = val.charCodeAt(0)
  5403. if ((encoding === 'utf8' && code < 128) ||
  5404. encoding === 'latin1') {
  5405. // Fast path: If `val` fits into a single byte, use that numeric value.
  5406. val = code
  5407. }
  5408. }
  5409. } else if (typeof val === 'number') {
  5410. val = val & 255
  5411. }
  5412. // Invalid ranges are not set to a default, so can range check early.
  5413. if (start < 0 || this.length < start || this.length < end) {
  5414. throw new RangeError('Out of range index')
  5415. }
  5416. if (end <= start) {
  5417. return this
  5418. }
  5419. start = start >>> 0
  5420. end = end === undefined ? this.length : end >>> 0
  5421. if (!val) val = 0
  5422. var i
  5423. if (typeof val === 'number') {
  5424. for (i = start; i < end; ++i) {
  5425. this[i] = val
  5426. }
  5427. } else {
  5428. var bytes = Buffer.isBuffer(val)
  5429. ? val
  5430. : Buffer.from(val, encoding)
  5431. var len = bytes.length
  5432. if (len === 0) {
  5433. throw new TypeError('The value "' + val +
  5434. '" is invalid for argument "value"')
  5435. }
  5436. for (i = 0; i < end - start; ++i) {
  5437. this[i + start] = bytes[i % len]
  5438. }
  5439. }
  5440. return this
  5441. }
  5442. // HELPER FUNCTIONS
  5443. // ================
  5444. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  5445. function base64clean (str) {
  5446. // Node takes equal signs as end of the Base64 encoding
  5447. str = str.split('=')[0]
  5448. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  5449. str = str.trim().replace(INVALID_BASE64_RE, '')
  5450. // Node converts strings with length < 2 to ''
  5451. if (str.length < 2) return ''
  5452. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  5453. while (str.length % 4 !== 0) {
  5454. str = str + '='
  5455. }
  5456. return str
  5457. }
  5458. function toHex (n) {
  5459. if (n < 16) return '0' + n.toString(16)
  5460. return n.toString(16)
  5461. }
  5462. function utf8ToBytes (string, units) {
  5463. units = units || Infinity
  5464. var codePoint
  5465. var length = string.length
  5466. var leadSurrogate = null
  5467. var bytes = []
  5468. for (var i = 0; i < length; ++i) {
  5469. codePoint = string.charCodeAt(i)
  5470. // is surrogate component
  5471. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  5472. // last char was a lead
  5473. if (!leadSurrogate) {
  5474. // no lead yet
  5475. if (codePoint > 0xDBFF) {
  5476. // unexpected trail
  5477. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5478. continue
  5479. } else if (i + 1 === length) {
  5480. // unpaired lead
  5481. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5482. continue
  5483. }
  5484. // valid lead
  5485. leadSurrogate = codePoint
  5486. continue
  5487. }
  5488. // 2 leads in a row
  5489. if (codePoint < 0xDC00) {
  5490. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5491. leadSurrogate = codePoint
  5492. continue
  5493. }
  5494. // valid surrogate pair
  5495. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  5496. } else if (leadSurrogate) {
  5497. // valid bmp char, but last char was a lead
  5498. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  5499. }
  5500. leadSurrogate = null
  5501. // encode utf8
  5502. if (codePoint < 0x80) {
  5503. if ((units -= 1) < 0) break
  5504. bytes.push(codePoint)
  5505. } else if (codePoint < 0x800) {
  5506. if ((units -= 2) < 0) break
  5507. bytes.push(
  5508. codePoint >> 0x6 | 0xC0,
  5509. codePoint & 0x3F | 0x80
  5510. )
  5511. } else if (codePoint < 0x10000) {
  5512. if ((units -= 3) < 0) break
  5513. bytes.push(
  5514. codePoint >> 0xC | 0xE0,
  5515. codePoint >> 0x6 & 0x3F | 0x80,
  5516. codePoint & 0x3F | 0x80
  5517. )
  5518. } else if (codePoint < 0x110000) {
  5519. if ((units -= 4) < 0) break
  5520. bytes.push(
  5521. codePoint >> 0x12 | 0xF0,
  5522. codePoint >> 0xC & 0x3F | 0x80,
  5523. codePoint >> 0x6 & 0x3F | 0x80,
  5524. codePoint & 0x3F | 0x80
  5525. )
  5526. } else {
  5527. throw new Error('Invalid code point')
  5528. }
  5529. }
  5530. return bytes
  5531. }
  5532. function asciiToBytes (str) {
  5533. var byteArray = []
  5534. for (var i = 0; i < str.length; ++i) {
  5535. // Node's code seems to be doing this and not & 0x7F..
  5536. byteArray.push(str.charCodeAt(i) & 0xFF)
  5537. }
  5538. return byteArray
  5539. }
  5540. function utf16leToBytes (str, units) {
  5541. var c, hi, lo
  5542. var byteArray = []
  5543. for (var i = 0; i < str.length; ++i) {
  5544. if ((units -= 2) < 0) break
  5545. c = str.charCodeAt(i)
  5546. hi = c >> 8
  5547. lo = c % 256
  5548. byteArray.push(lo)
  5549. byteArray.push(hi)
  5550. }
  5551. return byteArray
  5552. }
  5553. function base64ToBytes (str) {
  5554. return base64.toByteArray(base64clean(str))
  5555. }
  5556. function blitBuffer (src, dst, offset, length) {
  5557. for (var i = 0; i < length; ++i) {
  5558. if ((i + offset >= dst.length) || (i >= src.length)) break
  5559. dst[i + offset] = src[i]
  5560. }
  5561. return i
  5562. }
  5563. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  5564. // the `instanceof` check but they should be treated as of that type.
  5565. // See: https://github.com/feross/buffer/issues/166
  5566. function isInstance (obj, type) {
  5567. return obj instanceof type ||
  5568. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  5569. obj.constructor.name === type.name)
  5570. }
  5571. function numberIsNaN (obj) {
  5572. // For IE11 support
  5573. return obj !== obj // eslint-disable-line no-self-compare
  5574. }
  5575. }).call(this,require("buffer").Buffer)
  5576. },{"base64-js":27,"buffer":32,"ieee754":35}],33:[function(require,module,exports){
  5577. (function (Buffer){
  5578. // Copyright Joyent, Inc. and other Node contributors.
  5579. //
  5580. // Permission is hereby granted, free of charge, to any person obtaining a
  5581. // copy of this software and associated documentation files (the
  5582. // "Software"), to deal in the Software without restriction, including
  5583. // without limitation the rights to use, copy, modify, merge, publish,
  5584. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5585. // persons to whom the Software is furnished to do so, subject to the
  5586. // following conditions:
  5587. //
  5588. // The above copyright notice and this permission notice shall be included
  5589. // in all copies or substantial portions of the Software.
  5590. //
  5591. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5592. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5593. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5594. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5595. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5596. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5597. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5598. // NOTE: These type checking functions intentionally don't use `instanceof`
  5599. // because it is fragile and can be easily faked with `Object.create()`.
  5600. function isArray(arg) {
  5601. if (Array.isArray) {
  5602. return Array.isArray(arg);
  5603. }
  5604. return objectToString(arg) === '[object Array]';
  5605. }
  5606. exports.isArray = isArray;
  5607. function isBoolean(arg) {
  5608. return typeof arg === 'boolean';
  5609. }
  5610. exports.isBoolean = isBoolean;
  5611. function isNull(arg) {
  5612. return arg === null;
  5613. }
  5614. exports.isNull = isNull;
  5615. function isNullOrUndefined(arg) {
  5616. return arg == null;
  5617. }
  5618. exports.isNullOrUndefined = isNullOrUndefined;
  5619. function isNumber(arg) {
  5620. return typeof arg === 'number';
  5621. }
  5622. exports.isNumber = isNumber;
  5623. function isString(arg) {
  5624. return typeof arg === 'string';
  5625. }
  5626. exports.isString = isString;
  5627. function isSymbol(arg) {
  5628. return typeof arg === 'symbol';
  5629. }
  5630. exports.isSymbol = isSymbol;
  5631. function isUndefined(arg) {
  5632. return arg === void 0;
  5633. }
  5634. exports.isUndefined = isUndefined;
  5635. function isRegExp(re) {
  5636. return objectToString(re) === '[object RegExp]';
  5637. }
  5638. exports.isRegExp = isRegExp;
  5639. function isObject(arg) {
  5640. return typeof arg === 'object' && arg !== null;
  5641. }
  5642. exports.isObject = isObject;
  5643. function isDate(d) {
  5644. return objectToString(d) === '[object Date]';
  5645. }
  5646. exports.isDate = isDate;
  5647. function isError(e) {
  5648. return (objectToString(e) === '[object Error]' || e instanceof Error);
  5649. }
  5650. exports.isError = isError;
  5651. function isFunction(arg) {
  5652. return typeof arg === 'function';
  5653. }
  5654. exports.isFunction = isFunction;
  5655. function isPrimitive(arg) {
  5656. return arg === null ||
  5657. typeof arg === 'boolean' ||
  5658. typeof arg === 'number' ||
  5659. typeof arg === 'string' ||
  5660. typeof arg === 'symbol' || // ES6 symbol
  5661. typeof arg === 'undefined';
  5662. }
  5663. exports.isPrimitive = isPrimitive;
  5664. exports.isBuffer = Buffer.isBuffer;
  5665. function objectToString(o) {
  5666. return Object.prototype.toString.call(o);
  5667. }
  5668. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  5669. },{"../../is-buffer/index.js":37}],34:[function(require,module,exports){
  5670. // Copyright Joyent, Inc. and other Node contributors.
  5671. //
  5672. // Permission is hereby granted, free of charge, to any person obtaining a
  5673. // copy of this software and associated documentation files (the
  5674. // "Software"), to deal in the Software without restriction, including
  5675. // without limitation the rights to use, copy, modify, merge, publish,
  5676. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5677. // persons to whom the Software is furnished to do so, subject to the
  5678. // following conditions:
  5679. //
  5680. // The above copyright notice and this permission notice shall be included
  5681. // in all copies or substantial portions of the Software.
  5682. //
  5683. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5684. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5685. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5686. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5687. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5688. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5689. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5690. function EventEmitter() {
  5691. this._events = this._events || {};
  5692. this._maxListeners = this._maxListeners || undefined;
  5693. }
  5694. module.exports = EventEmitter;
  5695. // Backwards-compat with node 0.10.x
  5696. EventEmitter.EventEmitter = EventEmitter;
  5697. EventEmitter.prototype._events = undefined;
  5698. EventEmitter.prototype._maxListeners = undefined;
  5699. // By default EventEmitters will print a warning if more than 10 listeners are
  5700. // added to it. This is a useful default which helps finding memory leaks.
  5701. EventEmitter.defaultMaxListeners = 10;
  5702. // Obviously not all Emitters should be limited to 10. This function allows
  5703. // that to be increased. Set to zero for unlimited.
  5704. EventEmitter.prototype.setMaxListeners = function(n) {
  5705. if (!isNumber(n) || n < 0 || isNaN(n))
  5706. throw TypeError('n must be a positive number');
  5707. this._maxListeners = n;
  5708. return this;
  5709. };
  5710. EventEmitter.prototype.emit = function(type) {
  5711. var er, handler, len, args, i, listeners;
  5712. if (!this._events)
  5713. this._events = {};
  5714. // If there is no 'error' event listener then throw.
  5715. if (type === 'error') {
  5716. if (!this._events.error ||
  5717. (isObject(this._events.error) && !this._events.error.length)) {
  5718. er = arguments[1];
  5719. if (er instanceof Error) {
  5720. throw er; // Unhandled 'error' event
  5721. } else {
  5722. // At least give some kind of context to the user
  5723. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  5724. err.context = er;
  5725. throw err;
  5726. }
  5727. }
  5728. }
  5729. handler = this._events[type];
  5730. if (isUndefined(handler))
  5731. return false;
  5732. if (isFunction(handler)) {
  5733. switch (arguments.length) {
  5734. // fast cases
  5735. case 1:
  5736. handler.call(this);
  5737. break;
  5738. case 2:
  5739. handler.call(this, arguments[1]);
  5740. break;
  5741. case 3:
  5742. handler.call(this, arguments[1], arguments[2]);
  5743. break;
  5744. // slower
  5745. default:
  5746. args = Array.prototype.slice.call(arguments, 1);
  5747. handler.apply(this, args);
  5748. }
  5749. } else if (isObject(handler)) {
  5750. args = Array.prototype.slice.call(arguments, 1);
  5751. listeners = handler.slice();
  5752. len = listeners.length;
  5753. for (i = 0; i < len; i++)
  5754. listeners[i].apply(this, args);
  5755. }
  5756. return true;
  5757. };
  5758. EventEmitter.prototype.addListener = function(type, listener) {
  5759. var m;
  5760. if (!isFunction(listener))
  5761. throw TypeError('listener must be a function');
  5762. if (!this._events)
  5763. this._events = {};
  5764. // To avoid recursion in the case that type === "newListener"! Before
  5765. // adding it to the listeners, first emit "newListener".
  5766. if (this._events.newListener)
  5767. this.emit('newListener', type,
  5768. isFunction(listener.listener) ?
  5769. listener.listener : listener);
  5770. if (!this._events[type])
  5771. // Optimize the case of one listener. Don't need the extra array object.
  5772. this._events[type] = listener;
  5773. else if (isObject(this._events[type]))
  5774. // If we've already got an array, just append.
  5775. this._events[type].push(listener);
  5776. else
  5777. // Adding the second element, need to change to array.
  5778. this._events[type] = [this._events[type], listener];
  5779. // Check for listener leak
  5780. if (isObject(this._events[type]) && !this._events[type].warned) {
  5781. if (!isUndefined(this._maxListeners)) {
  5782. m = this._maxListeners;
  5783. } else {
  5784. m = EventEmitter.defaultMaxListeners;
  5785. }
  5786. if (m && m > 0 && this._events[type].length > m) {
  5787. this._events[type].warned = true;
  5788. console.error('(node) warning: possible EventEmitter memory ' +
  5789. 'leak detected. %d listeners added. ' +
  5790. 'Use emitter.setMaxListeners() to increase limit.',
  5791. this._events[type].length);
  5792. if (typeof console.trace === 'function') {
  5793. // not supported in IE 10
  5794. console.trace();
  5795. }
  5796. }
  5797. }
  5798. return this;
  5799. };
  5800. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  5801. EventEmitter.prototype.once = function(type, listener) {
  5802. if (!isFunction(listener))
  5803. throw TypeError('listener must be a function');
  5804. var fired = false;
  5805. function g() {
  5806. this.removeListener(type, g);
  5807. if (!fired) {
  5808. fired = true;
  5809. listener.apply(this, arguments);
  5810. }
  5811. }
  5812. g.listener = listener;
  5813. this.on(type, g);
  5814. return this;
  5815. };
  5816. // emits a 'removeListener' event iff the listener was removed
  5817. EventEmitter.prototype.removeListener = function(type, listener) {
  5818. var list, position, length, i;
  5819. if (!isFunction(listener))
  5820. throw TypeError('listener must be a function');
  5821. if (!this._events || !this._events[type])
  5822. return this;
  5823. list = this._events[type];
  5824. length = list.length;
  5825. position = -1;
  5826. if (list === listener ||
  5827. (isFunction(list.listener) && list.listener === listener)) {
  5828. delete this._events[type];
  5829. if (this._events.removeListener)
  5830. this.emit('removeListener', type, listener);
  5831. } else if (isObject(list)) {
  5832. for (i = length; i-- > 0;) {
  5833. if (list[i] === listener ||
  5834. (list[i].listener && list[i].listener === listener)) {
  5835. position = i;
  5836. break;
  5837. }
  5838. }
  5839. if (position < 0)
  5840. return this;
  5841. if (list.length === 1) {
  5842. list.length = 0;
  5843. delete this._events[type];
  5844. } else {
  5845. list.splice(position, 1);
  5846. }
  5847. if (this._events.removeListener)
  5848. this.emit('removeListener', type, listener);
  5849. }
  5850. return this;
  5851. };
  5852. EventEmitter.prototype.removeAllListeners = function(type) {
  5853. var key, listeners;
  5854. if (!this._events)
  5855. return this;
  5856. // not listening for removeListener, no need to emit
  5857. if (!this._events.removeListener) {
  5858. if (arguments.length === 0)
  5859. this._events = {};
  5860. else if (this._events[type])
  5861. delete this._events[type];
  5862. return this;
  5863. }
  5864. // emit removeListener for all listeners on all events
  5865. if (arguments.length === 0) {
  5866. for (key in this._events) {
  5867. if (key === 'removeListener') continue;
  5868. this.removeAllListeners(key);
  5869. }
  5870. this.removeAllListeners('removeListener');
  5871. this._events = {};
  5872. return this;
  5873. }
  5874. listeners = this._events[type];
  5875. if (isFunction(listeners)) {
  5876. this.removeListener(type, listeners);
  5877. } else if (listeners) {
  5878. // LIFO order
  5879. while (listeners.length)
  5880. this.removeListener(type, listeners[listeners.length - 1]);
  5881. }
  5882. delete this._events[type];
  5883. return this;
  5884. };
  5885. EventEmitter.prototype.listeners = function(type) {
  5886. var ret;
  5887. if (!this._events || !this._events[type])
  5888. ret = [];
  5889. else if (isFunction(this._events[type]))
  5890. ret = [this._events[type]];
  5891. else
  5892. ret = this._events[type].slice();
  5893. return ret;
  5894. };
  5895. EventEmitter.prototype.listenerCount = function(type) {
  5896. if (this._events) {
  5897. var evlistener = this._events[type];
  5898. if (isFunction(evlistener))
  5899. return 1;
  5900. else if (evlistener)
  5901. return evlistener.length;
  5902. }
  5903. return 0;
  5904. };
  5905. EventEmitter.listenerCount = function(emitter, type) {
  5906. return emitter.listenerCount(type);
  5907. };
  5908. function isFunction(arg) {
  5909. return typeof arg === 'function';
  5910. }
  5911. function isNumber(arg) {
  5912. return typeof arg === 'number';
  5913. }
  5914. function isObject(arg) {
  5915. return typeof arg === 'object' && arg !== null;
  5916. }
  5917. function isUndefined(arg) {
  5918. return arg === void 0;
  5919. }
  5920. },{}],35:[function(require,module,exports){
  5921. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5922. var e, m
  5923. var eLen = (nBytes * 8) - mLen - 1
  5924. var eMax = (1 << eLen) - 1
  5925. var eBias = eMax >> 1
  5926. var nBits = -7
  5927. var i = isLE ? (nBytes - 1) : 0
  5928. var d = isLE ? -1 : 1
  5929. var s = buffer[offset + i]
  5930. i += d
  5931. e = s & ((1 << (-nBits)) - 1)
  5932. s >>= (-nBits)
  5933. nBits += eLen
  5934. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5935. m = e & ((1 << (-nBits)) - 1)
  5936. e >>= (-nBits)
  5937. nBits += mLen
  5938. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5939. if (e === 0) {
  5940. e = 1 - eBias
  5941. } else if (e === eMax) {
  5942. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5943. } else {
  5944. m = m + Math.pow(2, mLen)
  5945. e = e - eBias
  5946. }
  5947. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5948. }
  5949. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5950. var e, m, c
  5951. var eLen = (nBytes * 8) - mLen - 1
  5952. var eMax = (1 << eLen) - 1
  5953. var eBias = eMax >> 1
  5954. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5955. var i = isLE ? 0 : (nBytes - 1)
  5956. var d = isLE ? 1 : -1
  5957. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5958. value = Math.abs(value)
  5959. if (isNaN(value) || value === Infinity) {
  5960. m = isNaN(value) ? 1 : 0
  5961. e = eMax
  5962. } else {
  5963. e = Math.floor(Math.log(value) / Math.LN2)
  5964. if (value * (c = Math.pow(2, -e)) < 1) {
  5965. e--
  5966. c *= 2
  5967. }
  5968. if (e + eBias >= 1) {
  5969. value += rt / c
  5970. } else {
  5971. value += rt * Math.pow(2, 1 - eBias)
  5972. }
  5973. if (value * c >= 2) {
  5974. e++
  5975. c /= 2
  5976. }
  5977. if (e + eBias >= eMax) {
  5978. m = 0
  5979. e = eMax
  5980. } else if (e + eBias >= 1) {
  5981. m = ((value * c) - 1) * Math.pow(2, mLen)
  5982. e = e + eBias
  5983. } else {
  5984. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5985. e = 0
  5986. }
  5987. }
  5988. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5989. e = (e << mLen) | m
  5990. eLen += mLen
  5991. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5992. buffer[offset + i - d] |= s * 128
  5993. }
  5994. },{}],36:[function(require,module,exports){
  5995. arguments[4][24][0].apply(exports,arguments)
  5996. },{"dup":24}],37:[function(require,module,exports){
  5997. /*!
  5998. * Determine if an object is a Buffer
  5999. *
  6000. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  6001. * @license MIT
  6002. */
  6003. // The _isBuffer check is for Safari 5-7 support, because it's missing
  6004. // Object.prototype.constructor. Remove this eventually
  6005. module.exports = function (obj) {
  6006. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  6007. }
  6008. function isBuffer (obj) {
  6009. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  6010. }
  6011. // For Node v0.10 support. Remove this eventually.
  6012. function isSlowBuffer (obj) {
  6013. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  6014. }
  6015. },{}],38:[function(require,module,exports){
  6016. var toString = {}.toString;
  6017. module.exports = Array.isArray || function (arr) {
  6018. return toString.call(arr) == '[object Array]';
  6019. };
  6020. },{}],39:[function(require,module,exports){
  6021. 'use strict';
  6022. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  6023. (typeof Uint16Array !== 'undefined') &&
  6024. (typeof Int32Array !== 'undefined');
  6025. function _has(obj, key) {
  6026. return Object.prototype.hasOwnProperty.call(obj, key);
  6027. }
  6028. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  6029. var sources = Array.prototype.slice.call(arguments, 1);
  6030. while (sources.length) {
  6031. var source = sources.shift();
  6032. if (!source) { continue; }
  6033. if (typeof source !== 'object') {
  6034. throw new TypeError(source + 'must be non-object');
  6035. }
  6036. for (var p in source) {
  6037. if (_has(source, p)) {
  6038. obj[p] = source[p];
  6039. }
  6040. }
  6041. }
  6042. return obj;
  6043. };
  6044. // reduce buffer size, avoiding mem copy
  6045. exports.shrinkBuf = function (buf, size) {
  6046. if (buf.length === size) { return buf; }
  6047. if (buf.subarray) { return buf.subarray(0, size); }
  6048. buf.length = size;
  6049. return buf;
  6050. };
  6051. var fnTyped = {
  6052. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6053. if (src.subarray && dest.subarray) {
  6054. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  6055. return;
  6056. }
  6057. // Fallback to ordinary array
  6058. for (var i = 0; i < len; i++) {
  6059. dest[dest_offs + i] = src[src_offs + i];
  6060. }
  6061. },
  6062. // Join array of chunks to single array.
  6063. flattenChunks: function (chunks) {
  6064. var i, l, len, pos, chunk, result;
  6065. // calculate data length
  6066. len = 0;
  6067. for (i = 0, l = chunks.length; i < l; i++) {
  6068. len += chunks[i].length;
  6069. }
  6070. // join chunks
  6071. result = new Uint8Array(len);
  6072. pos = 0;
  6073. for (i = 0, l = chunks.length; i < l; i++) {
  6074. chunk = chunks[i];
  6075. result.set(chunk, pos);
  6076. pos += chunk.length;
  6077. }
  6078. return result;
  6079. }
  6080. };
  6081. var fnUntyped = {
  6082. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6083. for (var i = 0; i < len; i++) {
  6084. dest[dest_offs + i] = src[src_offs + i];
  6085. }
  6086. },
  6087. // Join array of chunks to single array.
  6088. flattenChunks: function (chunks) {
  6089. return [].concat.apply([], chunks);
  6090. }
  6091. };
  6092. // Enable/Disable typed arrays use, for testing
  6093. //
  6094. exports.setTyped = function (on) {
  6095. if (on) {
  6096. exports.Buf8 = Uint8Array;
  6097. exports.Buf16 = Uint16Array;
  6098. exports.Buf32 = Int32Array;
  6099. exports.assign(exports, fnTyped);
  6100. } else {
  6101. exports.Buf8 = Array;
  6102. exports.Buf16 = Array;
  6103. exports.Buf32 = Array;
  6104. exports.assign(exports, fnUntyped);
  6105. }
  6106. };
  6107. exports.setTyped(TYPED_OK);
  6108. },{}],40:[function(require,module,exports){
  6109. 'use strict';
  6110. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6111. // It isn't worth it to make additional optimizations as in original.
  6112. // Small size is preferable.
  6113. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6114. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6115. //
  6116. // This software is provided 'as-is', without any express or implied
  6117. // warranty. In no event will the authors be held liable for any damages
  6118. // arising from the use of this software.
  6119. //
  6120. // Permission is granted to anyone to use this software for any purpose,
  6121. // including commercial applications, and to alter it and redistribute it
  6122. // freely, subject to the following restrictions:
  6123. //
  6124. // 1. The origin of this software must not be misrepresented; you must not
  6125. // claim that you wrote the original software. If you use this software
  6126. // in a product, an acknowledgment in the product documentation would be
  6127. // appreciated but is not required.
  6128. // 2. Altered source versions must be plainly marked as such, and must not be
  6129. // misrepresented as being the original software.
  6130. // 3. This notice may not be removed or altered from any source distribution.
  6131. function adler32(adler, buf, len, pos) {
  6132. var s1 = (adler & 0xffff) |0,
  6133. s2 = ((adler >>> 16) & 0xffff) |0,
  6134. n = 0;
  6135. while (len !== 0) {
  6136. // Set limit ~ twice less than 5552, to keep
  6137. // s2 in 31-bits, because we force signed ints.
  6138. // in other case %= will fail.
  6139. n = len > 2000 ? 2000 : len;
  6140. len -= n;
  6141. do {
  6142. s1 = (s1 + buf[pos++]) |0;
  6143. s2 = (s2 + s1) |0;
  6144. } while (--n);
  6145. s1 %= 65521;
  6146. s2 %= 65521;
  6147. }
  6148. return (s1 | (s2 << 16)) |0;
  6149. }
  6150. module.exports = adler32;
  6151. },{}],41:[function(require,module,exports){
  6152. 'use strict';
  6153. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6154. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6155. //
  6156. // This software is provided 'as-is', without any express or implied
  6157. // warranty. In no event will the authors be held liable for any damages
  6158. // arising from the use of this software.
  6159. //
  6160. // Permission is granted to anyone to use this software for any purpose,
  6161. // including commercial applications, and to alter it and redistribute it
  6162. // freely, subject to the following restrictions:
  6163. //
  6164. // 1. The origin of this software must not be misrepresented; you must not
  6165. // claim that you wrote the original software. If you use this software
  6166. // in a product, an acknowledgment in the product documentation would be
  6167. // appreciated but is not required.
  6168. // 2. Altered source versions must be plainly marked as such, and must not be
  6169. // misrepresented as being the original software.
  6170. // 3. This notice may not be removed or altered from any source distribution.
  6171. module.exports = {
  6172. /* Allowed flush values; see deflate() and inflate() below for details */
  6173. Z_NO_FLUSH: 0,
  6174. Z_PARTIAL_FLUSH: 1,
  6175. Z_SYNC_FLUSH: 2,
  6176. Z_FULL_FLUSH: 3,
  6177. Z_FINISH: 4,
  6178. Z_BLOCK: 5,
  6179. Z_TREES: 6,
  6180. /* Return codes for the compression/decompression functions. Negative values
  6181. * are errors, positive values are used for special but normal events.
  6182. */
  6183. Z_OK: 0,
  6184. Z_STREAM_END: 1,
  6185. Z_NEED_DICT: 2,
  6186. Z_ERRNO: -1,
  6187. Z_STREAM_ERROR: -2,
  6188. Z_DATA_ERROR: -3,
  6189. //Z_MEM_ERROR: -4,
  6190. Z_BUF_ERROR: -5,
  6191. //Z_VERSION_ERROR: -6,
  6192. /* compression levels */
  6193. Z_NO_COMPRESSION: 0,
  6194. Z_BEST_SPEED: 1,
  6195. Z_BEST_COMPRESSION: 9,
  6196. Z_DEFAULT_COMPRESSION: -1,
  6197. Z_FILTERED: 1,
  6198. Z_HUFFMAN_ONLY: 2,
  6199. Z_RLE: 3,
  6200. Z_FIXED: 4,
  6201. Z_DEFAULT_STRATEGY: 0,
  6202. /* Possible values of the data_type field (though see inflate()) */
  6203. Z_BINARY: 0,
  6204. Z_TEXT: 1,
  6205. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6206. Z_UNKNOWN: 2,
  6207. /* The deflate compression method */
  6208. Z_DEFLATED: 8
  6209. //Z_NULL: null // Use -1 or null inline, depending on var type
  6210. };
  6211. },{}],42:[function(require,module,exports){
  6212. 'use strict';
  6213. // Note: we can't get significant speed boost here.
  6214. // So write code to minimize size - no pregenerated tables
  6215. // and array tools dependencies.
  6216. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6217. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6218. //
  6219. // This software is provided 'as-is', without any express or implied
  6220. // warranty. In no event will the authors be held liable for any damages
  6221. // arising from the use of this software.
  6222. //
  6223. // Permission is granted to anyone to use this software for any purpose,
  6224. // including commercial applications, and to alter it and redistribute it
  6225. // freely, subject to the following restrictions:
  6226. //
  6227. // 1. The origin of this software must not be misrepresented; you must not
  6228. // claim that you wrote the original software. If you use this software
  6229. // in a product, an acknowledgment in the product documentation would be
  6230. // appreciated but is not required.
  6231. // 2. Altered source versions must be plainly marked as such, and must not be
  6232. // misrepresented as being the original software.
  6233. // 3. This notice may not be removed or altered from any source distribution.
  6234. // Use ordinary array, since untyped makes no boost here
  6235. function makeTable() {
  6236. var c, table = [];
  6237. for (var n = 0; n < 256; n++) {
  6238. c = n;
  6239. for (var k = 0; k < 8; k++) {
  6240. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6241. }
  6242. table[n] = c;
  6243. }
  6244. return table;
  6245. }
  6246. // Create table on load. Just 255 signed longs. Not a problem.
  6247. var crcTable = makeTable();
  6248. function crc32(crc, buf, len, pos) {
  6249. var t = crcTable,
  6250. end = pos + len;
  6251. crc ^= -1;
  6252. for (var i = pos; i < end; i++) {
  6253. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6254. }
  6255. return (crc ^ (-1)); // >>> 0;
  6256. }
  6257. module.exports = crc32;
  6258. },{}],43:[function(require,module,exports){
  6259. 'use strict';
  6260. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6261. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6262. //
  6263. // This software is provided 'as-is', without any express or implied
  6264. // warranty. In no event will the authors be held liable for any damages
  6265. // arising from the use of this software.
  6266. //
  6267. // Permission is granted to anyone to use this software for any purpose,
  6268. // including commercial applications, and to alter it and redistribute it
  6269. // freely, subject to the following restrictions:
  6270. //
  6271. // 1. The origin of this software must not be misrepresented; you must not
  6272. // claim that you wrote the original software. If you use this software
  6273. // in a product, an acknowledgment in the product documentation would be
  6274. // appreciated but is not required.
  6275. // 2. Altered source versions must be plainly marked as such, and must not be
  6276. // misrepresented as being the original software.
  6277. // 3. This notice may not be removed or altered from any source distribution.
  6278. var utils = require('../utils/common');
  6279. var trees = require('./trees');
  6280. var adler32 = require('./adler32');
  6281. var crc32 = require('./crc32');
  6282. var msg = require('./messages');
  6283. /* Public constants ==========================================================*/
  6284. /* ===========================================================================*/
  6285. /* Allowed flush values; see deflate() and inflate() below for details */
  6286. var Z_NO_FLUSH = 0;
  6287. var Z_PARTIAL_FLUSH = 1;
  6288. //var Z_SYNC_FLUSH = 2;
  6289. var Z_FULL_FLUSH = 3;
  6290. var Z_FINISH = 4;
  6291. var Z_BLOCK = 5;
  6292. //var Z_TREES = 6;
  6293. /* Return codes for the compression/decompression functions. Negative values
  6294. * are errors, positive values are used for special but normal events.
  6295. */
  6296. var Z_OK = 0;
  6297. var Z_STREAM_END = 1;
  6298. //var Z_NEED_DICT = 2;
  6299. //var Z_ERRNO = -1;
  6300. var Z_STREAM_ERROR = -2;
  6301. var Z_DATA_ERROR = -3;
  6302. //var Z_MEM_ERROR = -4;
  6303. var Z_BUF_ERROR = -5;
  6304. //var Z_VERSION_ERROR = -6;
  6305. /* compression levels */
  6306. //var Z_NO_COMPRESSION = 0;
  6307. //var Z_BEST_SPEED = 1;
  6308. //var Z_BEST_COMPRESSION = 9;
  6309. var Z_DEFAULT_COMPRESSION = -1;
  6310. var Z_FILTERED = 1;
  6311. var Z_HUFFMAN_ONLY = 2;
  6312. var Z_RLE = 3;
  6313. var Z_FIXED = 4;
  6314. var Z_DEFAULT_STRATEGY = 0;
  6315. /* Possible values of the data_type field (though see inflate()) */
  6316. //var Z_BINARY = 0;
  6317. //var Z_TEXT = 1;
  6318. //var Z_ASCII = 1; // = Z_TEXT
  6319. var Z_UNKNOWN = 2;
  6320. /* The deflate compression method */
  6321. var Z_DEFLATED = 8;
  6322. /*============================================================================*/
  6323. var MAX_MEM_LEVEL = 9;
  6324. /* Maximum value for memLevel in deflateInit2 */
  6325. var MAX_WBITS = 15;
  6326. /* 32K LZ77 window */
  6327. var DEF_MEM_LEVEL = 8;
  6328. var LENGTH_CODES = 29;
  6329. /* number of length codes, not counting the special END_BLOCK code */
  6330. var LITERALS = 256;
  6331. /* number of literal bytes 0..255 */
  6332. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6333. /* number of Literal or Length codes, including the END_BLOCK code */
  6334. var D_CODES = 30;
  6335. /* number of distance codes */
  6336. var BL_CODES = 19;
  6337. /* number of codes used to transfer the bit lengths */
  6338. var HEAP_SIZE = 2 * L_CODES + 1;
  6339. /* maximum heap size */
  6340. var MAX_BITS = 15;
  6341. /* All codes must not exceed MAX_BITS bits */
  6342. var MIN_MATCH = 3;
  6343. var MAX_MATCH = 258;
  6344. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6345. var PRESET_DICT = 0x20;
  6346. var INIT_STATE = 42;
  6347. var EXTRA_STATE = 69;
  6348. var NAME_STATE = 73;
  6349. var COMMENT_STATE = 91;
  6350. var HCRC_STATE = 103;
  6351. var BUSY_STATE = 113;
  6352. var FINISH_STATE = 666;
  6353. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6354. var BS_BLOCK_DONE = 2; /* block flush performed */
  6355. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6356. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6357. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6358. function err(strm, errorCode) {
  6359. strm.msg = msg[errorCode];
  6360. return errorCode;
  6361. }
  6362. function rank(f) {
  6363. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6364. }
  6365. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6366. /* =========================================================================
  6367. * Flush as much pending output as possible. All deflate() output goes
  6368. * through this function so some applications may wish to modify it
  6369. * to avoid allocating a large strm->output buffer and copying into it.
  6370. * (See also read_buf()).
  6371. */
  6372. function flush_pending(strm) {
  6373. var s = strm.state;
  6374. //_tr_flush_bits(s);
  6375. var len = s.pending;
  6376. if (len > strm.avail_out) {
  6377. len = strm.avail_out;
  6378. }
  6379. if (len === 0) { return; }
  6380. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6381. strm.next_out += len;
  6382. s.pending_out += len;
  6383. strm.total_out += len;
  6384. strm.avail_out -= len;
  6385. s.pending -= len;
  6386. if (s.pending === 0) {
  6387. s.pending_out = 0;
  6388. }
  6389. }
  6390. function flush_block_only(s, last) {
  6391. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6392. s.block_start = s.strstart;
  6393. flush_pending(s.strm);
  6394. }
  6395. function put_byte(s, b) {
  6396. s.pending_buf[s.pending++] = b;
  6397. }
  6398. /* =========================================================================
  6399. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6400. * IN assertion: the stream state is correct and there is enough room in
  6401. * pending_buf.
  6402. */
  6403. function putShortMSB(s, b) {
  6404. // put_byte(s, (Byte)(b >> 8));
  6405. // put_byte(s, (Byte)(b & 0xff));
  6406. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6407. s.pending_buf[s.pending++] = b & 0xff;
  6408. }
  6409. /* ===========================================================================
  6410. * Read a new buffer from the current input stream, update the adler32
  6411. * and total number of bytes read. All deflate() input goes through
  6412. * this function so some applications may wish to modify it to avoid
  6413. * allocating a large strm->input buffer and copying from it.
  6414. * (See also flush_pending()).
  6415. */
  6416. function read_buf(strm, buf, start, size) {
  6417. var len = strm.avail_in;
  6418. if (len > size) { len = size; }
  6419. if (len === 0) { return 0; }
  6420. strm.avail_in -= len;
  6421. // zmemcpy(buf, strm->next_in, len);
  6422. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6423. if (strm.state.wrap === 1) {
  6424. strm.adler = adler32(strm.adler, buf, len, start);
  6425. }
  6426. else if (strm.state.wrap === 2) {
  6427. strm.adler = crc32(strm.adler, buf, len, start);
  6428. }
  6429. strm.next_in += len;
  6430. strm.total_in += len;
  6431. return len;
  6432. }
  6433. /* ===========================================================================
  6434. * Set match_start to the longest match starting at the given string and
  6435. * return its length. Matches shorter or equal to prev_length are discarded,
  6436. * in which case the result is equal to prev_length and match_start is
  6437. * garbage.
  6438. * IN assertions: cur_match is the head of the hash chain for the current
  6439. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6440. * OUT assertion: the match length is not greater than s->lookahead.
  6441. */
  6442. function longest_match(s, cur_match) {
  6443. var chain_length = s.max_chain_length; /* max hash chain length */
  6444. var scan = s.strstart; /* current string */
  6445. var match; /* matched string */
  6446. var len; /* length of current match */
  6447. var best_len = s.prev_length; /* best match length so far */
  6448. var nice_match = s.nice_match; /* stop if match long enough */
  6449. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6450. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6451. var _win = s.window; // shortcut
  6452. var wmask = s.w_mask;
  6453. var prev = s.prev;
  6454. /* Stop when cur_match becomes <= limit. To simplify the code,
  6455. * we prevent matches with the string of window index 0.
  6456. */
  6457. var strend = s.strstart + MAX_MATCH;
  6458. var scan_end1 = _win[scan + best_len - 1];
  6459. var scan_end = _win[scan + best_len];
  6460. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6461. * It is easy to get rid of this optimization if necessary.
  6462. */
  6463. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6464. /* Do not waste too much time if we already have a good match: */
  6465. if (s.prev_length >= s.good_match) {
  6466. chain_length >>= 2;
  6467. }
  6468. /* Do not look for matches beyond the end of the input. This is necessary
  6469. * to make deflate deterministic.
  6470. */
  6471. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6472. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6473. do {
  6474. // Assert(cur_match < s->strstart, "no future");
  6475. match = cur_match;
  6476. /* Skip to next match if the match length cannot increase
  6477. * or if the match length is less than 2. Note that the checks below
  6478. * for insufficient lookahead only occur occasionally for performance
  6479. * reasons. Therefore uninitialized memory will be accessed, and
  6480. * conditional jumps will be made that depend on those values.
  6481. * However the length of the match is limited to the lookahead, so
  6482. * the output of deflate is not affected by the uninitialized values.
  6483. */
  6484. if (_win[match + best_len] !== scan_end ||
  6485. _win[match + best_len - 1] !== scan_end1 ||
  6486. _win[match] !== _win[scan] ||
  6487. _win[++match] !== _win[scan + 1]) {
  6488. continue;
  6489. }
  6490. /* The check at best_len-1 can be removed because it will be made
  6491. * again later. (This heuristic is not always a win.)
  6492. * It is not necessary to compare scan[2] and match[2] since they
  6493. * are always equal when the other bytes match, given that
  6494. * the hash keys are equal and that HASH_BITS >= 8.
  6495. */
  6496. scan += 2;
  6497. match++;
  6498. // Assert(*scan == *match, "match[2]?");
  6499. /* We check for insufficient lookahead only every 8th comparison;
  6500. * the 256th check will be made at strstart+258.
  6501. */
  6502. do {
  6503. /*jshint noempty:false*/
  6504. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6505. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6506. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6507. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6508. scan < strend);
  6509. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6510. len = MAX_MATCH - (strend - scan);
  6511. scan = strend - MAX_MATCH;
  6512. if (len > best_len) {
  6513. s.match_start = cur_match;
  6514. best_len = len;
  6515. if (len >= nice_match) {
  6516. break;
  6517. }
  6518. scan_end1 = _win[scan + best_len - 1];
  6519. scan_end = _win[scan + best_len];
  6520. }
  6521. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6522. if (best_len <= s.lookahead) {
  6523. return best_len;
  6524. }
  6525. return s.lookahead;
  6526. }
  6527. /* ===========================================================================
  6528. * Fill the window when the lookahead becomes insufficient.
  6529. * Updates strstart and lookahead.
  6530. *
  6531. * IN assertion: lookahead < MIN_LOOKAHEAD
  6532. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6533. * At least one byte has been read, or avail_in == 0; reads are
  6534. * performed for at least two bytes (required for the zip translate_eol
  6535. * option -- not supported here).
  6536. */
  6537. function fill_window(s) {
  6538. var _w_size = s.w_size;
  6539. var p, n, m, more, str;
  6540. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6541. do {
  6542. more = s.window_size - s.lookahead - s.strstart;
  6543. // JS ints have 32 bit, block below not needed
  6544. /* Deal with !@#$% 64K limit: */
  6545. //if (sizeof(int) <= 2) {
  6546. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6547. // more = wsize;
  6548. //
  6549. // } else if (more == (unsigned)(-1)) {
  6550. // /* Very unlikely, but possible on 16 bit machine if
  6551. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6552. // */
  6553. // more--;
  6554. // }
  6555. //}
  6556. /* If the window is almost full and there is insufficient lookahead,
  6557. * move the upper half to the lower one to make room in the upper half.
  6558. */
  6559. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6560. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6561. s.match_start -= _w_size;
  6562. s.strstart -= _w_size;
  6563. /* we now have strstart >= MAX_DIST */
  6564. s.block_start -= _w_size;
  6565. /* Slide the hash table (could be avoided with 32 bit values
  6566. at the expense of memory usage). We slide even when level == 0
  6567. to keep the hash table consistent if we switch back to level > 0
  6568. later. (Using level 0 permanently is not an optimal usage of
  6569. zlib, so we don't care about this pathological case.)
  6570. */
  6571. n = s.hash_size;
  6572. p = n;
  6573. do {
  6574. m = s.head[--p];
  6575. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6576. } while (--n);
  6577. n = _w_size;
  6578. p = n;
  6579. do {
  6580. m = s.prev[--p];
  6581. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6582. /* If n is not on any hash chain, prev[n] is garbage but
  6583. * its value will never be used.
  6584. */
  6585. } while (--n);
  6586. more += _w_size;
  6587. }
  6588. if (s.strm.avail_in === 0) {
  6589. break;
  6590. }
  6591. /* If there was no sliding:
  6592. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6593. * more == window_size - lookahead - strstart
  6594. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6595. * => more >= window_size - 2*WSIZE + 2
  6596. * In the BIG_MEM or MMAP case (not yet supported),
  6597. * window_size == input_size + MIN_LOOKAHEAD &&
  6598. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6599. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6600. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6601. */
  6602. //Assert(more >= 2, "more < 2");
  6603. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6604. s.lookahead += n;
  6605. /* Initialize the hash value now that we have some input: */
  6606. if (s.lookahead + s.insert >= MIN_MATCH) {
  6607. str = s.strstart - s.insert;
  6608. s.ins_h = s.window[str];
  6609. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6610. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6611. //#if MIN_MATCH != 3
  6612. // Call update_hash() MIN_MATCH-3 more times
  6613. //#endif
  6614. while (s.insert) {
  6615. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6616. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6617. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6618. s.head[s.ins_h] = str;
  6619. str++;
  6620. s.insert--;
  6621. if (s.lookahead + s.insert < MIN_MATCH) {
  6622. break;
  6623. }
  6624. }
  6625. }
  6626. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6627. * but this is not important since only literal bytes will be emitted.
  6628. */
  6629. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6630. /* If the WIN_INIT bytes after the end of the current data have never been
  6631. * written, then zero those bytes in order to avoid memory check reports of
  6632. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6633. * the longest match routines. Update the high water mark for the next
  6634. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6635. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6636. */
  6637. // if (s.high_water < s.window_size) {
  6638. // var curr = s.strstart + s.lookahead;
  6639. // var init = 0;
  6640. //
  6641. // if (s.high_water < curr) {
  6642. // /* Previous high water mark below current data -- zero WIN_INIT
  6643. // * bytes or up to end of window, whichever is less.
  6644. // */
  6645. // init = s.window_size - curr;
  6646. // if (init > WIN_INIT)
  6647. // init = WIN_INIT;
  6648. // zmemzero(s->window + curr, (unsigned)init);
  6649. // s->high_water = curr + init;
  6650. // }
  6651. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6652. // /* High water mark at or above current data, but below current data
  6653. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6654. // * to end of window, whichever is less.
  6655. // */
  6656. // init = (ulg)curr + WIN_INIT - s->high_water;
  6657. // if (init > s->window_size - s->high_water)
  6658. // init = s->window_size - s->high_water;
  6659. // zmemzero(s->window + s->high_water, (unsigned)init);
  6660. // s->high_water += init;
  6661. // }
  6662. // }
  6663. //
  6664. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6665. // "not enough room for search");
  6666. }
  6667. /* ===========================================================================
  6668. * Copy without compression as much as possible from the input stream, return
  6669. * the current block state.
  6670. * This function does not insert new strings in the dictionary since
  6671. * uncompressible data is probably not useful. This function is used
  6672. * only for the level=0 compression option.
  6673. * NOTE: this function should be optimized to avoid extra copying from
  6674. * window to pending_buf.
  6675. */
  6676. function deflate_stored(s, flush) {
  6677. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6678. * to pending_buf_size, and each stored block has a 5 byte header:
  6679. */
  6680. var max_block_size = 0xffff;
  6681. if (max_block_size > s.pending_buf_size - 5) {
  6682. max_block_size = s.pending_buf_size - 5;
  6683. }
  6684. /* Copy as much as possible from input to output: */
  6685. for (;;) {
  6686. /* Fill the window as much as possible: */
  6687. if (s.lookahead <= 1) {
  6688. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6689. // s->block_start >= (long)s->w_size, "slide too late");
  6690. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6691. // s.block_start >= s.w_size)) {
  6692. // throw new Error("slide too late");
  6693. // }
  6694. fill_window(s);
  6695. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6696. return BS_NEED_MORE;
  6697. }
  6698. if (s.lookahead === 0) {
  6699. break;
  6700. }
  6701. /* flush the current block */
  6702. }
  6703. //Assert(s->block_start >= 0L, "block gone");
  6704. // if (s.block_start < 0) throw new Error("block gone");
  6705. s.strstart += s.lookahead;
  6706. s.lookahead = 0;
  6707. /* Emit a stored block if pending_buf will be full: */
  6708. var max_start = s.block_start + max_block_size;
  6709. if (s.strstart === 0 || s.strstart >= max_start) {
  6710. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6711. s.lookahead = s.strstart - max_start;
  6712. s.strstart = max_start;
  6713. /*** FLUSH_BLOCK(s, 0); ***/
  6714. flush_block_only(s, false);
  6715. if (s.strm.avail_out === 0) {
  6716. return BS_NEED_MORE;
  6717. }
  6718. /***/
  6719. }
  6720. /* Flush if we may have to slide, otherwise block_start may become
  6721. * negative and the data will be gone:
  6722. */
  6723. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6724. /*** FLUSH_BLOCK(s, 0); ***/
  6725. flush_block_only(s, false);
  6726. if (s.strm.avail_out === 0) {
  6727. return BS_NEED_MORE;
  6728. }
  6729. /***/
  6730. }
  6731. }
  6732. s.insert = 0;
  6733. if (flush === Z_FINISH) {
  6734. /*** FLUSH_BLOCK(s, 1); ***/
  6735. flush_block_only(s, true);
  6736. if (s.strm.avail_out === 0) {
  6737. return BS_FINISH_STARTED;
  6738. }
  6739. /***/
  6740. return BS_FINISH_DONE;
  6741. }
  6742. if (s.strstart > s.block_start) {
  6743. /*** FLUSH_BLOCK(s, 0); ***/
  6744. flush_block_only(s, false);
  6745. if (s.strm.avail_out === 0) {
  6746. return BS_NEED_MORE;
  6747. }
  6748. /***/
  6749. }
  6750. return BS_NEED_MORE;
  6751. }
  6752. /* ===========================================================================
  6753. * Compress as much as possible from the input stream, return the current
  6754. * block state.
  6755. * This function does not perform lazy evaluation of matches and inserts
  6756. * new strings in the dictionary only for unmatched strings or for short
  6757. * matches. It is used only for the fast compression options.
  6758. */
  6759. function deflate_fast(s, flush) {
  6760. var hash_head; /* head of the hash chain */
  6761. var bflush; /* set if current block must be flushed */
  6762. for (;;) {
  6763. /* Make sure that we always have enough lookahead, except
  6764. * at the end of the input file. We need MAX_MATCH bytes
  6765. * for the next match, plus MIN_MATCH bytes to insert the
  6766. * string following the next match.
  6767. */
  6768. if (s.lookahead < MIN_LOOKAHEAD) {
  6769. fill_window(s);
  6770. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6771. return BS_NEED_MORE;
  6772. }
  6773. if (s.lookahead === 0) {
  6774. break; /* flush the current block */
  6775. }
  6776. }
  6777. /* Insert the string window[strstart .. strstart+2] in the
  6778. * dictionary, and set hash_head to the head of the hash chain:
  6779. */
  6780. hash_head = 0/*NIL*/;
  6781. if (s.lookahead >= MIN_MATCH) {
  6782. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6783. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6784. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6785. s.head[s.ins_h] = s.strstart;
  6786. /***/
  6787. }
  6788. /* Find the longest match, discarding those <= prev_length.
  6789. * At this point we have always match_length < MIN_MATCH
  6790. */
  6791. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6792. /* To simplify the code, we prevent matches with the string
  6793. * of window index 0 (in particular we have to avoid a match
  6794. * of the string with itself at the start of the input file).
  6795. */
  6796. s.match_length = longest_match(s, hash_head);
  6797. /* longest_match() sets match_start */
  6798. }
  6799. if (s.match_length >= MIN_MATCH) {
  6800. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6801. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6802. s.match_length - MIN_MATCH, bflush); ***/
  6803. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6804. s.lookahead -= s.match_length;
  6805. /* Insert new strings in the hash table only if the match length
  6806. * is not too large. This saves time but degrades compression.
  6807. */
  6808. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6809. s.match_length--; /* string at strstart already in table */
  6810. do {
  6811. s.strstart++;
  6812. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6813. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6814. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6815. s.head[s.ins_h] = s.strstart;
  6816. /***/
  6817. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6818. * always MIN_MATCH bytes ahead.
  6819. */
  6820. } while (--s.match_length !== 0);
  6821. s.strstart++;
  6822. } else
  6823. {
  6824. s.strstart += s.match_length;
  6825. s.match_length = 0;
  6826. s.ins_h = s.window[s.strstart];
  6827. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6828. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6829. //#if MIN_MATCH != 3
  6830. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6831. //#endif
  6832. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6833. * matter since it will be recomputed at next deflate call.
  6834. */
  6835. }
  6836. } else {
  6837. /* No match, output a literal byte */
  6838. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6839. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6840. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6841. s.lookahead--;
  6842. s.strstart++;
  6843. }
  6844. if (bflush) {
  6845. /*** FLUSH_BLOCK(s, 0); ***/
  6846. flush_block_only(s, false);
  6847. if (s.strm.avail_out === 0) {
  6848. return BS_NEED_MORE;
  6849. }
  6850. /***/
  6851. }
  6852. }
  6853. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6854. if (flush === Z_FINISH) {
  6855. /*** FLUSH_BLOCK(s, 1); ***/
  6856. flush_block_only(s, true);
  6857. if (s.strm.avail_out === 0) {
  6858. return BS_FINISH_STARTED;
  6859. }
  6860. /***/
  6861. return BS_FINISH_DONE;
  6862. }
  6863. if (s.last_lit) {
  6864. /*** FLUSH_BLOCK(s, 0); ***/
  6865. flush_block_only(s, false);
  6866. if (s.strm.avail_out === 0) {
  6867. return BS_NEED_MORE;
  6868. }
  6869. /***/
  6870. }
  6871. return BS_BLOCK_DONE;
  6872. }
  6873. /* ===========================================================================
  6874. * Same as above, but achieves better compression. We use a lazy
  6875. * evaluation for matches: a match is finally adopted only if there is
  6876. * no better match at the next window position.
  6877. */
  6878. function deflate_slow(s, flush) {
  6879. var hash_head; /* head of hash chain */
  6880. var bflush; /* set if current block must be flushed */
  6881. var max_insert;
  6882. /* Process the input block. */
  6883. for (;;) {
  6884. /* Make sure that we always have enough lookahead, except
  6885. * at the end of the input file. We need MAX_MATCH bytes
  6886. * for the next match, plus MIN_MATCH bytes to insert the
  6887. * string following the next match.
  6888. */
  6889. if (s.lookahead < MIN_LOOKAHEAD) {
  6890. fill_window(s);
  6891. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6892. return BS_NEED_MORE;
  6893. }
  6894. if (s.lookahead === 0) { break; } /* flush the current block */
  6895. }
  6896. /* Insert the string window[strstart .. strstart+2] in the
  6897. * dictionary, and set hash_head to the head of the hash chain:
  6898. */
  6899. hash_head = 0/*NIL*/;
  6900. if (s.lookahead >= MIN_MATCH) {
  6901. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6902. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6903. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6904. s.head[s.ins_h] = s.strstart;
  6905. /***/
  6906. }
  6907. /* Find the longest match, discarding those <= prev_length.
  6908. */
  6909. s.prev_length = s.match_length;
  6910. s.prev_match = s.match_start;
  6911. s.match_length = MIN_MATCH - 1;
  6912. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6913. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6914. /* To simplify the code, we prevent matches with the string
  6915. * of window index 0 (in particular we have to avoid a match
  6916. * of the string with itself at the start of the input file).
  6917. */
  6918. s.match_length = longest_match(s, hash_head);
  6919. /* longest_match() sets match_start */
  6920. if (s.match_length <= 5 &&
  6921. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6922. /* If prev_match is also MIN_MATCH, match_start is garbage
  6923. * but we will ignore the current match anyway.
  6924. */
  6925. s.match_length = MIN_MATCH - 1;
  6926. }
  6927. }
  6928. /* If there was a match at the previous step and the current
  6929. * match is not better, output the previous match:
  6930. */
  6931. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6932. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6933. /* Do not insert strings in hash table beyond this. */
  6934. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6935. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6936. s.prev_length - MIN_MATCH, bflush);***/
  6937. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6938. /* Insert in hash table all strings up to the end of the match.
  6939. * strstart-1 and strstart are already inserted. If there is not
  6940. * enough lookahead, the last two strings are not inserted in
  6941. * the hash table.
  6942. */
  6943. s.lookahead -= s.prev_length - 1;
  6944. s.prev_length -= 2;
  6945. do {
  6946. if (++s.strstart <= max_insert) {
  6947. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6948. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6949. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6950. s.head[s.ins_h] = s.strstart;
  6951. /***/
  6952. }
  6953. } while (--s.prev_length !== 0);
  6954. s.match_available = 0;
  6955. s.match_length = MIN_MATCH - 1;
  6956. s.strstart++;
  6957. if (bflush) {
  6958. /*** FLUSH_BLOCK(s, 0); ***/
  6959. flush_block_only(s, false);
  6960. if (s.strm.avail_out === 0) {
  6961. return BS_NEED_MORE;
  6962. }
  6963. /***/
  6964. }
  6965. } else if (s.match_available) {
  6966. /* If there was no match at the previous position, output a
  6967. * single literal. If there was a match but the current match
  6968. * is longer, truncate the previous match to a single literal.
  6969. */
  6970. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6971. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6972. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6973. if (bflush) {
  6974. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6975. flush_block_only(s, false);
  6976. /***/
  6977. }
  6978. s.strstart++;
  6979. s.lookahead--;
  6980. if (s.strm.avail_out === 0) {
  6981. return BS_NEED_MORE;
  6982. }
  6983. } else {
  6984. /* There is no previous match to compare with, wait for
  6985. * the next step to decide.
  6986. */
  6987. s.match_available = 1;
  6988. s.strstart++;
  6989. s.lookahead--;
  6990. }
  6991. }
  6992. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6993. if (s.match_available) {
  6994. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6995. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6996. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6997. s.match_available = 0;
  6998. }
  6999. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  7000. if (flush === Z_FINISH) {
  7001. /*** FLUSH_BLOCK(s, 1); ***/
  7002. flush_block_only(s, true);
  7003. if (s.strm.avail_out === 0) {
  7004. return BS_FINISH_STARTED;
  7005. }
  7006. /***/
  7007. return BS_FINISH_DONE;
  7008. }
  7009. if (s.last_lit) {
  7010. /*** FLUSH_BLOCK(s, 0); ***/
  7011. flush_block_only(s, false);
  7012. if (s.strm.avail_out === 0) {
  7013. return BS_NEED_MORE;
  7014. }
  7015. /***/
  7016. }
  7017. return BS_BLOCK_DONE;
  7018. }
  7019. /* ===========================================================================
  7020. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  7021. * one. Do not maintain a hash table. (It will be regenerated if this run of
  7022. * deflate switches away from Z_RLE.)
  7023. */
  7024. function deflate_rle(s, flush) {
  7025. var bflush; /* set if current block must be flushed */
  7026. var prev; /* byte at distance one to match */
  7027. var scan, strend; /* scan goes up to strend for length of run */
  7028. var _win = s.window;
  7029. for (;;) {
  7030. /* Make sure that we always have enough lookahead, except
  7031. * at the end of the input file. We need MAX_MATCH bytes
  7032. * for the longest run, plus one for the unrolled loop.
  7033. */
  7034. if (s.lookahead <= MAX_MATCH) {
  7035. fill_window(s);
  7036. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7037. return BS_NEED_MORE;
  7038. }
  7039. if (s.lookahead === 0) { break; } /* flush the current block */
  7040. }
  7041. /* See how many times the previous byte repeats */
  7042. s.match_length = 0;
  7043. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7044. scan = s.strstart - 1;
  7045. prev = _win[scan];
  7046. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7047. strend = s.strstart + MAX_MATCH;
  7048. do {
  7049. /*jshint noempty:false*/
  7050. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7051. prev === _win[++scan] && prev === _win[++scan] &&
  7052. prev === _win[++scan] && prev === _win[++scan] &&
  7053. prev === _win[++scan] && prev === _win[++scan] &&
  7054. scan < strend);
  7055. s.match_length = MAX_MATCH - (strend - scan);
  7056. if (s.match_length > s.lookahead) {
  7057. s.match_length = s.lookahead;
  7058. }
  7059. }
  7060. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7061. }
  7062. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7063. if (s.match_length >= MIN_MATCH) {
  7064. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7065. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7066. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7067. s.lookahead -= s.match_length;
  7068. s.strstart += s.match_length;
  7069. s.match_length = 0;
  7070. } else {
  7071. /* No match, output a literal byte */
  7072. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7073. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7074. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7075. s.lookahead--;
  7076. s.strstart++;
  7077. }
  7078. if (bflush) {
  7079. /*** FLUSH_BLOCK(s, 0); ***/
  7080. flush_block_only(s, false);
  7081. if (s.strm.avail_out === 0) {
  7082. return BS_NEED_MORE;
  7083. }
  7084. /***/
  7085. }
  7086. }
  7087. s.insert = 0;
  7088. if (flush === Z_FINISH) {
  7089. /*** FLUSH_BLOCK(s, 1); ***/
  7090. flush_block_only(s, true);
  7091. if (s.strm.avail_out === 0) {
  7092. return BS_FINISH_STARTED;
  7093. }
  7094. /***/
  7095. return BS_FINISH_DONE;
  7096. }
  7097. if (s.last_lit) {
  7098. /*** FLUSH_BLOCK(s, 0); ***/
  7099. flush_block_only(s, false);
  7100. if (s.strm.avail_out === 0) {
  7101. return BS_NEED_MORE;
  7102. }
  7103. /***/
  7104. }
  7105. return BS_BLOCK_DONE;
  7106. }
  7107. /* ===========================================================================
  7108. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7109. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7110. */
  7111. function deflate_huff(s, flush) {
  7112. var bflush; /* set if current block must be flushed */
  7113. for (;;) {
  7114. /* Make sure that we have a literal to write. */
  7115. if (s.lookahead === 0) {
  7116. fill_window(s);
  7117. if (s.lookahead === 0) {
  7118. if (flush === Z_NO_FLUSH) {
  7119. return BS_NEED_MORE;
  7120. }
  7121. break; /* flush the current block */
  7122. }
  7123. }
  7124. /* Output a literal byte */
  7125. s.match_length = 0;
  7126. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7127. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7128. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7129. s.lookahead--;
  7130. s.strstart++;
  7131. if (bflush) {
  7132. /*** FLUSH_BLOCK(s, 0); ***/
  7133. flush_block_only(s, false);
  7134. if (s.strm.avail_out === 0) {
  7135. return BS_NEED_MORE;
  7136. }
  7137. /***/
  7138. }
  7139. }
  7140. s.insert = 0;
  7141. if (flush === Z_FINISH) {
  7142. /*** FLUSH_BLOCK(s, 1); ***/
  7143. flush_block_only(s, true);
  7144. if (s.strm.avail_out === 0) {
  7145. return BS_FINISH_STARTED;
  7146. }
  7147. /***/
  7148. return BS_FINISH_DONE;
  7149. }
  7150. if (s.last_lit) {
  7151. /*** FLUSH_BLOCK(s, 0); ***/
  7152. flush_block_only(s, false);
  7153. if (s.strm.avail_out === 0) {
  7154. return BS_NEED_MORE;
  7155. }
  7156. /***/
  7157. }
  7158. return BS_BLOCK_DONE;
  7159. }
  7160. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7161. * the desired pack level (0..9). The values given below have been tuned to
  7162. * exclude worst case performance for pathological files. Better values may be
  7163. * found for specific files.
  7164. */
  7165. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7166. this.good_length = good_length;
  7167. this.max_lazy = max_lazy;
  7168. this.nice_length = nice_length;
  7169. this.max_chain = max_chain;
  7170. this.func = func;
  7171. }
  7172. var configuration_table;
  7173. configuration_table = [
  7174. /* good lazy nice chain */
  7175. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7176. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7177. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7178. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7179. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7180. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7181. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7182. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7183. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7184. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7185. ];
  7186. /* ===========================================================================
  7187. * Initialize the "longest match" routines for a new zlib stream
  7188. */
  7189. function lm_init(s) {
  7190. s.window_size = 2 * s.w_size;
  7191. /*** CLEAR_HASH(s); ***/
  7192. zero(s.head); // Fill with NIL (= 0);
  7193. /* Set the default configuration parameters:
  7194. */
  7195. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7196. s.good_match = configuration_table[s.level].good_length;
  7197. s.nice_match = configuration_table[s.level].nice_length;
  7198. s.max_chain_length = configuration_table[s.level].max_chain;
  7199. s.strstart = 0;
  7200. s.block_start = 0;
  7201. s.lookahead = 0;
  7202. s.insert = 0;
  7203. s.match_length = s.prev_length = MIN_MATCH - 1;
  7204. s.match_available = 0;
  7205. s.ins_h = 0;
  7206. }
  7207. function DeflateState() {
  7208. this.strm = null; /* pointer back to this zlib stream */
  7209. this.status = 0; /* as the name implies */
  7210. this.pending_buf = null; /* output still pending */
  7211. this.pending_buf_size = 0; /* size of pending_buf */
  7212. this.pending_out = 0; /* next pending byte to output to the stream */
  7213. this.pending = 0; /* nb of bytes in the pending buffer */
  7214. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7215. this.gzhead = null; /* gzip header information to write */
  7216. this.gzindex = 0; /* where in extra, name, or comment */
  7217. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7218. this.last_flush = -1; /* value of flush param for previous deflate call */
  7219. this.w_size = 0; /* LZ77 window size (32K by default) */
  7220. this.w_bits = 0; /* log2(w_size) (8..16) */
  7221. this.w_mask = 0; /* w_size - 1 */
  7222. this.window = null;
  7223. /* Sliding window. Input bytes are read into the second half of the window,
  7224. * and move to the first half later to keep a dictionary of at least wSize
  7225. * bytes. With this organization, matches are limited to a distance of
  7226. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7227. * performed with a length multiple of the block size.
  7228. */
  7229. this.window_size = 0;
  7230. /* Actual size of window: 2*wSize, except when the user input buffer
  7231. * is directly used as sliding window.
  7232. */
  7233. this.prev = null;
  7234. /* Link to older string with same hash index. To limit the size of this
  7235. * array to 64K, this link is maintained only for the last 32K strings.
  7236. * An index in this array is thus a window index modulo 32K.
  7237. */
  7238. this.head = null; /* Heads of the hash chains or NIL. */
  7239. this.ins_h = 0; /* hash index of string to be inserted */
  7240. this.hash_size = 0; /* number of elements in hash table */
  7241. this.hash_bits = 0; /* log2(hash_size) */
  7242. this.hash_mask = 0; /* hash_size-1 */
  7243. this.hash_shift = 0;
  7244. /* Number of bits by which ins_h must be shifted at each input
  7245. * step. It must be such that after MIN_MATCH steps, the oldest
  7246. * byte no longer takes part in the hash key, that is:
  7247. * hash_shift * MIN_MATCH >= hash_bits
  7248. */
  7249. this.block_start = 0;
  7250. /* Window position at the beginning of the current output block. Gets
  7251. * negative when the window is moved backwards.
  7252. */
  7253. this.match_length = 0; /* length of best match */
  7254. this.prev_match = 0; /* previous match */
  7255. this.match_available = 0; /* set if previous match exists */
  7256. this.strstart = 0; /* start of string to insert */
  7257. this.match_start = 0; /* start of matching string */
  7258. this.lookahead = 0; /* number of valid bytes ahead in window */
  7259. this.prev_length = 0;
  7260. /* Length of the best match at previous step. Matches not greater than this
  7261. * are discarded. This is used in the lazy match evaluation.
  7262. */
  7263. this.max_chain_length = 0;
  7264. /* To speed up deflation, hash chains are never searched beyond this
  7265. * length. A higher limit improves compression ratio but degrades the
  7266. * speed.
  7267. */
  7268. this.max_lazy_match = 0;
  7269. /* Attempt to find a better match only when the current match is strictly
  7270. * smaller than this value. This mechanism is used only for compression
  7271. * levels >= 4.
  7272. */
  7273. // That's alias to max_lazy_match, don't use directly
  7274. //this.max_insert_length = 0;
  7275. /* Insert new strings in the hash table only if the match length is not
  7276. * greater than this length. This saves time but degrades compression.
  7277. * max_insert_length is used only for compression levels <= 3.
  7278. */
  7279. this.level = 0; /* compression level (1..9) */
  7280. this.strategy = 0; /* favor or force Huffman coding*/
  7281. this.good_match = 0;
  7282. /* Use a faster search when the previous match is longer than this */
  7283. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7284. /* used by trees.c: */
  7285. /* Didn't use ct_data typedef below to suppress compiler warning */
  7286. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7287. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7288. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7289. // Use flat array of DOUBLE size, with interleaved fata,
  7290. // because JS does not support effective
  7291. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7292. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7293. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7294. zero(this.dyn_ltree);
  7295. zero(this.dyn_dtree);
  7296. zero(this.bl_tree);
  7297. this.l_desc = null; /* desc. for literal tree */
  7298. this.d_desc = null; /* desc. for distance tree */
  7299. this.bl_desc = null; /* desc. for bit length tree */
  7300. //ush bl_count[MAX_BITS+1];
  7301. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7302. /* number of codes at each bit length for an optimal tree */
  7303. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7304. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7305. zero(this.heap);
  7306. this.heap_len = 0; /* number of elements in the heap */
  7307. this.heap_max = 0; /* element of largest frequency */
  7308. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7309. * The same heap array is used to build all trees.
  7310. */
  7311. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7312. zero(this.depth);
  7313. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7314. */
  7315. this.l_buf = 0; /* buffer index for literals or lengths */
  7316. this.lit_bufsize = 0;
  7317. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7318. * limiting lit_bufsize to 64K:
  7319. * - frequencies can be kept in 16 bit counters
  7320. * - if compression is not successful for the first block, all input
  7321. * data is still in the window so we can still emit a stored block even
  7322. * when input comes from standard input. (This can also be done for
  7323. * all blocks if lit_bufsize is not greater than 32K.)
  7324. * - if compression is not successful for a file smaller than 64K, we can
  7325. * even emit a stored file instead of a stored block (saving 5 bytes).
  7326. * This is applicable only for zip (not gzip or zlib).
  7327. * - creating new Huffman trees less frequently may not provide fast
  7328. * adaptation to changes in the input data statistics. (Take for
  7329. * example a binary file with poorly compressible code followed by
  7330. * a highly compressible string table.) Smaller buffer sizes give
  7331. * fast adaptation but have of course the overhead of transmitting
  7332. * trees more frequently.
  7333. * - I can't count above 4
  7334. */
  7335. this.last_lit = 0; /* running index in l_buf */
  7336. this.d_buf = 0;
  7337. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7338. * the same number of elements. To use different lengths, an extra flag
  7339. * array would be necessary.
  7340. */
  7341. this.opt_len = 0; /* bit length of current block with optimal trees */
  7342. this.static_len = 0; /* bit length of current block with static trees */
  7343. this.matches = 0; /* number of string matches in current block */
  7344. this.insert = 0; /* bytes at end of window left to insert */
  7345. this.bi_buf = 0;
  7346. /* Output buffer. bits are inserted starting at the bottom (least
  7347. * significant bits).
  7348. */
  7349. this.bi_valid = 0;
  7350. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7351. * are always zero.
  7352. */
  7353. // Used for window memory init. We safely ignore it for JS. That makes
  7354. // sense only for pointers and memory check tools.
  7355. //this.high_water = 0;
  7356. /* High water mark offset in window for initialized bytes -- bytes above
  7357. * this are set to zero in order to avoid memory check warnings when
  7358. * longest match routines access bytes past the input. This is then
  7359. * updated to the new high water mark.
  7360. */
  7361. }
  7362. function deflateResetKeep(strm) {
  7363. var s;
  7364. if (!strm || !strm.state) {
  7365. return err(strm, Z_STREAM_ERROR);
  7366. }
  7367. strm.total_in = strm.total_out = 0;
  7368. strm.data_type = Z_UNKNOWN;
  7369. s = strm.state;
  7370. s.pending = 0;
  7371. s.pending_out = 0;
  7372. if (s.wrap < 0) {
  7373. s.wrap = -s.wrap;
  7374. /* was made negative by deflate(..., Z_FINISH); */
  7375. }
  7376. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7377. strm.adler = (s.wrap === 2) ?
  7378. 0 // crc32(0, Z_NULL, 0)
  7379. :
  7380. 1; // adler32(0, Z_NULL, 0)
  7381. s.last_flush = Z_NO_FLUSH;
  7382. trees._tr_init(s);
  7383. return Z_OK;
  7384. }
  7385. function deflateReset(strm) {
  7386. var ret = deflateResetKeep(strm);
  7387. if (ret === Z_OK) {
  7388. lm_init(strm.state);
  7389. }
  7390. return ret;
  7391. }
  7392. function deflateSetHeader(strm, head) {
  7393. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7394. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7395. strm.state.gzhead = head;
  7396. return Z_OK;
  7397. }
  7398. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7399. if (!strm) { // === Z_NULL
  7400. return Z_STREAM_ERROR;
  7401. }
  7402. var wrap = 1;
  7403. if (level === Z_DEFAULT_COMPRESSION) {
  7404. level = 6;
  7405. }
  7406. if (windowBits < 0) { /* suppress zlib wrapper */
  7407. wrap = 0;
  7408. windowBits = -windowBits;
  7409. }
  7410. else if (windowBits > 15) {
  7411. wrap = 2; /* write gzip wrapper instead */
  7412. windowBits -= 16;
  7413. }
  7414. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7415. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7416. strategy < 0 || strategy > Z_FIXED) {
  7417. return err(strm, Z_STREAM_ERROR);
  7418. }
  7419. if (windowBits === 8) {
  7420. windowBits = 9;
  7421. }
  7422. /* until 256-byte window bug fixed */
  7423. var s = new DeflateState();
  7424. strm.state = s;
  7425. s.strm = strm;
  7426. s.wrap = wrap;
  7427. s.gzhead = null;
  7428. s.w_bits = windowBits;
  7429. s.w_size = 1 << s.w_bits;
  7430. s.w_mask = s.w_size - 1;
  7431. s.hash_bits = memLevel + 7;
  7432. s.hash_size = 1 << s.hash_bits;
  7433. s.hash_mask = s.hash_size - 1;
  7434. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7435. s.window = new utils.Buf8(s.w_size * 2);
  7436. s.head = new utils.Buf16(s.hash_size);
  7437. s.prev = new utils.Buf16(s.w_size);
  7438. // Don't need mem init magic for JS.
  7439. //s.high_water = 0; /* nothing written to s->window yet */
  7440. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7441. s.pending_buf_size = s.lit_bufsize * 4;
  7442. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7443. //s->pending_buf = (uchf *) overlay;
  7444. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7445. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7446. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7447. s.d_buf = 1 * s.lit_bufsize;
  7448. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7449. s.l_buf = (1 + 2) * s.lit_bufsize;
  7450. s.level = level;
  7451. s.strategy = strategy;
  7452. s.method = method;
  7453. return deflateReset(strm);
  7454. }
  7455. function deflateInit(strm, level) {
  7456. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7457. }
  7458. function deflate(strm, flush) {
  7459. var old_flush, s;
  7460. var beg, val; // for gzip header write only
  7461. if (!strm || !strm.state ||
  7462. flush > Z_BLOCK || flush < 0) {
  7463. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7464. }
  7465. s = strm.state;
  7466. if (!strm.output ||
  7467. (!strm.input && strm.avail_in !== 0) ||
  7468. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7469. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7470. }
  7471. s.strm = strm; /* just in case */
  7472. old_flush = s.last_flush;
  7473. s.last_flush = flush;
  7474. /* Write the header */
  7475. if (s.status === INIT_STATE) {
  7476. if (s.wrap === 2) { // GZIP header
  7477. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7478. put_byte(s, 31);
  7479. put_byte(s, 139);
  7480. put_byte(s, 8);
  7481. if (!s.gzhead) { // s->gzhead == Z_NULL
  7482. put_byte(s, 0);
  7483. put_byte(s, 0);
  7484. put_byte(s, 0);
  7485. put_byte(s, 0);
  7486. put_byte(s, 0);
  7487. put_byte(s, s.level === 9 ? 2 :
  7488. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7489. 4 : 0));
  7490. put_byte(s, OS_CODE);
  7491. s.status = BUSY_STATE;
  7492. }
  7493. else {
  7494. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7495. (s.gzhead.hcrc ? 2 : 0) +
  7496. (!s.gzhead.extra ? 0 : 4) +
  7497. (!s.gzhead.name ? 0 : 8) +
  7498. (!s.gzhead.comment ? 0 : 16)
  7499. );
  7500. put_byte(s, s.gzhead.time & 0xff);
  7501. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7502. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7503. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7504. put_byte(s, s.level === 9 ? 2 :
  7505. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7506. 4 : 0));
  7507. put_byte(s, s.gzhead.os & 0xff);
  7508. if (s.gzhead.extra && s.gzhead.extra.length) {
  7509. put_byte(s, s.gzhead.extra.length & 0xff);
  7510. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7511. }
  7512. if (s.gzhead.hcrc) {
  7513. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7514. }
  7515. s.gzindex = 0;
  7516. s.status = EXTRA_STATE;
  7517. }
  7518. }
  7519. else // DEFLATE header
  7520. {
  7521. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7522. var level_flags = -1;
  7523. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7524. level_flags = 0;
  7525. } else if (s.level < 6) {
  7526. level_flags = 1;
  7527. } else if (s.level === 6) {
  7528. level_flags = 2;
  7529. } else {
  7530. level_flags = 3;
  7531. }
  7532. header |= (level_flags << 6);
  7533. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7534. header += 31 - (header % 31);
  7535. s.status = BUSY_STATE;
  7536. putShortMSB(s, header);
  7537. /* Save the adler32 of the preset dictionary: */
  7538. if (s.strstart !== 0) {
  7539. putShortMSB(s, strm.adler >>> 16);
  7540. putShortMSB(s, strm.adler & 0xffff);
  7541. }
  7542. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7543. }
  7544. }
  7545. //#ifdef GZIP
  7546. if (s.status === EXTRA_STATE) {
  7547. if (s.gzhead.extra/* != Z_NULL*/) {
  7548. beg = s.pending; /* start of bytes to update crc */
  7549. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7550. if (s.pending === s.pending_buf_size) {
  7551. if (s.gzhead.hcrc && s.pending > beg) {
  7552. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7553. }
  7554. flush_pending(strm);
  7555. beg = s.pending;
  7556. if (s.pending === s.pending_buf_size) {
  7557. break;
  7558. }
  7559. }
  7560. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7561. s.gzindex++;
  7562. }
  7563. if (s.gzhead.hcrc && s.pending > beg) {
  7564. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7565. }
  7566. if (s.gzindex === s.gzhead.extra.length) {
  7567. s.gzindex = 0;
  7568. s.status = NAME_STATE;
  7569. }
  7570. }
  7571. else {
  7572. s.status = NAME_STATE;
  7573. }
  7574. }
  7575. if (s.status === NAME_STATE) {
  7576. if (s.gzhead.name/* != Z_NULL*/) {
  7577. beg = s.pending; /* start of bytes to update crc */
  7578. //int val;
  7579. do {
  7580. if (s.pending === s.pending_buf_size) {
  7581. if (s.gzhead.hcrc && s.pending > beg) {
  7582. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7583. }
  7584. flush_pending(strm);
  7585. beg = s.pending;
  7586. if (s.pending === s.pending_buf_size) {
  7587. val = 1;
  7588. break;
  7589. }
  7590. }
  7591. // JS specific: little magic to add zero terminator to end of string
  7592. if (s.gzindex < s.gzhead.name.length) {
  7593. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7594. } else {
  7595. val = 0;
  7596. }
  7597. put_byte(s, val);
  7598. } while (val !== 0);
  7599. if (s.gzhead.hcrc && s.pending > beg) {
  7600. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7601. }
  7602. if (val === 0) {
  7603. s.gzindex = 0;
  7604. s.status = COMMENT_STATE;
  7605. }
  7606. }
  7607. else {
  7608. s.status = COMMENT_STATE;
  7609. }
  7610. }
  7611. if (s.status === COMMENT_STATE) {
  7612. if (s.gzhead.comment/* != Z_NULL*/) {
  7613. beg = s.pending; /* start of bytes to update crc */
  7614. //int val;
  7615. do {
  7616. if (s.pending === s.pending_buf_size) {
  7617. if (s.gzhead.hcrc && s.pending > beg) {
  7618. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7619. }
  7620. flush_pending(strm);
  7621. beg = s.pending;
  7622. if (s.pending === s.pending_buf_size) {
  7623. val = 1;
  7624. break;
  7625. }
  7626. }
  7627. // JS specific: little magic to add zero terminator to end of string
  7628. if (s.gzindex < s.gzhead.comment.length) {
  7629. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7630. } else {
  7631. val = 0;
  7632. }
  7633. put_byte(s, val);
  7634. } while (val !== 0);
  7635. if (s.gzhead.hcrc && s.pending > beg) {
  7636. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7637. }
  7638. if (val === 0) {
  7639. s.status = HCRC_STATE;
  7640. }
  7641. }
  7642. else {
  7643. s.status = HCRC_STATE;
  7644. }
  7645. }
  7646. if (s.status === HCRC_STATE) {
  7647. if (s.gzhead.hcrc) {
  7648. if (s.pending + 2 > s.pending_buf_size) {
  7649. flush_pending(strm);
  7650. }
  7651. if (s.pending + 2 <= s.pending_buf_size) {
  7652. put_byte(s, strm.adler & 0xff);
  7653. put_byte(s, (strm.adler >> 8) & 0xff);
  7654. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7655. s.status = BUSY_STATE;
  7656. }
  7657. }
  7658. else {
  7659. s.status = BUSY_STATE;
  7660. }
  7661. }
  7662. //#endif
  7663. /* Flush as much pending output as possible */
  7664. if (s.pending !== 0) {
  7665. flush_pending(strm);
  7666. if (strm.avail_out === 0) {
  7667. /* Since avail_out is 0, deflate will be called again with
  7668. * more output space, but possibly with both pending and
  7669. * avail_in equal to zero. There won't be anything to do,
  7670. * but this is not an error situation so make sure we
  7671. * return OK instead of BUF_ERROR at next call of deflate:
  7672. */
  7673. s.last_flush = -1;
  7674. return Z_OK;
  7675. }
  7676. /* Make sure there is something to do and avoid duplicate consecutive
  7677. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7678. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7679. */
  7680. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7681. flush !== Z_FINISH) {
  7682. return err(strm, Z_BUF_ERROR);
  7683. }
  7684. /* User must not provide more input after the first FINISH: */
  7685. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7686. return err(strm, Z_BUF_ERROR);
  7687. }
  7688. /* Start a new block or continue the current one.
  7689. */
  7690. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7691. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7692. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7693. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7694. configuration_table[s.level].func(s, flush));
  7695. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7696. s.status = FINISH_STATE;
  7697. }
  7698. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7699. if (strm.avail_out === 0) {
  7700. s.last_flush = -1;
  7701. /* avoid BUF_ERROR next call, see above */
  7702. }
  7703. return Z_OK;
  7704. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7705. * of deflate should use the same flush parameter to make sure
  7706. * that the flush is complete. So we don't have to output an
  7707. * empty block here, this will be done at next call. This also
  7708. * ensures that for a very small output buffer, we emit at most
  7709. * one empty block.
  7710. */
  7711. }
  7712. if (bstate === BS_BLOCK_DONE) {
  7713. if (flush === Z_PARTIAL_FLUSH) {
  7714. trees._tr_align(s);
  7715. }
  7716. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7717. trees._tr_stored_block(s, 0, 0, false);
  7718. /* For a full flush, this empty block will be recognized
  7719. * as a special marker by inflate_sync().
  7720. */
  7721. if (flush === Z_FULL_FLUSH) {
  7722. /*** CLEAR_HASH(s); ***/ /* forget history */
  7723. zero(s.head); // Fill with NIL (= 0);
  7724. if (s.lookahead === 0) {
  7725. s.strstart = 0;
  7726. s.block_start = 0;
  7727. s.insert = 0;
  7728. }
  7729. }
  7730. }
  7731. flush_pending(strm);
  7732. if (strm.avail_out === 0) {
  7733. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7734. return Z_OK;
  7735. }
  7736. }
  7737. }
  7738. //Assert(strm->avail_out > 0, "bug2");
  7739. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7740. if (flush !== Z_FINISH) { return Z_OK; }
  7741. if (s.wrap <= 0) { return Z_STREAM_END; }
  7742. /* Write the trailer */
  7743. if (s.wrap === 2) {
  7744. put_byte(s, strm.adler & 0xff);
  7745. put_byte(s, (strm.adler >> 8) & 0xff);
  7746. put_byte(s, (strm.adler >> 16) & 0xff);
  7747. put_byte(s, (strm.adler >> 24) & 0xff);
  7748. put_byte(s, strm.total_in & 0xff);
  7749. put_byte(s, (strm.total_in >> 8) & 0xff);
  7750. put_byte(s, (strm.total_in >> 16) & 0xff);
  7751. put_byte(s, (strm.total_in >> 24) & 0xff);
  7752. }
  7753. else
  7754. {
  7755. putShortMSB(s, strm.adler >>> 16);
  7756. putShortMSB(s, strm.adler & 0xffff);
  7757. }
  7758. flush_pending(strm);
  7759. /* If avail_out is zero, the application will call deflate again
  7760. * to flush the rest.
  7761. */
  7762. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7763. /* write the trailer only once! */
  7764. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7765. }
  7766. function deflateEnd(strm) {
  7767. var status;
  7768. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7769. return Z_STREAM_ERROR;
  7770. }
  7771. status = strm.state.status;
  7772. if (status !== INIT_STATE &&
  7773. status !== EXTRA_STATE &&
  7774. status !== NAME_STATE &&
  7775. status !== COMMENT_STATE &&
  7776. status !== HCRC_STATE &&
  7777. status !== BUSY_STATE &&
  7778. status !== FINISH_STATE
  7779. ) {
  7780. return err(strm, Z_STREAM_ERROR);
  7781. }
  7782. strm.state = null;
  7783. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7784. }
  7785. /* =========================================================================
  7786. * Initializes the compression dictionary from the given byte
  7787. * sequence without producing any compressed output.
  7788. */
  7789. function deflateSetDictionary(strm, dictionary) {
  7790. var dictLength = dictionary.length;
  7791. var s;
  7792. var str, n;
  7793. var wrap;
  7794. var avail;
  7795. var next;
  7796. var input;
  7797. var tmpDict;
  7798. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7799. return Z_STREAM_ERROR;
  7800. }
  7801. s = strm.state;
  7802. wrap = s.wrap;
  7803. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7804. return Z_STREAM_ERROR;
  7805. }
  7806. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7807. if (wrap === 1) {
  7808. /* adler32(strm->adler, dictionary, dictLength); */
  7809. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7810. }
  7811. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  7812. /* if dictionary would fill window, just replace the history */
  7813. if (dictLength >= s.w_size) {
  7814. if (wrap === 0) { /* already empty otherwise */
  7815. /*** CLEAR_HASH(s); ***/
  7816. zero(s.head); // Fill with NIL (= 0);
  7817. s.strstart = 0;
  7818. s.block_start = 0;
  7819. s.insert = 0;
  7820. }
  7821. /* use the tail */
  7822. // dictionary = dictionary.slice(dictLength - s.w_size);
  7823. tmpDict = new utils.Buf8(s.w_size);
  7824. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7825. dictionary = tmpDict;
  7826. dictLength = s.w_size;
  7827. }
  7828. /* insert dictionary into window and hash */
  7829. avail = strm.avail_in;
  7830. next = strm.next_in;
  7831. input = strm.input;
  7832. strm.avail_in = dictLength;
  7833. strm.next_in = 0;
  7834. strm.input = dictionary;
  7835. fill_window(s);
  7836. while (s.lookahead >= MIN_MATCH) {
  7837. str = s.strstart;
  7838. n = s.lookahead - (MIN_MATCH - 1);
  7839. do {
  7840. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7841. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7842. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7843. s.head[s.ins_h] = str;
  7844. str++;
  7845. } while (--n);
  7846. s.strstart = str;
  7847. s.lookahead = MIN_MATCH - 1;
  7848. fill_window(s);
  7849. }
  7850. s.strstart += s.lookahead;
  7851. s.block_start = s.strstart;
  7852. s.insert = s.lookahead;
  7853. s.lookahead = 0;
  7854. s.match_length = s.prev_length = MIN_MATCH - 1;
  7855. s.match_available = 0;
  7856. strm.next_in = next;
  7857. strm.input = input;
  7858. strm.avail_in = avail;
  7859. s.wrap = wrap;
  7860. return Z_OK;
  7861. }
  7862. exports.deflateInit = deflateInit;
  7863. exports.deflateInit2 = deflateInit2;
  7864. exports.deflateReset = deflateReset;
  7865. exports.deflateResetKeep = deflateResetKeep;
  7866. exports.deflateSetHeader = deflateSetHeader;
  7867. exports.deflate = deflate;
  7868. exports.deflateEnd = deflateEnd;
  7869. exports.deflateSetDictionary = deflateSetDictionary;
  7870. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7871. /* Not implemented
  7872. exports.deflateBound = deflateBound;
  7873. exports.deflateCopy = deflateCopy;
  7874. exports.deflateParams = deflateParams;
  7875. exports.deflatePending = deflatePending;
  7876. exports.deflatePrime = deflatePrime;
  7877. exports.deflateTune = deflateTune;
  7878. */
  7879. },{"../utils/common":39,"./adler32":40,"./crc32":42,"./messages":47,"./trees":48}],44:[function(require,module,exports){
  7880. 'use strict';
  7881. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7882. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7883. //
  7884. // This software is provided 'as-is', without any express or implied
  7885. // warranty. In no event will the authors be held liable for any damages
  7886. // arising from the use of this software.
  7887. //
  7888. // Permission is granted to anyone to use this software for any purpose,
  7889. // including commercial applications, and to alter it and redistribute it
  7890. // freely, subject to the following restrictions:
  7891. //
  7892. // 1. The origin of this software must not be misrepresented; you must not
  7893. // claim that you wrote the original software. If you use this software
  7894. // in a product, an acknowledgment in the product documentation would be
  7895. // appreciated but is not required.
  7896. // 2. Altered source versions must be plainly marked as such, and must not be
  7897. // misrepresented as being the original software.
  7898. // 3. This notice may not be removed or altered from any source distribution.
  7899. // See state defs from inflate.js
  7900. var BAD = 30; /* got a data error -- remain here until reset */
  7901. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7902. /*
  7903. Decode literal, length, and distance codes and write out the resulting
  7904. literal and match bytes until either not enough input or output is
  7905. available, an end-of-block is encountered, or a data error is encountered.
  7906. When large enough input and output buffers are supplied to inflate(), for
  7907. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7908. inflate execution time is spent in this routine.
  7909. Entry assumptions:
  7910. state.mode === LEN
  7911. strm.avail_in >= 6
  7912. strm.avail_out >= 258
  7913. start >= strm.avail_out
  7914. state.bits < 8
  7915. On return, state.mode is one of:
  7916. LEN -- ran out of enough output space or enough available input
  7917. TYPE -- reached end of block code, inflate() to interpret next block
  7918. BAD -- error in block data
  7919. Notes:
  7920. - The maximum input bits used by a length/distance pair is 15 bits for the
  7921. length code, 5 bits for the length extra, 15 bits for the distance code,
  7922. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7923. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7924. checking for available input while decoding.
  7925. - The maximum bytes that a single length/distance pair can output is 258
  7926. bytes, which is the maximum length that can be coded. inflate_fast()
  7927. requires strm.avail_out >= 258 for each loop to avoid checking for
  7928. output space.
  7929. */
  7930. module.exports = function inflate_fast(strm, start) {
  7931. var state;
  7932. var _in; /* local strm.input */
  7933. var last; /* have enough input while in < last */
  7934. var _out; /* local strm.output */
  7935. var beg; /* inflate()'s initial strm.output */
  7936. var end; /* while out < end, enough space available */
  7937. //#ifdef INFLATE_STRICT
  7938. var dmax; /* maximum distance from zlib header */
  7939. //#endif
  7940. var wsize; /* window size or zero if not using window */
  7941. var whave; /* valid bytes in the window */
  7942. var wnext; /* window write index */
  7943. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  7944. var s_window; /* allocated sliding window, if wsize != 0 */
  7945. var hold; /* local strm.hold */
  7946. var bits; /* local strm.bits */
  7947. var lcode; /* local strm.lencode */
  7948. var dcode; /* local strm.distcode */
  7949. var lmask; /* mask for first level of length codes */
  7950. var dmask; /* mask for first level of distance codes */
  7951. var here; /* retrieved table entry */
  7952. var op; /* code bits, operation, extra bits, or */
  7953. /* window position, window bytes to copy */
  7954. var len; /* match length, unused bytes */
  7955. var dist; /* match distance */
  7956. var from; /* where to copy match from */
  7957. var from_source;
  7958. var input, output; // JS specific, because we have no pointers
  7959. /* copy state to local variables */
  7960. state = strm.state;
  7961. //here = state.here;
  7962. _in = strm.next_in;
  7963. input = strm.input;
  7964. last = _in + (strm.avail_in - 5);
  7965. _out = strm.next_out;
  7966. output = strm.output;
  7967. beg = _out - (start - strm.avail_out);
  7968. end = _out + (strm.avail_out - 257);
  7969. //#ifdef INFLATE_STRICT
  7970. dmax = state.dmax;
  7971. //#endif
  7972. wsize = state.wsize;
  7973. whave = state.whave;
  7974. wnext = state.wnext;
  7975. s_window = state.window;
  7976. hold = state.hold;
  7977. bits = state.bits;
  7978. lcode = state.lencode;
  7979. dcode = state.distcode;
  7980. lmask = (1 << state.lenbits) - 1;
  7981. dmask = (1 << state.distbits) - 1;
  7982. /* decode literals and length/distances until end-of-block or not enough
  7983. input data or output space */
  7984. top:
  7985. do {
  7986. if (bits < 15) {
  7987. hold += input[_in++] << bits;
  7988. bits += 8;
  7989. hold += input[_in++] << bits;
  7990. bits += 8;
  7991. }
  7992. here = lcode[hold & lmask];
  7993. dolen:
  7994. for (;;) { // Goto emulation
  7995. op = here >>> 24/*here.bits*/;
  7996. hold >>>= op;
  7997. bits -= op;
  7998. op = (here >>> 16) & 0xff/*here.op*/;
  7999. if (op === 0) { /* literal */
  8000. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8001. // "inflate: literal '%c'\n" :
  8002. // "inflate: literal 0x%02x\n", here.val));
  8003. output[_out++] = here & 0xffff/*here.val*/;
  8004. }
  8005. else if (op & 16) { /* length base */
  8006. len = here & 0xffff/*here.val*/;
  8007. op &= 15; /* number of extra bits */
  8008. if (op) {
  8009. if (bits < op) {
  8010. hold += input[_in++] << bits;
  8011. bits += 8;
  8012. }
  8013. len += hold & ((1 << op) - 1);
  8014. hold >>>= op;
  8015. bits -= op;
  8016. }
  8017. //Tracevv((stderr, "inflate: length %u\n", len));
  8018. if (bits < 15) {
  8019. hold += input[_in++] << bits;
  8020. bits += 8;
  8021. hold += input[_in++] << bits;
  8022. bits += 8;
  8023. }
  8024. here = dcode[hold & dmask];
  8025. dodist:
  8026. for (;;) { // goto emulation
  8027. op = here >>> 24/*here.bits*/;
  8028. hold >>>= op;
  8029. bits -= op;
  8030. op = (here >>> 16) & 0xff/*here.op*/;
  8031. if (op & 16) { /* distance base */
  8032. dist = here & 0xffff/*here.val*/;
  8033. op &= 15; /* number of extra bits */
  8034. if (bits < op) {
  8035. hold += input[_in++] << bits;
  8036. bits += 8;
  8037. if (bits < op) {
  8038. hold += input[_in++] << bits;
  8039. bits += 8;
  8040. }
  8041. }
  8042. dist += hold & ((1 << op) - 1);
  8043. //#ifdef INFLATE_STRICT
  8044. if (dist > dmax) {
  8045. strm.msg = 'invalid distance too far back';
  8046. state.mode = BAD;
  8047. break top;
  8048. }
  8049. //#endif
  8050. hold >>>= op;
  8051. bits -= op;
  8052. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8053. op = _out - beg; /* max distance in output */
  8054. if (dist > op) { /* see if copy from window */
  8055. op = dist - op; /* distance back in window */
  8056. if (op > whave) {
  8057. if (state.sane) {
  8058. strm.msg = 'invalid distance too far back';
  8059. state.mode = BAD;
  8060. break top;
  8061. }
  8062. // (!) This block is disabled in zlib defaults,
  8063. // don't enable it for binary compatibility
  8064. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8065. // if (len <= op - whave) {
  8066. // do {
  8067. // output[_out++] = 0;
  8068. // } while (--len);
  8069. // continue top;
  8070. // }
  8071. // len -= op - whave;
  8072. // do {
  8073. // output[_out++] = 0;
  8074. // } while (--op > whave);
  8075. // if (op === 0) {
  8076. // from = _out - dist;
  8077. // do {
  8078. // output[_out++] = output[from++];
  8079. // } while (--len);
  8080. // continue top;
  8081. // }
  8082. //#endif
  8083. }
  8084. from = 0; // window index
  8085. from_source = s_window;
  8086. if (wnext === 0) { /* very common case */
  8087. from += wsize - op;
  8088. if (op < len) { /* some from window */
  8089. len -= op;
  8090. do {
  8091. output[_out++] = s_window[from++];
  8092. } while (--op);
  8093. from = _out - dist; /* rest from output */
  8094. from_source = output;
  8095. }
  8096. }
  8097. else if (wnext < op) { /* wrap around window */
  8098. from += wsize + wnext - op;
  8099. op -= wnext;
  8100. if (op < len) { /* some from end of window */
  8101. len -= op;
  8102. do {
  8103. output[_out++] = s_window[from++];
  8104. } while (--op);
  8105. from = 0;
  8106. if (wnext < len) { /* some from start of window */
  8107. op = wnext;
  8108. len -= op;
  8109. do {
  8110. output[_out++] = s_window[from++];
  8111. } while (--op);
  8112. from = _out - dist; /* rest from output */
  8113. from_source = output;
  8114. }
  8115. }
  8116. }
  8117. else { /* contiguous in window */
  8118. from += wnext - op;
  8119. if (op < len) { /* some from window */
  8120. len -= op;
  8121. do {
  8122. output[_out++] = s_window[from++];
  8123. } while (--op);
  8124. from = _out - dist; /* rest from output */
  8125. from_source = output;
  8126. }
  8127. }
  8128. while (len > 2) {
  8129. output[_out++] = from_source[from++];
  8130. output[_out++] = from_source[from++];
  8131. output[_out++] = from_source[from++];
  8132. len -= 3;
  8133. }
  8134. if (len) {
  8135. output[_out++] = from_source[from++];
  8136. if (len > 1) {
  8137. output[_out++] = from_source[from++];
  8138. }
  8139. }
  8140. }
  8141. else {
  8142. from = _out - dist; /* copy direct from output */
  8143. do { /* minimum length is three */
  8144. output[_out++] = output[from++];
  8145. output[_out++] = output[from++];
  8146. output[_out++] = output[from++];
  8147. len -= 3;
  8148. } while (len > 2);
  8149. if (len) {
  8150. output[_out++] = output[from++];
  8151. if (len > 1) {
  8152. output[_out++] = output[from++];
  8153. }
  8154. }
  8155. }
  8156. }
  8157. else if ((op & 64) === 0) { /* 2nd level distance code */
  8158. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8159. continue dodist;
  8160. }
  8161. else {
  8162. strm.msg = 'invalid distance code';
  8163. state.mode = BAD;
  8164. break top;
  8165. }
  8166. break; // need to emulate goto via "continue"
  8167. }
  8168. }
  8169. else if ((op & 64) === 0) { /* 2nd level length code */
  8170. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8171. continue dolen;
  8172. }
  8173. else if (op & 32) { /* end-of-block */
  8174. //Tracevv((stderr, "inflate: end of block\n"));
  8175. state.mode = TYPE;
  8176. break top;
  8177. }
  8178. else {
  8179. strm.msg = 'invalid literal/length code';
  8180. state.mode = BAD;
  8181. break top;
  8182. }
  8183. break; // need to emulate goto via "continue"
  8184. }
  8185. } while (_in < last && _out < end);
  8186. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8187. len = bits >> 3;
  8188. _in -= len;
  8189. bits -= len << 3;
  8190. hold &= (1 << bits) - 1;
  8191. /* update state and return */
  8192. strm.next_in = _in;
  8193. strm.next_out = _out;
  8194. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8195. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8196. state.hold = hold;
  8197. state.bits = bits;
  8198. return;
  8199. };
  8200. },{}],45:[function(require,module,exports){
  8201. 'use strict';
  8202. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8203. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8204. //
  8205. // This software is provided 'as-is', without any express or implied
  8206. // warranty. In no event will the authors be held liable for any damages
  8207. // arising from the use of this software.
  8208. //
  8209. // Permission is granted to anyone to use this software for any purpose,
  8210. // including commercial applications, and to alter it and redistribute it
  8211. // freely, subject to the following restrictions:
  8212. //
  8213. // 1. The origin of this software must not be misrepresented; you must not
  8214. // claim that you wrote the original software. If you use this software
  8215. // in a product, an acknowledgment in the product documentation would be
  8216. // appreciated but is not required.
  8217. // 2. Altered source versions must be plainly marked as such, and must not be
  8218. // misrepresented as being the original software.
  8219. // 3. This notice may not be removed or altered from any source distribution.
  8220. var utils = require('../utils/common');
  8221. var adler32 = require('./adler32');
  8222. var crc32 = require('./crc32');
  8223. var inflate_fast = require('./inffast');
  8224. var inflate_table = require('./inftrees');
  8225. var CODES = 0;
  8226. var LENS = 1;
  8227. var DISTS = 2;
  8228. /* Public constants ==========================================================*/
  8229. /* ===========================================================================*/
  8230. /* Allowed flush values; see deflate() and inflate() below for details */
  8231. //var Z_NO_FLUSH = 0;
  8232. //var Z_PARTIAL_FLUSH = 1;
  8233. //var Z_SYNC_FLUSH = 2;
  8234. //var Z_FULL_FLUSH = 3;
  8235. var Z_FINISH = 4;
  8236. var Z_BLOCK = 5;
  8237. var Z_TREES = 6;
  8238. /* Return codes for the compression/decompression functions. Negative values
  8239. * are errors, positive values are used for special but normal events.
  8240. */
  8241. var Z_OK = 0;
  8242. var Z_STREAM_END = 1;
  8243. var Z_NEED_DICT = 2;
  8244. //var Z_ERRNO = -1;
  8245. var Z_STREAM_ERROR = -2;
  8246. var Z_DATA_ERROR = -3;
  8247. var Z_MEM_ERROR = -4;
  8248. var Z_BUF_ERROR = -5;
  8249. //var Z_VERSION_ERROR = -6;
  8250. /* The deflate compression method */
  8251. var Z_DEFLATED = 8;
  8252. /* STATES ====================================================================*/
  8253. /* ===========================================================================*/
  8254. var HEAD = 1; /* i: waiting for magic header */
  8255. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8256. var TIME = 3; /* i: waiting for modification time (gzip) */
  8257. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8258. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8259. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8260. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8261. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8262. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8263. var DICTID = 10; /* i: waiting for dictionary check value */
  8264. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8265. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8266. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8267. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8268. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8269. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8270. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8271. var LENLENS = 18; /* i: waiting for code length code lengths */
  8272. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8273. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8274. var LEN = 21; /* i: waiting for length/lit/eob code */
  8275. var LENEXT = 22; /* i: waiting for length extra bits */
  8276. var DIST = 23; /* i: waiting for distance code */
  8277. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8278. var MATCH = 25; /* o: waiting for output space to copy string */
  8279. var LIT = 26; /* o: waiting for output space to write literal */
  8280. var CHECK = 27; /* i: waiting for 32-bit check value */
  8281. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8282. var DONE = 29; /* finished check, done -- remain here until reset */
  8283. var BAD = 30; /* got a data error -- remain here until reset */
  8284. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8285. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8286. /* ===========================================================================*/
  8287. var ENOUGH_LENS = 852;
  8288. var ENOUGH_DISTS = 592;
  8289. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8290. var MAX_WBITS = 15;
  8291. /* 32K LZ77 window */
  8292. var DEF_WBITS = MAX_WBITS;
  8293. function zswap32(q) {
  8294. return (((q >>> 24) & 0xff) +
  8295. ((q >>> 8) & 0xff00) +
  8296. ((q & 0xff00) << 8) +
  8297. ((q & 0xff) << 24));
  8298. }
  8299. function InflateState() {
  8300. this.mode = 0; /* current inflate mode */
  8301. this.last = false; /* true if processing last block */
  8302. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8303. this.havedict = false; /* true if dictionary provided */
  8304. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8305. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8306. this.check = 0; /* protected copy of check value */
  8307. this.total = 0; /* protected copy of output count */
  8308. // TODO: may be {}
  8309. this.head = null; /* where to save gzip header information */
  8310. /* sliding window */
  8311. this.wbits = 0; /* log base 2 of requested window size */
  8312. this.wsize = 0; /* window size or zero if not using window */
  8313. this.whave = 0; /* valid bytes in the window */
  8314. this.wnext = 0; /* window write index */
  8315. this.window = null; /* allocated sliding window, if needed */
  8316. /* bit accumulator */
  8317. this.hold = 0; /* input bit accumulator */
  8318. this.bits = 0; /* number of bits in "in" */
  8319. /* for string and stored block copying */
  8320. this.length = 0; /* literal or length of data to copy */
  8321. this.offset = 0; /* distance back to copy string from */
  8322. /* for table and code decoding */
  8323. this.extra = 0; /* extra bits needed */
  8324. /* fixed and dynamic code tables */
  8325. this.lencode = null; /* starting table for length/literal codes */
  8326. this.distcode = null; /* starting table for distance codes */
  8327. this.lenbits = 0; /* index bits for lencode */
  8328. this.distbits = 0; /* index bits for distcode */
  8329. /* dynamic table building */
  8330. this.ncode = 0; /* number of code length code lengths */
  8331. this.nlen = 0; /* number of length code lengths */
  8332. this.ndist = 0; /* number of distance code lengths */
  8333. this.have = 0; /* number of code lengths in lens[] */
  8334. this.next = null; /* next available space in codes[] */
  8335. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8336. this.work = new utils.Buf16(288); /* work area for code table building */
  8337. /*
  8338. because we don't have pointers in js, we use lencode and distcode directly
  8339. as buffers so we don't need codes
  8340. */
  8341. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8342. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8343. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8344. this.sane = 0; /* if false, allow invalid distance too far */
  8345. this.back = 0; /* bits back of last unprocessed length/lit */
  8346. this.was = 0; /* initial length of match */
  8347. }
  8348. function inflateResetKeep(strm) {
  8349. var state;
  8350. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8351. state = strm.state;
  8352. strm.total_in = strm.total_out = state.total = 0;
  8353. strm.msg = ''; /*Z_NULL*/
  8354. if (state.wrap) { /* to support ill-conceived Java test suite */
  8355. strm.adler = state.wrap & 1;
  8356. }
  8357. state.mode = HEAD;
  8358. state.last = 0;
  8359. state.havedict = 0;
  8360. state.dmax = 32768;
  8361. state.head = null/*Z_NULL*/;
  8362. state.hold = 0;
  8363. state.bits = 0;
  8364. //state.lencode = state.distcode = state.next = state.codes;
  8365. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8366. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8367. state.sane = 1;
  8368. state.back = -1;
  8369. //Tracev((stderr, "inflate: reset\n"));
  8370. return Z_OK;
  8371. }
  8372. function inflateReset(strm) {
  8373. var state;
  8374. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8375. state = strm.state;
  8376. state.wsize = 0;
  8377. state.whave = 0;
  8378. state.wnext = 0;
  8379. return inflateResetKeep(strm);
  8380. }
  8381. function inflateReset2(strm, windowBits) {
  8382. var wrap;
  8383. var state;
  8384. /* get the state */
  8385. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8386. state = strm.state;
  8387. /* extract wrap request from windowBits parameter */
  8388. if (windowBits < 0) {
  8389. wrap = 0;
  8390. windowBits = -windowBits;
  8391. }
  8392. else {
  8393. wrap = (windowBits >> 4) + 1;
  8394. if (windowBits < 48) {
  8395. windowBits &= 15;
  8396. }
  8397. }
  8398. /* set number of window bits, free window if different */
  8399. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8400. return Z_STREAM_ERROR;
  8401. }
  8402. if (state.window !== null && state.wbits !== windowBits) {
  8403. state.window = null;
  8404. }
  8405. /* update state and reset the rest of it */
  8406. state.wrap = wrap;
  8407. state.wbits = windowBits;
  8408. return inflateReset(strm);
  8409. }
  8410. function inflateInit2(strm, windowBits) {
  8411. var ret;
  8412. var state;
  8413. if (!strm) { return Z_STREAM_ERROR; }
  8414. //strm.msg = Z_NULL; /* in case we return an error */
  8415. state = new InflateState();
  8416. //if (state === Z_NULL) return Z_MEM_ERROR;
  8417. //Tracev((stderr, "inflate: allocated\n"));
  8418. strm.state = state;
  8419. state.window = null/*Z_NULL*/;
  8420. ret = inflateReset2(strm, windowBits);
  8421. if (ret !== Z_OK) {
  8422. strm.state = null/*Z_NULL*/;
  8423. }
  8424. return ret;
  8425. }
  8426. function inflateInit(strm) {
  8427. return inflateInit2(strm, DEF_WBITS);
  8428. }
  8429. /*
  8430. Return state with length and distance decoding tables and index sizes set to
  8431. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8432. If BUILDFIXED is defined, then instead this routine builds the tables the
  8433. first time it's called, and returns those tables the first time and
  8434. thereafter. This reduces the size of the code by about 2K bytes, in
  8435. exchange for a little execution time. However, BUILDFIXED should not be
  8436. used for threaded applications, since the rewriting of the tables and virgin
  8437. may not be thread-safe.
  8438. */
  8439. var virgin = true;
  8440. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8441. function fixedtables(state) {
  8442. /* build fixed huffman tables if first call (may not be thread safe) */
  8443. if (virgin) {
  8444. var sym;
  8445. lenfix = new utils.Buf32(512);
  8446. distfix = new utils.Buf32(32);
  8447. /* literal/length table */
  8448. sym = 0;
  8449. while (sym < 144) { state.lens[sym++] = 8; }
  8450. while (sym < 256) { state.lens[sym++] = 9; }
  8451. while (sym < 280) { state.lens[sym++] = 7; }
  8452. while (sym < 288) { state.lens[sym++] = 8; }
  8453. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8454. /* distance table */
  8455. sym = 0;
  8456. while (sym < 32) { state.lens[sym++] = 5; }
  8457. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8458. /* do this just once */
  8459. virgin = false;
  8460. }
  8461. state.lencode = lenfix;
  8462. state.lenbits = 9;
  8463. state.distcode = distfix;
  8464. state.distbits = 5;
  8465. }
  8466. /*
  8467. Update the window with the last wsize (normally 32K) bytes written before
  8468. returning. If window does not exist yet, create it. This is only called
  8469. when a window is already in use, or when output has been written during this
  8470. inflate call, but the end of the deflate stream has not been reached yet.
  8471. It is also called to create a window for dictionary data when a dictionary
  8472. is loaded.
  8473. Providing output buffers larger than 32K to inflate() should provide a speed
  8474. advantage, since only the last 32K of output is copied to the sliding window
  8475. upon return from inflate(), and since all distances after the first 32K of
  8476. output will fall in the output data, making match copies simpler and faster.
  8477. The advantage may be dependent on the size of the processor's data caches.
  8478. */
  8479. function updatewindow(strm, src, end, copy) {
  8480. var dist;
  8481. var state = strm.state;
  8482. /* if it hasn't been done already, allocate space for the window */
  8483. if (state.window === null) {
  8484. state.wsize = 1 << state.wbits;
  8485. state.wnext = 0;
  8486. state.whave = 0;
  8487. state.window = new utils.Buf8(state.wsize);
  8488. }
  8489. /* copy state->wsize or less output bytes into the circular window */
  8490. if (copy >= state.wsize) {
  8491. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8492. state.wnext = 0;
  8493. state.whave = state.wsize;
  8494. }
  8495. else {
  8496. dist = state.wsize - state.wnext;
  8497. if (dist > copy) {
  8498. dist = copy;
  8499. }
  8500. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8501. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8502. copy -= dist;
  8503. if (copy) {
  8504. //zmemcpy(state->window, end - copy, copy);
  8505. utils.arraySet(state.window, src, end - copy, copy, 0);
  8506. state.wnext = copy;
  8507. state.whave = state.wsize;
  8508. }
  8509. else {
  8510. state.wnext += dist;
  8511. if (state.wnext === state.wsize) { state.wnext = 0; }
  8512. if (state.whave < state.wsize) { state.whave += dist; }
  8513. }
  8514. }
  8515. return 0;
  8516. }
  8517. function inflate(strm, flush) {
  8518. var state;
  8519. var input, output; // input/output buffers
  8520. var next; /* next input INDEX */
  8521. var put; /* next output INDEX */
  8522. var have, left; /* available input and output */
  8523. var hold; /* bit buffer */
  8524. var bits; /* bits in bit buffer */
  8525. var _in, _out; /* save starting available input and output */
  8526. var copy; /* number of stored or match bytes to copy */
  8527. var from; /* where to copy match bytes from */
  8528. var from_source;
  8529. var here = 0; /* current decoding table entry */
  8530. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8531. //var last; /* parent table entry */
  8532. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8533. var len; /* length to copy for repeats, bits to drop */
  8534. var ret; /* return code */
  8535. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8536. var opts;
  8537. var n; // temporary var for NEED_BITS
  8538. var order = /* permutation of code lengths */
  8539. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8540. if (!strm || !strm.state || !strm.output ||
  8541. (!strm.input && strm.avail_in !== 0)) {
  8542. return Z_STREAM_ERROR;
  8543. }
  8544. state = strm.state;
  8545. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8546. //--- LOAD() ---
  8547. put = strm.next_out;
  8548. output = strm.output;
  8549. left = strm.avail_out;
  8550. next = strm.next_in;
  8551. input = strm.input;
  8552. have = strm.avail_in;
  8553. hold = state.hold;
  8554. bits = state.bits;
  8555. //---
  8556. _in = have;
  8557. _out = left;
  8558. ret = Z_OK;
  8559. inf_leave: // goto emulation
  8560. for (;;) {
  8561. switch (state.mode) {
  8562. case HEAD:
  8563. if (state.wrap === 0) {
  8564. state.mode = TYPEDO;
  8565. break;
  8566. }
  8567. //=== NEEDBITS(16);
  8568. while (bits < 16) {
  8569. if (have === 0) { break inf_leave; }
  8570. have--;
  8571. hold += input[next++] << bits;
  8572. bits += 8;
  8573. }
  8574. //===//
  8575. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8576. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8577. //=== CRC2(state.check, hold);
  8578. hbuf[0] = hold & 0xff;
  8579. hbuf[1] = (hold >>> 8) & 0xff;
  8580. state.check = crc32(state.check, hbuf, 2, 0);
  8581. //===//
  8582. //=== INITBITS();
  8583. hold = 0;
  8584. bits = 0;
  8585. //===//
  8586. state.mode = FLAGS;
  8587. break;
  8588. }
  8589. state.flags = 0; /* expect zlib header */
  8590. if (state.head) {
  8591. state.head.done = false;
  8592. }
  8593. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8594. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8595. strm.msg = 'incorrect header check';
  8596. state.mode = BAD;
  8597. break;
  8598. }
  8599. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8600. strm.msg = 'unknown compression method';
  8601. state.mode = BAD;
  8602. break;
  8603. }
  8604. //--- DROPBITS(4) ---//
  8605. hold >>>= 4;
  8606. bits -= 4;
  8607. //---//
  8608. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8609. if (state.wbits === 0) {
  8610. state.wbits = len;
  8611. }
  8612. else if (len > state.wbits) {
  8613. strm.msg = 'invalid window size';
  8614. state.mode = BAD;
  8615. break;
  8616. }
  8617. state.dmax = 1 << len;
  8618. //Tracev((stderr, "inflate: zlib header ok\n"));
  8619. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8620. state.mode = hold & 0x200 ? DICTID : TYPE;
  8621. //=== INITBITS();
  8622. hold = 0;
  8623. bits = 0;
  8624. //===//
  8625. break;
  8626. case FLAGS:
  8627. //=== NEEDBITS(16); */
  8628. while (bits < 16) {
  8629. if (have === 0) { break inf_leave; }
  8630. have--;
  8631. hold += input[next++] << bits;
  8632. bits += 8;
  8633. }
  8634. //===//
  8635. state.flags = hold;
  8636. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8637. strm.msg = 'unknown compression method';
  8638. state.mode = BAD;
  8639. break;
  8640. }
  8641. if (state.flags & 0xe000) {
  8642. strm.msg = 'unknown header flags set';
  8643. state.mode = BAD;
  8644. break;
  8645. }
  8646. if (state.head) {
  8647. state.head.text = ((hold >> 8) & 1);
  8648. }
  8649. if (state.flags & 0x0200) {
  8650. //=== CRC2(state.check, hold);
  8651. hbuf[0] = hold & 0xff;
  8652. hbuf[1] = (hold >>> 8) & 0xff;
  8653. state.check = crc32(state.check, hbuf, 2, 0);
  8654. //===//
  8655. }
  8656. //=== INITBITS();
  8657. hold = 0;
  8658. bits = 0;
  8659. //===//
  8660. state.mode = TIME;
  8661. /* falls through */
  8662. case TIME:
  8663. //=== NEEDBITS(32); */
  8664. while (bits < 32) {
  8665. if (have === 0) { break inf_leave; }
  8666. have--;
  8667. hold += input[next++] << bits;
  8668. bits += 8;
  8669. }
  8670. //===//
  8671. if (state.head) {
  8672. state.head.time = hold;
  8673. }
  8674. if (state.flags & 0x0200) {
  8675. //=== CRC4(state.check, hold)
  8676. hbuf[0] = hold & 0xff;
  8677. hbuf[1] = (hold >>> 8) & 0xff;
  8678. hbuf[2] = (hold >>> 16) & 0xff;
  8679. hbuf[3] = (hold >>> 24) & 0xff;
  8680. state.check = crc32(state.check, hbuf, 4, 0);
  8681. //===
  8682. }
  8683. //=== INITBITS();
  8684. hold = 0;
  8685. bits = 0;
  8686. //===//
  8687. state.mode = OS;
  8688. /* falls through */
  8689. case OS:
  8690. //=== NEEDBITS(16); */
  8691. while (bits < 16) {
  8692. if (have === 0) { break inf_leave; }
  8693. have--;
  8694. hold += input[next++] << bits;
  8695. bits += 8;
  8696. }
  8697. //===//
  8698. if (state.head) {
  8699. state.head.xflags = (hold & 0xff);
  8700. state.head.os = (hold >> 8);
  8701. }
  8702. if (state.flags & 0x0200) {
  8703. //=== CRC2(state.check, hold);
  8704. hbuf[0] = hold & 0xff;
  8705. hbuf[1] = (hold >>> 8) & 0xff;
  8706. state.check = crc32(state.check, hbuf, 2, 0);
  8707. //===//
  8708. }
  8709. //=== INITBITS();
  8710. hold = 0;
  8711. bits = 0;
  8712. //===//
  8713. state.mode = EXLEN;
  8714. /* falls through */
  8715. case EXLEN:
  8716. if (state.flags & 0x0400) {
  8717. //=== NEEDBITS(16); */
  8718. while (bits < 16) {
  8719. if (have === 0) { break inf_leave; }
  8720. have--;
  8721. hold += input[next++] << bits;
  8722. bits += 8;
  8723. }
  8724. //===//
  8725. state.length = hold;
  8726. if (state.head) {
  8727. state.head.extra_len = hold;
  8728. }
  8729. if (state.flags & 0x0200) {
  8730. //=== CRC2(state.check, hold);
  8731. hbuf[0] = hold & 0xff;
  8732. hbuf[1] = (hold >>> 8) & 0xff;
  8733. state.check = crc32(state.check, hbuf, 2, 0);
  8734. //===//
  8735. }
  8736. //=== INITBITS();
  8737. hold = 0;
  8738. bits = 0;
  8739. //===//
  8740. }
  8741. else if (state.head) {
  8742. state.head.extra = null/*Z_NULL*/;
  8743. }
  8744. state.mode = EXTRA;
  8745. /* falls through */
  8746. case EXTRA:
  8747. if (state.flags & 0x0400) {
  8748. copy = state.length;
  8749. if (copy > have) { copy = have; }
  8750. if (copy) {
  8751. if (state.head) {
  8752. len = state.head.extra_len - state.length;
  8753. if (!state.head.extra) {
  8754. // Use untyped array for more convenient processing later
  8755. state.head.extra = new Array(state.head.extra_len);
  8756. }
  8757. utils.arraySet(
  8758. state.head.extra,
  8759. input,
  8760. next,
  8761. // extra field is limited to 65536 bytes
  8762. // - no need for additional size check
  8763. copy,
  8764. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8765. len
  8766. );
  8767. //zmemcpy(state.head.extra + len, next,
  8768. // len + copy > state.head.extra_max ?
  8769. // state.head.extra_max - len : copy);
  8770. }
  8771. if (state.flags & 0x0200) {
  8772. state.check = crc32(state.check, input, copy, next);
  8773. }
  8774. have -= copy;
  8775. next += copy;
  8776. state.length -= copy;
  8777. }
  8778. if (state.length) { break inf_leave; }
  8779. }
  8780. state.length = 0;
  8781. state.mode = NAME;
  8782. /* falls through */
  8783. case NAME:
  8784. if (state.flags & 0x0800) {
  8785. if (have === 0) { break inf_leave; }
  8786. copy = 0;
  8787. do {
  8788. // TODO: 2 or 1 bytes?
  8789. len = input[next + copy++];
  8790. /* use constant limit because in js we should not preallocate memory */
  8791. if (state.head && len &&
  8792. (state.length < 65536 /*state.head.name_max*/)) {
  8793. state.head.name += String.fromCharCode(len);
  8794. }
  8795. } while (len && copy < have);
  8796. if (state.flags & 0x0200) {
  8797. state.check = crc32(state.check, input, copy, next);
  8798. }
  8799. have -= copy;
  8800. next += copy;
  8801. if (len) { break inf_leave; }
  8802. }
  8803. else if (state.head) {
  8804. state.head.name = null;
  8805. }
  8806. state.length = 0;
  8807. state.mode = COMMENT;
  8808. /* falls through */
  8809. case COMMENT:
  8810. if (state.flags & 0x1000) {
  8811. if (have === 0) { break inf_leave; }
  8812. copy = 0;
  8813. do {
  8814. len = input[next + copy++];
  8815. /* use constant limit because in js we should not preallocate memory */
  8816. if (state.head && len &&
  8817. (state.length < 65536 /*state.head.comm_max*/)) {
  8818. state.head.comment += String.fromCharCode(len);
  8819. }
  8820. } while (len && copy < have);
  8821. if (state.flags & 0x0200) {
  8822. state.check = crc32(state.check, input, copy, next);
  8823. }
  8824. have -= copy;
  8825. next += copy;
  8826. if (len) { break inf_leave; }
  8827. }
  8828. else if (state.head) {
  8829. state.head.comment = null;
  8830. }
  8831. state.mode = HCRC;
  8832. /* falls through */
  8833. case HCRC:
  8834. if (state.flags & 0x0200) {
  8835. //=== NEEDBITS(16); */
  8836. while (bits < 16) {
  8837. if (have === 0) { break inf_leave; }
  8838. have--;
  8839. hold += input[next++] << bits;
  8840. bits += 8;
  8841. }
  8842. //===//
  8843. if (hold !== (state.check & 0xffff)) {
  8844. strm.msg = 'header crc mismatch';
  8845. state.mode = BAD;
  8846. break;
  8847. }
  8848. //=== INITBITS();
  8849. hold = 0;
  8850. bits = 0;
  8851. //===//
  8852. }
  8853. if (state.head) {
  8854. state.head.hcrc = ((state.flags >> 9) & 1);
  8855. state.head.done = true;
  8856. }
  8857. strm.adler = state.check = 0;
  8858. state.mode = TYPE;
  8859. break;
  8860. case DICTID:
  8861. //=== NEEDBITS(32); */
  8862. while (bits < 32) {
  8863. if (have === 0) { break inf_leave; }
  8864. have--;
  8865. hold += input[next++] << bits;
  8866. bits += 8;
  8867. }
  8868. //===//
  8869. strm.adler = state.check = zswap32(hold);
  8870. //=== INITBITS();
  8871. hold = 0;
  8872. bits = 0;
  8873. //===//
  8874. state.mode = DICT;
  8875. /* falls through */
  8876. case DICT:
  8877. if (state.havedict === 0) {
  8878. //--- RESTORE() ---
  8879. strm.next_out = put;
  8880. strm.avail_out = left;
  8881. strm.next_in = next;
  8882. strm.avail_in = have;
  8883. state.hold = hold;
  8884. state.bits = bits;
  8885. //---
  8886. return Z_NEED_DICT;
  8887. }
  8888. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8889. state.mode = TYPE;
  8890. /* falls through */
  8891. case TYPE:
  8892. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8893. /* falls through */
  8894. case TYPEDO:
  8895. if (state.last) {
  8896. //--- BYTEBITS() ---//
  8897. hold >>>= bits & 7;
  8898. bits -= bits & 7;
  8899. //---//
  8900. state.mode = CHECK;
  8901. break;
  8902. }
  8903. //=== NEEDBITS(3); */
  8904. while (bits < 3) {
  8905. if (have === 0) { break inf_leave; }
  8906. have--;
  8907. hold += input[next++] << bits;
  8908. bits += 8;
  8909. }
  8910. //===//
  8911. state.last = (hold & 0x01)/*BITS(1)*/;
  8912. //--- DROPBITS(1) ---//
  8913. hold >>>= 1;
  8914. bits -= 1;
  8915. //---//
  8916. switch ((hold & 0x03)/*BITS(2)*/) {
  8917. case 0: /* stored block */
  8918. //Tracev((stderr, "inflate: stored block%s\n",
  8919. // state.last ? " (last)" : ""));
  8920. state.mode = STORED;
  8921. break;
  8922. case 1: /* fixed block */
  8923. fixedtables(state);
  8924. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8925. // state.last ? " (last)" : ""));
  8926. state.mode = LEN_; /* decode codes */
  8927. if (flush === Z_TREES) {
  8928. //--- DROPBITS(2) ---//
  8929. hold >>>= 2;
  8930. bits -= 2;
  8931. //---//
  8932. break inf_leave;
  8933. }
  8934. break;
  8935. case 2: /* dynamic block */
  8936. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8937. // state.last ? " (last)" : ""));
  8938. state.mode = TABLE;
  8939. break;
  8940. case 3:
  8941. strm.msg = 'invalid block type';
  8942. state.mode = BAD;
  8943. }
  8944. //--- DROPBITS(2) ---//
  8945. hold >>>= 2;
  8946. bits -= 2;
  8947. //---//
  8948. break;
  8949. case STORED:
  8950. //--- BYTEBITS() ---// /* go to byte boundary */
  8951. hold >>>= bits & 7;
  8952. bits -= bits & 7;
  8953. //---//
  8954. //=== NEEDBITS(32); */
  8955. while (bits < 32) {
  8956. if (have === 0) { break inf_leave; }
  8957. have--;
  8958. hold += input[next++] << bits;
  8959. bits += 8;
  8960. }
  8961. //===//
  8962. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8963. strm.msg = 'invalid stored block lengths';
  8964. state.mode = BAD;
  8965. break;
  8966. }
  8967. state.length = hold & 0xffff;
  8968. //Tracev((stderr, "inflate: stored length %u\n",
  8969. // state.length));
  8970. //=== INITBITS();
  8971. hold = 0;
  8972. bits = 0;
  8973. //===//
  8974. state.mode = COPY_;
  8975. if (flush === Z_TREES) { break inf_leave; }
  8976. /* falls through */
  8977. case COPY_:
  8978. state.mode = COPY;
  8979. /* falls through */
  8980. case COPY:
  8981. copy = state.length;
  8982. if (copy) {
  8983. if (copy > have) { copy = have; }
  8984. if (copy > left) { copy = left; }
  8985. if (copy === 0) { break inf_leave; }
  8986. //--- zmemcpy(put, next, copy); ---
  8987. utils.arraySet(output, input, next, copy, put);
  8988. //---//
  8989. have -= copy;
  8990. next += copy;
  8991. left -= copy;
  8992. put += copy;
  8993. state.length -= copy;
  8994. break;
  8995. }
  8996. //Tracev((stderr, "inflate: stored end\n"));
  8997. state.mode = TYPE;
  8998. break;
  8999. case TABLE:
  9000. //=== NEEDBITS(14); */
  9001. while (bits < 14) {
  9002. if (have === 0) { break inf_leave; }
  9003. have--;
  9004. hold += input[next++] << bits;
  9005. bits += 8;
  9006. }
  9007. //===//
  9008. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9009. //--- DROPBITS(5) ---//
  9010. hold >>>= 5;
  9011. bits -= 5;
  9012. //---//
  9013. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9014. //--- DROPBITS(5) ---//
  9015. hold >>>= 5;
  9016. bits -= 5;
  9017. //---//
  9018. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9019. //--- DROPBITS(4) ---//
  9020. hold >>>= 4;
  9021. bits -= 4;
  9022. //---//
  9023. //#ifndef PKZIP_BUG_WORKAROUND
  9024. if (state.nlen > 286 || state.ndist > 30) {
  9025. strm.msg = 'too many length or distance symbols';
  9026. state.mode = BAD;
  9027. break;
  9028. }
  9029. //#endif
  9030. //Tracev((stderr, "inflate: table sizes ok\n"));
  9031. state.have = 0;
  9032. state.mode = LENLENS;
  9033. /* falls through */
  9034. case LENLENS:
  9035. while (state.have < state.ncode) {
  9036. //=== NEEDBITS(3);
  9037. while (bits < 3) {
  9038. if (have === 0) { break inf_leave; }
  9039. have--;
  9040. hold += input[next++] << bits;
  9041. bits += 8;
  9042. }
  9043. //===//
  9044. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9045. //--- DROPBITS(3) ---//
  9046. hold >>>= 3;
  9047. bits -= 3;
  9048. //---//
  9049. }
  9050. while (state.have < 19) {
  9051. state.lens[order[state.have++]] = 0;
  9052. }
  9053. // We have separate tables & no pointers. 2 commented lines below not needed.
  9054. //state.next = state.codes;
  9055. //state.lencode = state.next;
  9056. // Switch to use dynamic table
  9057. state.lencode = state.lendyn;
  9058. state.lenbits = 7;
  9059. opts = { bits: state.lenbits };
  9060. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9061. state.lenbits = opts.bits;
  9062. if (ret) {
  9063. strm.msg = 'invalid code lengths set';
  9064. state.mode = BAD;
  9065. break;
  9066. }
  9067. //Tracev((stderr, "inflate: code lengths ok\n"));
  9068. state.have = 0;
  9069. state.mode = CODELENS;
  9070. /* falls through */
  9071. case CODELENS:
  9072. while (state.have < state.nlen + state.ndist) {
  9073. for (;;) {
  9074. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9075. here_bits = here >>> 24;
  9076. here_op = (here >>> 16) & 0xff;
  9077. here_val = here & 0xffff;
  9078. if ((here_bits) <= bits) { break; }
  9079. //--- PULLBYTE() ---//
  9080. if (have === 0) { break inf_leave; }
  9081. have--;
  9082. hold += input[next++] << bits;
  9083. bits += 8;
  9084. //---//
  9085. }
  9086. if (here_val < 16) {
  9087. //--- DROPBITS(here.bits) ---//
  9088. hold >>>= here_bits;
  9089. bits -= here_bits;
  9090. //---//
  9091. state.lens[state.have++] = here_val;
  9092. }
  9093. else {
  9094. if (here_val === 16) {
  9095. //=== NEEDBITS(here.bits + 2);
  9096. n = here_bits + 2;
  9097. while (bits < n) {
  9098. if (have === 0) { break inf_leave; }
  9099. have--;
  9100. hold += input[next++] << bits;
  9101. bits += 8;
  9102. }
  9103. //===//
  9104. //--- DROPBITS(here.bits) ---//
  9105. hold >>>= here_bits;
  9106. bits -= here_bits;
  9107. //---//
  9108. if (state.have === 0) {
  9109. strm.msg = 'invalid bit length repeat';
  9110. state.mode = BAD;
  9111. break;
  9112. }
  9113. len = state.lens[state.have - 1];
  9114. copy = 3 + (hold & 0x03);//BITS(2);
  9115. //--- DROPBITS(2) ---//
  9116. hold >>>= 2;
  9117. bits -= 2;
  9118. //---//
  9119. }
  9120. else if (here_val === 17) {
  9121. //=== NEEDBITS(here.bits + 3);
  9122. n = here_bits + 3;
  9123. while (bits < n) {
  9124. if (have === 0) { break inf_leave; }
  9125. have--;
  9126. hold += input[next++] << bits;
  9127. bits += 8;
  9128. }
  9129. //===//
  9130. //--- DROPBITS(here.bits) ---//
  9131. hold >>>= here_bits;
  9132. bits -= here_bits;
  9133. //---//
  9134. len = 0;
  9135. copy = 3 + (hold & 0x07);//BITS(3);
  9136. //--- DROPBITS(3) ---//
  9137. hold >>>= 3;
  9138. bits -= 3;
  9139. //---//
  9140. }
  9141. else {
  9142. //=== NEEDBITS(here.bits + 7);
  9143. n = here_bits + 7;
  9144. while (bits < n) {
  9145. if (have === 0) { break inf_leave; }
  9146. have--;
  9147. hold += input[next++] << bits;
  9148. bits += 8;
  9149. }
  9150. //===//
  9151. //--- DROPBITS(here.bits) ---//
  9152. hold >>>= here_bits;
  9153. bits -= here_bits;
  9154. //---//
  9155. len = 0;
  9156. copy = 11 + (hold & 0x7f);//BITS(7);
  9157. //--- DROPBITS(7) ---//
  9158. hold >>>= 7;
  9159. bits -= 7;
  9160. //---//
  9161. }
  9162. if (state.have + copy > state.nlen + state.ndist) {
  9163. strm.msg = 'invalid bit length repeat';
  9164. state.mode = BAD;
  9165. break;
  9166. }
  9167. while (copy--) {
  9168. state.lens[state.have++] = len;
  9169. }
  9170. }
  9171. }
  9172. /* handle error breaks in while */
  9173. if (state.mode === BAD) { break; }
  9174. /* check for end-of-block code (better have one) */
  9175. if (state.lens[256] === 0) {
  9176. strm.msg = 'invalid code -- missing end-of-block';
  9177. state.mode = BAD;
  9178. break;
  9179. }
  9180. /* build code tables -- note: do not change the lenbits or distbits
  9181. values here (9 and 6) without reading the comments in inftrees.h
  9182. concerning the ENOUGH constants, which depend on those values */
  9183. state.lenbits = 9;
  9184. opts = { bits: state.lenbits };
  9185. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9186. // We have separate tables & no pointers. 2 commented lines below not needed.
  9187. // state.next_index = opts.table_index;
  9188. state.lenbits = opts.bits;
  9189. // state.lencode = state.next;
  9190. if (ret) {
  9191. strm.msg = 'invalid literal/lengths set';
  9192. state.mode = BAD;
  9193. break;
  9194. }
  9195. state.distbits = 6;
  9196. //state.distcode.copy(state.codes);
  9197. // Switch to use dynamic table
  9198. state.distcode = state.distdyn;
  9199. opts = { bits: state.distbits };
  9200. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9201. // We have separate tables & no pointers. 2 commented lines below not needed.
  9202. // state.next_index = opts.table_index;
  9203. state.distbits = opts.bits;
  9204. // state.distcode = state.next;
  9205. if (ret) {
  9206. strm.msg = 'invalid distances set';
  9207. state.mode = BAD;
  9208. break;
  9209. }
  9210. //Tracev((stderr, 'inflate: codes ok\n'));
  9211. state.mode = LEN_;
  9212. if (flush === Z_TREES) { break inf_leave; }
  9213. /* falls through */
  9214. case LEN_:
  9215. state.mode = LEN;
  9216. /* falls through */
  9217. case LEN:
  9218. if (have >= 6 && left >= 258) {
  9219. //--- RESTORE() ---
  9220. strm.next_out = put;
  9221. strm.avail_out = left;
  9222. strm.next_in = next;
  9223. strm.avail_in = have;
  9224. state.hold = hold;
  9225. state.bits = bits;
  9226. //---
  9227. inflate_fast(strm, _out);
  9228. //--- LOAD() ---
  9229. put = strm.next_out;
  9230. output = strm.output;
  9231. left = strm.avail_out;
  9232. next = strm.next_in;
  9233. input = strm.input;
  9234. have = strm.avail_in;
  9235. hold = state.hold;
  9236. bits = state.bits;
  9237. //---
  9238. if (state.mode === TYPE) {
  9239. state.back = -1;
  9240. }
  9241. break;
  9242. }
  9243. state.back = 0;
  9244. for (;;) {
  9245. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9246. here_bits = here >>> 24;
  9247. here_op = (here >>> 16) & 0xff;
  9248. here_val = here & 0xffff;
  9249. if (here_bits <= bits) { break; }
  9250. //--- PULLBYTE() ---//
  9251. if (have === 0) { break inf_leave; }
  9252. have--;
  9253. hold += input[next++] << bits;
  9254. bits += 8;
  9255. //---//
  9256. }
  9257. if (here_op && (here_op & 0xf0) === 0) {
  9258. last_bits = here_bits;
  9259. last_op = here_op;
  9260. last_val = here_val;
  9261. for (;;) {
  9262. here = state.lencode[last_val +
  9263. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9264. here_bits = here >>> 24;
  9265. here_op = (here >>> 16) & 0xff;
  9266. here_val = here & 0xffff;
  9267. if ((last_bits + here_bits) <= bits) { break; }
  9268. //--- PULLBYTE() ---//
  9269. if (have === 0) { break inf_leave; }
  9270. have--;
  9271. hold += input[next++] << bits;
  9272. bits += 8;
  9273. //---//
  9274. }
  9275. //--- DROPBITS(last.bits) ---//
  9276. hold >>>= last_bits;
  9277. bits -= last_bits;
  9278. //---//
  9279. state.back += last_bits;
  9280. }
  9281. //--- DROPBITS(here.bits) ---//
  9282. hold >>>= here_bits;
  9283. bits -= here_bits;
  9284. //---//
  9285. state.back += here_bits;
  9286. state.length = here_val;
  9287. if (here_op === 0) {
  9288. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9289. // "inflate: literal '%c'\n" :
  9290. // "inflate: literal 0x%02x\n", here.val));
  9291. state.mode = LIT;
  9292. break;
  9293. }
  9294. if (here_op & 32) {
  9295. //Tracevv((stderr, "inflate: end of block\n"));
  9296. state.back = -1;
  9297. state.mode = TYPE;
  9298. break;
  9299. }
  9300. if (here_op & 64) {
  9301. strm.msg = 'invalid literal/length code';
  9302. state.mode = BAD;
  9303. break;
  9304. }
  9305. state.extra = here_op & 15;
  9306. state.mode = LENEXT;
  9307. /* falls through */
  9308. case LENEXT:
  9309. if (state.extra) {
  9310. //=== NEEDBITS(state.extra);
  9311. n = state.extra;
  9312. while (bits < n) {
  9313. if (have === 0) { break inf_leave; }
  9314. have--;
  9315. hold += input[next++] << bits;
  9316. bits += 8;
  9317. }
  9318. //===//
  9319. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9320. //--- DROPBITS(state.extra) ---//
  9321. hold >>>= state.extra;
  9322. bits -= state.extra;
  9323. //---//
  9324. state.back += state.extra;
  9325. }
  9326. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9327. state.was = state.length;
  9328. state.mode = DIST;
  9329. /* falls through */
  9330. case DIST:
  9331. for (;;) {
  9332. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9333. here_bits = here >>> 24;
  9334. here_op = (here >>> 16) & 0xff;
  9335. here_val = here & 0xffff;
  9336. if ((here_bits) <= bits) { break; }
  9337. //--- PULLBYTE() ---//
  9338. if (have === 0) { break inf_leave; }
  9339. have--;
  9340. hold += input[next++] << bits;
  9341. bits += 8;
  9342. //---//
  9343. }
  9344. if ((here_op & 0xf0) === 0) {
  9345. last_bits = here_bits;
  9346. last_op = here_op;
  9347. last_val = here_val;
  9348. for (;;) {
  9349. here = state.distcode[last_val +
  9350. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9351. here_bits = here >>> 24;
  9352. here_op = (here >>> 16) & 0xff;
  9353. here_val = here & 0xffff;
  9354. if ((last_bits + here_bits) <= bits) { break; }
  9355. //--- PULLBYTE() ---//
  9356. if (have === 0) { break inf_leave; }
  9357. have--;
  9358. hold += input[next++] << bits;
  9359. bits += 8;
  9360. //---//
  9361. }
  9362. //--- DROPBITS(last.bits) ---//
  9363. hold >>>= last_bits;
  9364. bits -= last_bits;
  9365. //---//
  9366. state.back += last_bits;
  9367. }
  9368. //--- DROPBITS(here.bits) ---//
  9369. hold >>>= here_bits;
  9370. bits -= here_bits;
  9371. //---//
  9372. state.back += here_bits;
  9373. if (here_op & 64) {
  9374. strm.msg = 'invalid distance code';
  9375. state.mode = BAD;
  9376. break;
  9377. }
  9378. state.offset = here_val;
  9379. state.extra = (here_op) & 15;
  9380. state.mode = DISTEXT;
  9381. /* falls through */
  9382. case DISTEXT:
  9383. if (state.extra) {
  9384. //=== NEEDBITS(state.extra);
  9385. n = state.extra;
  9386. while (bits < n) {
  9387. if (have === 0) { break inf_leave; }
  9388. have--;
  9389. hold += input[next++] << bits;
  9390. bits += 8;
  9391. }
  9392. //===//
  9393. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9394. //--- DROPBITS(state.extra) ---//
  9395. hold >>>= state.extra;
  9396. bits -= state.extra;
  9397. //---//
  9398. state.back += state.extra;
  9399. }
  9400. //#ifdef INFLATE_STRICT
  9401. if (state.offset > state.dmax) {
  9402. strm.msg = 'invalid distance too far back';
  9403. state.mode = BAD;
  9404. break;
  9405. }
  9406. //#endif
  9407. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9408. state.mode = MATCH;
  9409. /* falls through */
  9410. case MATCH:
  9411. if (left === 0) { break inf_leave; }
  9412. copy = _out - left;
  9413. if (state.offset > copy) { /* copy from window */
  9414. copy = state.offset - copy;
  9415. if (copy > state.whave) {
  9416. if (state.sane) {
  9417. strm.msg = 'invalid distance too far back';
  9418. state.mode = BAD;
  9419. break;
  9420. }
  9421. // (!) This block is disabled in zlib defaults,
  9422. // don't enable it for binary compatibility
  9423. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9424. // Trace((stderr, "inflate.c too far\n"));
  9425. // copy -= state.whave;
  9426. // if (copy > state.length) { copy = state.length; }
  9427. // if (copy > left) { copy = left; }
  9428. // left -= copy;
  9429. // state.length -= copy;
  9430. // do {
  9431. // output[put++] = 0;
  9432. // } while (--copy);
  9433. // if (state.length === 0) { state.mode = LEN; }
  9434. // break;
  9435. //#endif
  9436. }
  9437. if (copy > state.wnext) {
  9438. copy -= state.wnext;
  9439. from = state.wsize - copy;
  9440. }
  9441. else {
  9442. from = state.wnext - copy;
  9443. }
  9444. if (copy > state.length) { copy = state.length; }
  9445. from_source = state.window;
  9446. }
  9447. else { /* copy from output */
  9448. from_source = output;
  9449. from = put - state.offset;
  9450. copy = state.length;
  9451. }
  9452. if (copy > left) { copy = left; }
  9453. left -= copy;
  9454. state.length -= copy;
  9455. do {
  9456. output[put++] = from_source[from++];
  9457. } while (--copy);
  9458. if (state.length === 0) { state.mode = LEN; }
  9459. break;
  9460. case LIT:
  9461. if (left === 0) { break inf_leave; }
  9462. output[put++] = state.length;
  9463. left--;
  9464. state.mode = LEN;
  9465. break;
  9466. case CHECK:
  9467. if (state.wrap) {
  9468. //=== NEEDBITS(32);
  9469. while (bits < 32) {
  9470. if (have === 0) { break inf_leave; }
  9471. have--;
  9472. // Use '|' instead of '+' to make sure that result is signed
  9473. hold |= input[next++] << bits;
  9474. bits += 8;
  9475. }
  9476. //===//
  9477. _out -= left;
  9478. strm.total_out += _out;
  9479. state.total += _out;
  9480. if (_out) {
  9481. strm.adler = state.check =
  9482. /*UPDATE(state.check, put - _out, _out);*/
  9483. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9484. }
  9485. _out = left;
  9486. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9487. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9488. strm.msg = 'incorrect data check';
  9489. state.mode = BAD;
  9490. break;
  9491. }
  9492. //=== INITBITS();
  9493. hold = 0;
  9494. bits = 0;
  9495. //===//
  9496. //Tracev((stderr, "inflate: check matches trailer\n"));
  9497. }
  9498. state.mode = LENGTH;
  9499. /* falls through */
  9500. case LENGTH:
  9501. if (state.wrap && state.flags) {
  9502. //=== NEEDBITS(32);
  9503. while (bits < 32) {
  9504. if (have === 0) { break inf_leave; }
  9505. have--;
  9506. hold += input[next++] << bits;
  9507. bits += 8;
  9508. }
  9509. //===//
  9510. if (hold !== (state.total & 0xffffffff)) {
  9511. strm.msg = 'incorrect length check';
  9512. state.mode = BAD;
  9513. break;
  9514. }
  9515. //=== INITBITS();
  9516. hold = 0;
  9517. bits = 0;
  9518. //===//
  9519. //Tracev((stderr, "inflate: length matches trailer\n"));
  9520. }
  9521. state.mode = DONE;
  9522. /* falls through */
  9523. case DONE:
  9524. ret = Z_STREAM_END;
  9525. break inf_leave;
  9526. case BAD:
  9527. ret = Z_DATA_ERROR;
  9528. break inf_leave;
  9529. case MEM:
  9530. return Z_MEM_ERROR;
  9531. case SYNC:
  9532. /* falls through */
  9533. default:
  9534. return Z_STREAM_ERROR;
  9535. }
  9536. }
  9537. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9538. /*
  9539. Return from inflate(), updating the total counts and the check value.
  9540. If there was no progress during the inflate() call, return a buffer
  9541. error. Call updatewindow() to create and/or update the window state.
  9542. Note: a memory error from inflate() is non-recoverable.
  9543. */
  9544. //--- RESTORE() ---
  9545. strm.next_out = put;
  9546. strm.avail_out = left;
  9547. strm.next_in = next;
  9548. strm.avail_in = have;
  9549. state.hold = hold;
  9550. state.bits = bits;
  9551. //---
  9552. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9553. (state.mode < CHECK || flush !== Z_FINISH))) {
  9554. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9555. state.mode = MEM;
  9556. return Z_MEM_ERROR;
  9557. }
  9558. }
  9559. _in -= strm.avail_in;
  9560. _out -= strm.avail_out;
  9561. strm.total_in += _in;
  9562. strm.total_out += _out;
  9563. state.total += _out;
  9564. if (state.wrap && _out) {
  9565. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9566. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9567. }
  9568. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9569. (state.mode === TYPE ? 128 : 0) +
  9570. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9571. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9572. ret = Z_BUF_ERROR;
  9573. }
  9574. return ret;
  9575. }
  9576. function inflateEnd(strm) {
  9577. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9578. return Z_STREAM_ERROR;
  9579. }
  9580. var state = strm.state;
  9581. if (state.window) {
  9582. state.window = null;
  9583. }
  9584. strm.state = null;
  9585. return Z_OK;
  9586. }
  9587. function inflateGetHeader(strm, head) {
  9588. var state;
  9589. /* check state */
  9590. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9591. state = strm.state;
  9592. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9593. /* save header structure */
  9594. state.head = head;
  9595. head.done = false;
  9596. return Z_OK;
  9597. }
  9598. function inflateSetDictionary(strm, dictionary) {
  9599. var dictLength = dictionary.length;
  9600. var state;
  9601. var dictid;
  9602. var ret;
  9603. /* check state */
  9604. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9605. state = strm.state;
  9606. if (state.wrap !== 0 && state.mode !== DICT) {
  9607. return Z_STREAM_ERROR;
  9608. }
  9609. /* check for correct dictionary identifier */
  9610. if (state.mode === DICT) {
  9611. dictid = 1; /* adler32(0, null, 0)*/
  9612. /* dictid = adler32(dictid, dictionary, dictLength); */
  9613. dictid = adler32(dictid, dictionary, dictLength, 0);
  9614. if (dictid !== state.check) {
  9615. return Z_DATA_ERROR;
  9616. }
  9617. }
  9618. /* copy dictionary to window using updatewindow(), which will amend the
  9619. existing dictionary if appropriate */
  9620. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9621. if (ret) {
  9622. state.mode = MEM;
  9623. return Z_MEM_ERROR;
  9624. }
  9625. state.havedict = 1;
  9626. // Tracev((stderr, "inflate: dictionary set\n"));
  9627. return Z_OK;
  9628. }
  9629. exports.inflateReset = inflateReset;
  9630. exports.inflateReset2 = inflateReset2;
  9631. exports.inflateResetKeep = inflateResetKeep;
  9632. exports.inflateInit = inflateInit;
  9633. exports.inflateInit2 = inflateInit2;
  9634. exports.inflate = inflate;
  9635. exports.inflateEnd = inflateEnd;
  9636. exports.inflateGetHeader = inflateGetHeader;
  9637. exports.inflateSetDictionary = inflateSetDictionary;
  9638. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9639. /* Not implemented
  9640. exports.inflateCopy = inflateCopy;
  9641. exports.inflateGetDictionary = inflateGetDictionary;
  9642. exports.inflateMark = inflateMark;
  9643. exports.inflatePrime = inflatePrime;
  9644. exports.inflateSync = inflateSync;
  9645. exports.inflateSyncPoint = inflateSyncPoint;
  9646. exports.inflateUndermine = inflateUndermine;
  9647. */
  9648. },{"../utils/common":39,"./adler32":40,"./crc32":42,"./inffast":44,"./inftrees":46}],46:[function(require,module,exports){
  9649. 'use strict';
  9650. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9651. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9652. //
  9653. // This software is provided 'as-is', without any express or implied
  9654. // warranty. In no event will the authors be held liable for any damages
  9655. // arising from the use of this software.
  9656. //
  9657. // Permission is granted to anyone to use this software for any purpose,
  9658. // including commercial applications, and to alter it and redistribute it
  9659. // freely, subject to the following restrictions:
  9660. //
  9661. // 1. The origin of this software must not be misrepresented; you must not
  9662. // claim that you wrote the original software. If you use this software
  9663. // in a product, an acknowledgment in the product documentation would be
  9664. // appreciated but is not required.
  9665. // 2. Altered source versions must be plainly marked as such, and must not be
  9666. // misrepresented as being the original software.
  9667. // 3. This notice may not be removed or altered from any source distribution.
  9668. var utils = require('../utils/common');
  9669. var MAXBITS = 15;
  9670. var ENOUGH_LENS = 852;
  9671. var ENOUGH_DISTS = 592;
  9672. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9673. var CODES = 0;
  9674. var LENS = 1;
  9675. var DISTS = 2;
  9676. var lbase = [ /* Length codes 257..285 base */
  9677. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9678. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9679. ];
  9680. var lext = [ /* Length codes 257..285 extra */
  9681. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9682. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9683. ];
  9684. var dbase = [ /* Distance codes 0..29 base */
  9685. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9686. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9687. 8193, 12289, 16385, 24577, 0, 0
  9688. ];
  9689. var dext = [ /* Distance codes 0..29 extra */
  9690. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9691. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9692. 28, 28, 29, 29, 64, 64
  9693. ];
  9694. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9695. {
  9696. var bits = opts.bits;
  9697. //here = opts.here; /* table entry for duplication */
  9698. var len = 0; /* a code's length in bits */
  9699. var sym = 0; /* index of code symbols */
  9700. var min = 0, max = 0; /* minimum and maximum code lengths */
  9701. var root = 0; /* number of index bits for root table */
  9702. var curr = 0; /* number of index bits for current table */
  9703. var drop = 0; /* code bits to drop for sub-table */
  9704. var left = 0; /* number of prefix codes available */
  9705. var used = 0; /* code entries in table used */
  9706. var huff = 0; /* Huffman code */
  9707. var incr; /* for incrementing code, index */
  9708. var fill; /* index for replicating entries */
  9709. var low; /* low bits for current root entry */
  9710. var mask; /* mask for low root bits */
  9711. var next; /* next available space in table */
  9712. var base = null; /* base value table to use */
  9713. var base_index = 0;
  9714. // var shoextra; /* extra bits table to use */
  9715. var end; /* use base and extra for symbol > end */
  9716. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  9717. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  9718. var extra = null;
  9719. var extra_index = 0;
  9720. var here_bits, here_op, here_val;
  9721. /*
  9722. Process a set of code lengths to create a canonical Huffman code. The
  9723. code lengths are lens[0..codes-1]. Each length corresponds to the
  9724. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9725. symbols by length from short to long, and retaining the symbol order
  9726. for codes with equal lengths. Then the code starts with all zero bits
  9727. for the first code of the shortest length, and the codes are integer
  9728. increments for the same length, and zeros are appended as the length
  9729. increases. For the deflate format, these bits are stored backwards
  9730. from their more natural integer increment ordering, and so when the
  9731. decoding tables are built in the large loop below, the integer codes
  9732. are incremented backwards.
  9733. This routine assumes, but does not check, that all of the entries in
  9734. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9735. 1..MAXBITS is interpreted as that code length. zero means that that
  9736. symbol does not occur in this code.
  9737. The codes are sorted by computing a count of codes for each length,
  9738. creating from that a table of starting indices for each length in the
  9739. sorted table, and then entering the symbols in order in the sorted
  9740. table. The sorted table is work[], with that space being provided by
  9741. the caller.
  9742. The length counts are used for other purposes as well, i.e. finding
  9743. the minimum and maximum length codes, determining if there are any
  9744. codes at all, checking for a valid set of lengths, and looking ahead
  9745. at length counts to determine sub-table sizes when building the
  9746. decoding tables.
  9747. */
  9748. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9749. for (len = 0; len <= MAXBITS; len++) {
  9750. count[len] = 0;
  9751. }
  9752. for (sym = 0; sym < codes; sym++) {
  9753. count[lens[lens_index + sym]]++;
  9754. }
  9755. /* bound code lengths, force root to be within code lengths */
  9756. root = bits;
  9757. for (max = MAXBITS; max >= 1; max--) {
  9758. if (count[max] !== 0) { break; }
  9759. }
  9760. if (root > max) {
  9761. root = max;
  9762. }
  9763. if (max === 0) { /* no symbols to code at all */
  9764. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9765. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9766. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9767. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9768. //table.op[opts.table_index] = 64;
  9769. //table.bits[opts.table_index] = 1;
  9770. //table.val[opts.table_index++] = 0;
  9771. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9772. opts.bits = 1;
  9773. return 0; /* no symbols, but wait for decoding to report error */
  9774. }
  9775. for (min = 1; min < max; min++) {
  9776. if (count[min] !== 0) { break; }
  9777. }
  9778. if (root < min) {
  9779. root = min;
  9780. }
  9781. /* check for an over-subscribed or incomplete set of lengths */
  9782. left = 1;
  9783. for (len = 1; len <= MAXBITS; len++) {
  9784. left <<= 1;
  9785. left -= count[len];
  9786. if (left < 0) {
  9787. return -1;
  9788. } /* over-subscribed */
  9789. }
  9790. if (left > 0 && (type === CODES || max !== 1)) {
  9791. return -1; /* incomplete set */
  9792. }
  9793. /* generate offsets into symbol table for each length for sorting */
  9794. offs[1] = 0;
  9795. for (len = 1; len < MAXBITS; len++) {
  9796. offs[len + 1] = offs[len] + count[len];
  9797. }
  9798. /* sort symbols by length, by symbol order within each length */
  9799. for (sym = 0; sym < codes; sym++) {
  9800. if (lens[lens_index + sym] !== 0) {
  9801. work[offs[lens[lens_index + sym]]++] = sym;
  9802. }
  9803. }
  9804. /*
  9805. Create and fill in decoding tables. In this loop, the table being
  9806. filled is at next and has curr index bits. The code being used is huff
  9807. with length len. That code is converted to an index by dropping drop
  9808. bits off of the bottom. For codes where len is less than drop + curr,
  9809. those top drop + curr - len bits are incremented through all values to
  9810. fill the table with replicated entries.
  9811. root is the number of index bits for the root table. When len exceeds
  9812. root, sub-tables are created pointed to by the root entry with an index
  9813. of the low root bits of huff. This is saved in low to check for when a
  9814. new sub-table should be started. drop is zero when the root table is
  9815. being filled, and drop is root when sub-tables are being filled.
  9816. When a new sub-table is needed, it is necessary to look ahead in the
  9817. code lengths to determine what size sub-table is needed. The length
  9818. counts are used for this, and so count[] is decremented as codes are
  9819. entered in the tables.
  9820. used keeps track of how many table entries have been allocated from the
  9821. provided *table space. It is checked for LENS and DIST tables against
  9822. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9823. the initial root table size constants. See the comments in inftrees.h
  9824. for more information.
  9825. sym increments through all symbols, and the loop terminates when
  9826. all codes of length max, i.e. all codes, have been processed. This
  9827. routine permits incomplete codes, so another loop after this one fills
  9828. in the rest of the decoding tables with invalid code markers.
  9829. */
  9830. /* set up for code type */
  9831. // poor man optimization - use if-else instead of switch,
  9832. // to avoid deopts in old v8
  9833. if (type === CODES) {
  9834. base = extra = work; /* dummy value--not used */
  9835. end = 19;
  9836. } else if (type === LENS) {
  9837. base = lbase;
  9838. base_index -= 257;
  9839. extra = lext;
  9840. extra_index -= 257;
  9841. end = 256;
  9842. } else { /* DISTS */
  9843. base = dbase;
  9844. extra = dext;
  9845. end = -1;
  9846. }
  9847. /* initialize opts for loop */
  9848. huff = 0; /* starting code */
  9849. sym = 0; /* starting code symbol */
  9850. len = min; /* starting code length */
  9851. next = table_index; /* current table to fill in */
  9852. curr = root; /* current table index bits */
  9853. drop = 0; /* current bits to drop from code for index */
  9854. low = -1; /* trigger new sub-table when len > root */
  9855. used = 1 << root; /* use root table entries */
  9856. mask = used - 1; /* mask for comparing low */
  9857. /* check available table space */
  9858. if ((type === LENS && used > ENOUGH_LENS) ||
  9859. (type === DISTS && used > ENOUGH_DISTS)) {
  9860. return 1;
  9861. }
  9862. /* process all codes and make table entries */
  9863. for (;;) {
  9864. /* create table entry */
  9865. here_bits = len - drop;
  9866. if (work[sym] < end) {
  9867. here_op = 0;
  9868. here_val = work[sym];
  9869. }
  9870. else if (work[sym] > end) {
  9871. here_op = extra[extra_index + work[sym]];
  9872. here_val = base[base_index + work[sym]];
  9873. }
  9874. else {
  9875. here_op = 32 + 64; /* end of block */
  9876. here_val = 0;
  9877. }
  9878. /* replicate for those indices with low len bits equal to huff */
  9879. incr = 1 << (len - drop);
  9880. fill = 1 << curr;
  9881. min = fill; /* save offset to next table */
  9882. do {
  9883. fill -= incr;
  9884. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9885. } while (fill !== 0);
  9886. /* backwards increment the len-bit code huff */
  9887. incr = 1 << (len - 1);
  9888. while (huff & incr) {
  9889. incr >>= 1;
  9890. }
  9891. if (incr !== 0) {
  9892. huff &= incr - 1;
  9893. huff += incr;
  9894. } else {
  9895. huff = 0;
  9896. }
  9897. /* go to next symbol, update count, len */
  9898. sym++;
  9899. if (--count[len] === 0) {
  9900. if (len === max) { break; }
  9901. len = lens[lens_index + work[sym]];
  9902. }
  9903. /* create new sub-table if needed */
  9904. if (len > root && (huff & mask) !== low) {
  9905. /* if first time, transition to sub-tables */
  9906. if (drop === 0) {
  9907. drop = root;
  9908. }
  9909. /* increment past last table */
  9910. next += min; /* here min is 1 << curr */
  9911. /* determine length of next table */
  9912. curr = len - drop;
  9913. left = 1 << curr;
  9914. while (curr + drop < max) {
  9915. left -= count[curr + drop];
  9916. if (left <= 0) { break; }
  9917. curr++;
  9918. left <<= 1;
  9919. }
  9920. /* check for enough space */
  9921. used += 1 << curr;
  9922. if ((type === LENS && used > ENOUGH_LENS) ||
  9923. (type === DISTS && used > ENOUGH_DISTS)) {
  9924. return 1;
  9925. }
  9926. /* point entry in root table to sub-table */
  9927. low = huff & mask;
  9928. /*table.op[low] = curr;
  9929. table.bits[low] = root;
  9930. table.val[low] = next - opts.table_index;*/
  9931. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  9932. }
  9933. }
  9934. /* fill in remaining table entry if code is incomplete (guaranteed to have
  9935. at most one remaining entry, since if the code is incomplete, the
  9936. maximum code length that was allowed to get this far is one bit) */
  9937. if (huff !== 0) {
  9938. //table.op[next + huff] = 64; /* invalid code marker */
  9939. //table.bits[next + huff] = len - drop;
  9940. //table.val[next + huff] = 0;
  9941. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  9942. }
  9943. /* set return parameters */
  9944. //opts.table_index += used;
  9945. opts.bits = root;
  9946. return 0;
  9947. };
  9948. },{"../utils/common":39}],47:[function(require,module,exports){
  9949. 'use strict';
  9950. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9951. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9952. //
  9953. // This software is provided 'as-is', without any express or implied
  9954. // warranty. In no event will the authors be held liable for any damages
  9955. // arising from the use of this software.
  9956. //
  9957. // Permission is granted to anyone to use this software for any purpose,
  9958. // including commercial applications, and to alter it and redistribute it
  9959. // freely, subject to the following restrictions:
  9960. //
  9961. // 1. The origin of this software must not be misrepresented; you must not
  9962. // claim that you wrote the original software. If you use this software
  9963. // in a product, an acknowledgment in the product documentation would be
  9964. // appreciated but is not required.
  9965. // 2. Altered source versions must be plainly marked as such, and must not be
  9966. // misrepresented as being the original software.
  9967. // 3. This notice may not be removed or altered from any source distribution.
  9968. module.exports = {
  9969. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  9970. 1: 'stream end', /* Z_STREAM_END 1 */
  9971. 0: '', /* Z_OK 0 */
  9972. '-1': 'file error', /* Z_ERRNO (-1) */
  9973. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  9974. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  9975. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  9976. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  9977. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  9978. };
  9979. },{}],48:[function(require,module,exports){
  9980. 'use strict';
  9981. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9982. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9983. //
  9984. // This software is provided 'as-is', without any express or implied
  9985. // warranty. In no event will the authors be held liable for any damages
  9986. // arising from the use of this software.
  9987. //
  9988. // Permission is granted to anyone to use this software for any purpose,
  9989. // including commercial applications, and to alter it and redistribute it
  9990. // freely, subject to the following restrictions:
  9991. //
  9992. // 1. The origin of this software must not be misrepresented; you must not
  9993. // claim that you wrote the original software. If you use this software
  9994. // in a product, an acknowledgment in the product documentation would be
  9995. // appreciated but is not required.
  9996. // 2. Altered source versions must be plainly marked as such, and must not be
  9997. // misrepresented as being the original software.
  9998. // 3. This notice may not be removed or altered from any source distribution.
  9999. /* eslint-disable space-unary-ops */
  10000. var utils = require('../utils/common');
  10001. /* Public constants ==========================================================*/
  10002. /* ===========================================================================*/
  10003. //var Z_FILTERED = 1;
  10004. //var Z_HUFFMAN_ONLY = 2;
  10005. //var Z_RLE = 3;
  10006. var Z_FIXED = 4;
  10007. //var Z_DEFAULT_STRATEGY = 0;
  10008. /* Possible values of the data_type field (though see inflate()) */
  10009. var Z_BINARY = 0;
  10010. var Z_TEXT = 1;
  10011. //var Z_ASCII = 1; // = Z_TEXT
  10012. var Z_UNKNOWN = 2;
  10013. /*============================================================================*/
  10014. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10015. // From zutil.h
  10016. var STORED_BLOCK = 0;
  10017. var STATIC_TREES = 1;
  10018. var DYN_TREES = 2;
  10019. /* The three kinds of block type */
  10020. var MIN_MATCH = 3;
  10021. var MAX_MATCH = 258;
  10022. /* The minimum and maximum match lengths */
  10023. // From deflate.h
  10024. /* ===========================================================================
  10025. * Internal compression state.
  10026. */
  10027. var LENGTH_CODES = 29;
  10028. /* number of length codes, not counting the special END_BLOCK code */
  10029. var LITERALS = 256;
  10030. /* number of literal bytes 0..255 */
  10031. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10032. /* number of Literal or Length codes, including the END_BLOCK code */
  10033. var D_CODES = 30;
  10034. /* number of distance codes */
  10035. var BL_CODES = 19;
  10036. /* number of codes used to transfer the bit lengths */
  10037. var HEAP_SIZE = 2 * L_CODES + 1;
  10038. /* maximum heap size */
  10039. var MAX_BITS = 15;
  10040. /* All codes must not exceed MAX_BITS bits */
  10041. var Buf_size = 16;
  10042. /* size of bit buffer in bi_buf */
  10043. /* ===========================================================================
  10044. * Constants
  10045. */
  10046. var MAX_BL_BITS = 7;
  10047. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10048. var END_BLOCK = 256;
  10049. /* end of block literal code */
  10050. var REP_3_6 = 16;
  10051. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10052. var REPZ_3_10 = 17;
  10053. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10054. var REPZ_11_138 = 18;
  10055. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10056. /* eslint-disable comma-spacing,array-bracket-spacing */
  10057. var extra_lbits = /* extra bits for each length code */
  10058. [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];
  10059. var extra_dbits = /* extra bits for each distance code */
  10060. [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];
  10061. var extra_blbits = /* extra bits for each bit length code */
  10062. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10063. var bl_order =
  10064. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10065. /* eslint-enable comma-spacing,array-bracket-spacing */
  10066. /* The lengths of the bit length codes are sent in order of decreasing
  10067. * probability, to avoid transmitting the lengths for unused bit length codes.
  10068. */
  10069. /* ===========================================================================
  10070. * Local data. These are initialized only once.
  10071. */
  10072. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10073. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10074. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  10075. var static_ltree = new Array((L_CODES + 2) * 2);
  10076. zero(static_ltree);
  10077. /* The static literal tree. Since the bit lengths are imposed, there is no
  10078. * need for the L_CODES extra codes used during heap construction. However
  10079. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10080. * below).
  10081. */
  10082. var static_dtree = new Array(D_CODES * 2);
  10083. zero(static_dtree);
  10084. /* The static distance tree. (Actually a trivial tree since all codes use
  10085. * 5 bits.)
  10086. */
  10087. var _dist_code = new Array(DIST_CODE_LEN);
  10088. zero(_dist_code);
  10089. /* Distance codes. The first 256 values correspond to the distances
  10090. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10091. * the 15 bit distances.
  10092. */
  10093. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10094. zero(_length_code);
  10095. /* length code for each normalized match length (0 == MIN_MATCH) */
  10096. var base_length = new Array(LENGTH_CODES);
  10097. zero(base_length);
  10098. /* First normalized length for each code (0 = MIN_MATCH) */
  10099. var base_dist = new Array(D_CODES);
  10100. zero(base_dist);
  10101. /* First normalized distance for each code (0 = distance of 1) */
  10102. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10103. this.static_tree = static_tree; /* static tree or NULL */
  10104. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10105. this.extra_base = extra_base; /* base index for extra_bits */
  10106. this.elems = elems; /* max number of elements in the tree */
  10107. this.max_length = max_length; /* max bit length for the codes */
  10108. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10109. this.has_stree = static_tree && static_tree.length;
  10110. }
  10111. var static_l_desc;
  10112. var static_d_desc;
  10113. var static_bl_desc;
  10114. function TreeDesc(dyn_tree, stat_desc) {
  10115. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10116. this.max_code = 0; /* largest code with non zero frequency */
  10117. this.stat_desc = stat_desc; /* the corresponding static tree */
  10118. }
  10119. function d_code(dist) {
  10120. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10121. }
  10122. /* ===========================================================================
  10123. * Output a short LSB first on the stream.
  10124. * IN assertion: there is enough room in pendingBuf.
  10125. */
  10126. function put_short(s, w) {
  10127. // put_byte(s, (uch)((w) & 0xff));
  10128. // put_byte(s, (uch)((ush)(w) >> 8));
  10129. s.pending_buf[s.pending++] = (w) & 0xff;
  10130. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10131. }
  10132. /* ===========================================================================
  10133. * Send a value on a given number of bits.
  10134. * IN assertion: length <= 16 and value fits in length bits.
  10135. */
  10136. function send_bits(s, value, length) {
  10137. if (s.bi_valid > (Buf_size - length)) {
  10138. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10139. put_short(s, s.bi_buf);
  10140. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10141. s.bi_valid += length - Buf_size;
  10142. } else {
  10143. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10144. s.bi_valid += length;
  10145. }
  10146. }
  10147. function send_code(s, c, tree) {
  10148. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10149. }
  10150. /* ===========================================================================
  10151. * Reverse the first len bits of a code, using straightforward code (a faster
  10152. * method would use a table)
  10153. * IN assertion: 1 <= len <= 15
  10154. */
  10155. function bi_reverse(code, len) {
  10156. var res = 0;
  10157. do {
  10158. res |= code & 1;
  10159. code >>>= 1;
  10160. res <<= 1;
  10161. } while (--len > 0);
  10162. return res >>> 1;
  10163. }
  10164. /* ===========================================================================
  10165. * Flush the bit buffer, keeping at most 7 bits in it.
  10166. */
  10167. function bi_flush(s) {
  10168. if (s.bi_valid === 16) {
  10169. put_short(s, s.bi_buf);
  10170. s.bi_buf = 0;
  10171. s.bi_valid = 0;
  10172. } else if (s.bi_valid >= 8) {
  10173. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10174. s.bi_buf >>= 8;
  10175. s.bi_valid -= 8;
  10176. }
  10177. }
  10178. /* ===========================================================================
  10179. * Compute the optimal bit lengths for a tree and update the total bit length
  10180. * for the current block.
  10181. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10182. * above are the tree nodes sorted by increasing frequency.
  10183. * OUT assertions: the field len is set to the optimal bit length, the
  10184. * array bl_count contains the frequencies for each bit length.
  10185. * The length opt_len is updated; static_len is also updated if stree is
  10186. * not null.
  10187. */
  10188. function gen_bitlen(s, desc)
  10189. // deflate_state *s;
  10190. // tree_desc *desc; /* the tree descriptor */
  10191. {
  10192. var tree = desc.dyn_tree;
  10193. var max_code = desc.max_code;
  10194. var stree = desc.stat_desc.static_tree;
  10195. var has_stree = desc.stat_desc.has_stree;
  10196. var extra = desc.stat_desc.extra_bits;
  10197. var base = desc.stat_desc.extra_base;
  10198. var max_length = desc.stat_desc.max_length;
  10199. var h; /* heap index */
  10200. var n, m; /* iterate over the tree elements */
  10201. var bits; /* bit length */
  10202. var xbits; /* extra bits */
  10203. var f; /* frequency */
  10204. var overflow = 0; /* number of elements with bit length too large */
  10205. for (bits = 0; bits <= MAX_BITS; bits++) {
  10206. s.bl_count[bits] = 0;
  10207. }
  10208. /* In a first pass, compute the optimal bit lengths (which may
  10209. * overflow in the case of the bit length tree).
  10210. */
  10211. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10212. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10213. n = s.heap[h];
  10214. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10215. if (bits > max_length) {
  10216. bits = max_length;
  10217. overflow++;
  10218. }
  10219. tree[n * 2 + 1]/*.Len*/ = bits;
  10220. /* We overwrite tree[n].Dad which is no longer needed */
  10221. if (n > max_code) { continue; } /* not a leaf node */
  10222. s.bl_count[bits]++;
  10223. xbits = 0;
  10224. if (n >= base) {
  10225. xbits = extra[n - base];
  10226. }
  10227. f = tree[n * 2]/*.Freq*/;
  10228. s.opt_len += f * (bits + xbits);
  10229. if (has_stree) {
  10230. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10231. }
  10232. }
  10233. if (overflow === 0) { return; }
  10234. // Trace((stderr,"\nbit length overflow\n"));
  10235. /* This happens for example on obj2 and pic of the Calgary corpus */
  10236. /* Find the first bit length which could increase: */
  10237. do {
  10238. bits = max_length - 1;
  10239. while (s.bl_count[bits] === 0) { bits--; }
  10240. s.bl_count[bits]--; /* move one leaf down the tree */
  10241. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10242. s.bl_count[max_length]--;
  10243. /* The brother of the overflow item also moves one step up,
  10244. * but this does not affect bl_count[max_length]
  10245. */
  10246. overflow -= 2;
  10247. } while (overflow > 0);
  10248. /* Now recompute all bit lengths, scanning in increasing frequency.
  10249. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10250. * lengths instead of fixing only the wrong ones. This idea is taken
  10251. * from 'ar' written by Haruhiko Okumura.)
  10252. */
  10253. for (bits = max_length; bits !== 0; bits--) {
  10254. n = s.bl_count[bits];
  10255. while (n !== 0) {
  10256. m = s.heap[--h];
  10257. if (m > max_code) { continue; }
  10258. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10259. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10260. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10261. tree[m * 2 + 1]/*.Len*/ = bits;
  10262. }
  10263. n--;
  10264. }
  10265. }
  10266. }
  10267. /* ===========================================================================
  10268. * Generate the codes for a given tree and bit counts (which need not be
  10269. * optimal).
  10270. * IN assertion: the array bl_count contains the bit length statistics for
  10271. * the given tree and the field len is set for all tree elements.
  10272. * OUT assertion: the field code is set for all tree elements of non
  10273. * zero code length.
  10274. */
  10275. function gen_codes(tree, max_code, bl_count)
  10276. // ct_data *tree; /* the tree to decorate */
  10277. // int max_code; /* largest code with non zero frequency */
  10278. // ushf *bl_count; /* number of codes at each bit length */
  10279. {
  10280. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10281. var code = 0; /* running code value */
  10282. var bits; /* bit index */
  10283. var n; /* code index */
  10284. /* The distribution counts are first used to generate the code values
  10285. * without bit reversal.
  10286. */
  10287. for (bits = 1; bits <= MAX_BITS; bits++) {
  10288. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10289. }
  10290. /* Check that the bit counts in bl_count are consistent. The last code
  10291. * must be all ones.
  10292. */
  10293. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10294. // "inconsistent bit counts");
  10295. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10296. for (n = 0; n <= max_code; n++) {
  10297. var len = tree[n * 2 + 1]/*.Len*/;
  10298. if (len === 0) { continue; }
  10299. /* Now reverse the bits */
  10300. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10301. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10302. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10303. }
  10304. }
  10305. /* ===========================================================================
  10306. * Initialize the various 'constant' tables.
  10307. */
  10308. function tr_static_init() {
  10309. var n; /* iterates over tree elements */
  10310. var bits; /* bit counter */
  10311. var length; /* length value */
  10312. var code; /* code value */
  10313. var dist; /* distance index */
  10314. var bl_count = new Array(MAX_BITS + 1);
  10315. /* number of codes at each bit length for an optimal tree */
  10316. // do check in _tr_init()
  10317. //if (static_init_done) return;
  10318. /* For some embedded targets, global variables are not initialized: */
  10319. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10320. static_l_desc.static_tree = static_ltree;
  10321. static_l_desc.extra_bits = extra_lbits;
  10322. static_d_desc.static_tree = static_dtree;
  10323. static_d_desc.extra_bits = extra_dbits;
  10324. static_bl_desc.extra_bits = extra_blbits;
  10325. #endif*/
  10326. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10327. length = 0;
  10328. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10329. base_length[code] = length;
  10330. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10331. _length_code[length++] = code;
  10332. }
  10333. }
  10334. //Assert (length == 256, "tr_static_init: length != 256");
  10335. /* Note that the length 255 (match length 258) can be represented
  10336. * in two different ways: code 284 + 5 bits or code 285, so we
  10337. * overwrite length_code[255] to use the best encoding:
  10338. */
  10339. _length_code[length - 1] = code;
  10340. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10341. dist = 0;
  10342. for (code = 0; code < 16; code++) {
  10343. base_dist[code] = dist;
  10344. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10345. _dist_code[dist++] = code;
  10346. }
  10347. }
  10348. //Assert (dist == 256, "tr_static_init: dist != 256");
  10349. dist >>= 7; /* from now on, all distances are divided by 128 */
  10350. for (; code < D_CODES; code++) {
  10351. base_dist[code] = dist << 7;
  10352. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10353. _dist_code[256 + dist++] = code;
  10354. }
  10355. }
  10356. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10357. /* Construct the codes of the static literal tree */
  10358. for (bits = 0; bits <= MAX_BITS; bits++) {
  10359. bl_count[bits] = 0;
  10360. }
  10361. n = 0;
  10362. while (n <= 143) {
  10363. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10364. n++;
  10365. bl_count[8]++;
  10366. }
  10367. while (n <= 255) {
  10368. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10369. n++;
  10370. bl_count[9]++;
  10371. }
  10372. while (n <= 279) {
  10373. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10374. n++;
  10375. bl_count[7]++;
  10376. }
  10377. while (n <= 287) {
  10378. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10379. n++;
  10380. bl_count[8]++;
  10381. }
  10382. /* Codes 286 and 287 do not exist, but we must include them in the
  10383. * tree construction to get a canonical Huffman tree (longest code
  10384. * all ones)
  10385. */
  10386. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10387. /* The static distance tree is trivial: */
  10388. for (n = 0; n < D_CODES; n++) {
  10389. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10390. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10391. }
  10392. // Now data ready and we can init static trees
  10393. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10394. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10395. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10396. //static_init_done = true;
  10397. }
  10398. /* ===========================================================================
  10399. * Initialize a new block.
  10400. */
  10401. function init_block(s) {
  10402. var n; /* iterates over tree elements */
  10403. /* Initialize the trees. */
  10404. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10405. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10406. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10407. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10408. s.opt_len = s.static_len = 0;
  10409. s.last_lit = s.matches = 0;
  10410. }
  10411. /* ===========================================================================
  10412. * Flush the bit buffer and align the output on a byte boundary
  10413. */
  10414. function bi_windup(s)
  10415. {
  10416. if (s.bi_valid > 8) {
  10417. put_short(s, s.bi_buf);
  10418. } else if (s.bi_valid > 0) {
  10419. //put_byte(s, (Byte)s->bi_buf);
  10420. s.pending_buf[s.pending++] = s.bi_buf;
  10421. }
  10422. s.bi_buf = 0;
  10423. s.bi_valid = 0;
  10424. }
  10425. /* ===========================================================================
  10426. * Copy a stored block, storing first the length and its
  10427. * one's complement if requested.
  10428. */
  10429. function copy_block(s, buf, len, header)
  10430. //DeflateState *s;
  10431. //charf *buf; /* the input data */
  10432. //unsigned len; /* its length */
  10433. //int header; /* true if block header must be written */
  10434. {
  10435. bi_windup(s); /* align on byte boundary */
  10436. if (header) {
  10437. put_short(s, len);
  10438. put_short(s, ~len);
  10439. }
  10440. // while (len--) {
  10441. // put_byte(s, *buf++);
  10442. // }
  10443. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10444. s.pending += len;
  10445. }
  10446. /* ===========================================================================
  10447. * Compares to subtrees, using the tree depth as tie breaker when
  10448. * the subtrees have equal frequency. This minimizes the worst case length.
  10449. */
  10450. function smaller(tree, n, m, depth) {
  10451. var _n2 = n * 2;
  10452. var _m2 = m * 2;
  10453. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10454. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10455. }
  10456. /* ===========================================================================
  10457. * Restore the heap property by moving down the tree starting at node k,
  10458. * exchanging a node with the smallest of its two sons if necessary, stopping
  10459. * when the heap property is re-established (each father smaller than its
  10460. * two sons).
  10461. */
  10462. function pqdownheap(s, tree, k)
  10463. // deflate_state *s;
  10464. // ct_data *tree; /* the tree to restore */
  10465. // int k; /* node to move down */
  10466. {
  10467. var v = s.heap[k];
  10468. var j = k << 1; /* left son of k */
  10469. while (j <= s.heap_len) {
  10470. /* Set j to the smallest of the two sons: */
  10471. if (j < s.heap_len &&
  10472. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10473. j++;
  10474. }
  10475. /* Exit if v is smaller than both sons */
  10476. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10477. /* Exchange v with the smallest son */
  10478. s.heap[k] = s.heap[j];
  10479. k = j;
  10480. /* And continue down the tree, setting j to the left son of k */
  10481. j <<= 1;
  10482. }
  10483. s.heap[k] = v;
  10484. }
  10485. // inlined manually
  10486. // var SMALLEST = 1;
  10487. /* ===========================================================================
  10488. * Send the block data compressed using the given Huffman trees
  10489. */
  10490. function compress_block(s, ltree, dtree)
  10491. // deflate_state *s;
  10492. // const ct_data *ltree; /* literal tree */
  10493. // const ct_data *dtree; /* distance tree */
  10494. {
  10495. var dist; /* distance of matched string */
  10496. var lc; /* match length or unmatched char (if dist == 0) */
  10497. var lx = 0; /* running index in l_buf */
  10498. var code; /* the code to send */
  10499. var extra; /* number of extra bits to send */
  10500. if (s.last_lit !== 0) {
  10501. do {
  10502. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10503. lc = s.pending_buf[s.l_buf + lx];
  10504. lx++;
  10505. if (dist === 0) {
  10506. send_code(s, lc, ltree); /* send a literal byte */
  10507. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10508. } else {
  10509. /* Here, lc is the match length - MIN_MATCH */
  10510. code = _length_code[lc];
  10511. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10512. extra = extra_lbits[code];
  10513. if (extra !== 0) {
  10514. lc -= base_length[code];
  10515. send_bits(s, lc, extra); /* send the extra length bits */
  10516. }
  10517. dist--; /* dist is now the match distance - 1 */
  10518. code = d_code(dist);
  10519. //Assert (code < D_CODES, "bad d_code");
  10520. send_code(s, code, dtree); /* send the distance code */
  10521. extra = extra_dbits[code];
  10522. if (extra !== 0) {
  10523. dist -= base_dist[code];
  10524. send_bits(s, dist, extra); /* send the extra distance bits */
  10525. }
  10526. } /* literal or match pair ? */
  10527. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10528. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10529. // "pendingBuf overflow");
  10530. } while (lx < s.last_lit);
  10531. }
  10532. send_code(s, END_BLOCK, ltree);
  10533. }
  10534. /* ===========================================================================
  10535. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10536. * Update the total bit length for the current block.
  10537. * IN assertion: the field freq is set for all tree elements.
  10538. * OUT assertions: the fields len and code are set to the optimal bit length
  10539. * and corresponding code. The length opt_len is updated; static_len is
  10540. * also updated if stree is not null. The field max_code is set.
  10541. */
  10542. function build_tree(s, desc)
  10543. // deflate_state *s;
  10544. // tree_desc *desc; /* the tree descriptor */
  10545. {
  10546. var tree = desc.dyn_tree;
  10547. var stree = desc.stat_desc.static_tree;
  10548. var has_stree = desc.stat_desc.has_stree;
  10549. var elems = desc.stat_desc.elems;
  10550. var n, m; /* iterate over heap elements */
  10551. var max_code = -1; /* largest code with non zero frequency */
  10552. var node; /* new node being created */
  10553. /* Construct the initial heap, with least frequent element in
  10554. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10555. * heap[0] is not used.
  10556. */
  10557. s.heap_len = 0;
  10558. s.heap_max = HEAP_SIZE;
  10559. for (n = 0; n < elems; n++) {
  10560. if (tree[n * 2]/*.Freq*/ !== 0) {
  10561. s.heap[++s.heap_len] = max_code = n;
  10562. s.depth[n] = 0;
  10563. } else {
  10564. tree[n * 2 + 1]/*.Len*/ = 0;
  10565. }
  10566. }
  10567. /* The pkzip format requires that at least one distance code exists,
  10568. * and that at least one bit should be sent even if there is only one
  10569. * possible code. So to avoid special checks later on we force at least
  10570. * two codes of non zero frequency.
  10571. */
  10572. while (s.heap_len < 2) {
  10573. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10574. tree[node * 2]/*.Freq*/ = 1;
  10575. s.depth[node] = 0;
  10576. s.opt_len--;
  10577. if (has_stree) {
  10578. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10579. }
  10580. /* node is 0 or 1 so it does not have extra bits */
  10581. }
  10582. desc.max_code = max_code;
  10583. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10584. * establish sub-heaps of increasing lengths:
  10585. */
  10586. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10587. /* Construct the Huffman tree by repeatedly combining the least two
  10588. * frequent nodes.
  10589. */
  10590. node = elems; /* next internal node of the tree */
  10591. do {
  10592. //pqremove(s, tree, n); /* n = node of least frequency */
  10593. /*** pqremove ***/
  10594. n = s.heap[1/*SMALLEST*/];
  10595. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10596. pqdownheap(s, tree, 1/*SMALLEST*/);
  10597. /***/
  10598. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10599. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10600. s.heap[--s.heap_max] = m;
  10601. /* Create a new node father of n and m */
  10602. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10603. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10604. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10605. /* and insert the new node in the heap */
  10606. s.heap[1/*SMALLEST*/] = node++;
  10607. pqdownheap(s, tree, 1/*SMALLEST*/);
  10608. } while (s.heap_len >= 2);
  10609. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10610. /* At this point, the fields freq and dad are set. We can now
  10611. * generate the bit lengths.
  10612. */
  10613. gen_bitlen(s, desc);
  10614. /* The field len is now set, we can generate the bit codes */
  10615. gen_codes(tree, max_code, s.bl_count);
  10616. }
  10617. /* ===========================================================================
  10618. * Scan a literal or distance tree to determine the frequencies of the codes
  10619. * in the bit length tree.
  10620. */
  10621. function scan_tree(s, tree, max_code)
  10622. // deflate_state *s;
  10623. // ct_data *tree; /* the tree to be scanned */
  10624. // int max_code; /* and its largest code of non zero frequency */
  10625. {
  10626. var n; /* iterates over all tree elements */
  10627. var prevlen = -1; /* last emitted length */
  10628. var curlen; /* length of current code */
  10629. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10630. var count = 0; /* repeat count of the current code */
  10631. var max_count = 7; /* max repeat count */
  10632. var min_count = 4; /* min repeat count */
  10633. if (nextlen === 0) {
  10634. max_count = 138;
  10635. min_count = 3;
  10636. }
  10637. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  10638. for (n = 0; n <= max_code; n++) {
  10639. curlen = nextlen;
  10640. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10641. if (++count < max_count && curlen === nextlen) {
  10642. continue;
  10643. } else if (count < min_count) {
  10644. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10645. } else if (curlen !== 0) {
  10646. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10647. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  10648. } else if (count <= 10) {
  10649. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  10650. } else {
  10651. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  10652. }
  10653. count = 0;
  10654. prevlen = curlen;
  10655. if (nextlen === 0) {
  10656. max_count = 138;
  10657. min_count = 3;
  10658. } else if (curlen === nextlen) {
  10659. max_count = 6;
  10660. min_count = 3;
  10661. } else {
  10662. max_count = 7;
  10663. min_count = 4;
  10664. }
  10665. }
  10666. }
  10667. /* ===========================================================================
  10668. * Send a literal or distance tree in compressed form, using the codes in
  10669. * bl_tree.
  10670. */
  10671. function send_tree(s, tree, max_code)
  10672. // deflate_state *s;
  10673. // ct_data *tree; /* the tree to be scanned */
  10674. // int max_code; /* and its largest code of non zero frequency */
  10675. {
  10676. var n; /* iterates over all tree elements */
  10677. var prevlen = -1; /* last emitted length */
  10678. var curlen; /* length of current code */
  10679. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10680. var count = 0; /* repeat count of the current code */
  10681. var max_count = 7; /* max repeat count */
  10682. var min_count = 4; /* min repeat count */
  10683. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10684. if (nextlen === 0) {
  10685. max_count = 138;
  10686. min_count = 3;
  10687. }
  10688. for (n = 0; n <= max_code; n++) {
  10689. curlen = nextlen;
  10690. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10691. if (++count < max_count && curlen === nextlen) {
  10692. continue;
  10693. } else if (count < min_count) {
  10694. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10695. } else if (curlen !== 0) {
  10696. if (curlen !== prevlen) {
  10697. send_code(s, curlen, s.bl_tree);
  10698. count--;
  10699. }
  10700. //Assert(count >= 3 && count <= 6, " 3_6?");
  10701. send_code(s, REP_3_6, s.bl_tree);
  10702. send_bits(s, count - 3, 2);
  10703. } else if (count <= 10) {
  10704. send_code(s, REPZ_3_10, s.bl_tree);
  10705. send_bits(s, count - 3, 3);
  10706. } else {
  10707. send_code(s, REPZ_11_138, s.bl_tree);
  10708. send_bits(s, count - 11, 7);
  10709. }
  10710. count = 0;
  10711. prevlen = curlen;
  10712. if (nextlen === 0) {
  10713. max_count = 138;
  10714. min_count = 3;
  10715. } else if (curlen === nextlen) {
  10716. max_count = 6;
  10717. min_count = 3;
  10718. } else {
  10719. max_count = 7;
  10720. min_count = 4;
  10721. }
  10722. }
  10723. }
  10724. /* ===========================================================================
  10725. * Construct the Huffman tree for the bit lengths and return the index in
  10726. * bl_order of the last bit length code to send.
  10727. */
  10728. function build_bl_tree(s) {
  10729. var max_blindex; /* index of last bit length code of non zero freq */
  10730. /* Determine the bit length frequencies for literal and distance trees */
  10731. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  10732. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  10733. /* Build the bit length tree: */
  10734. build_tree(s, s.bl_desc);
  10735. /* opt_len now includes the length of the tree representations, except
  10736. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  10737. */
  10738. /* Determine the number of bit length codes to send. The pkzip format
  10739. * requires that at least 4 bit length codes be sent. (appnote.txt says
  10740. * 3 but the actual value used is 4.)
  10741. */
  10742. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  10743. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  10744. break;
  10745. }
  10746. }
  10747. /* Update opt_len to include the bit length tree and counts */
  10748. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  10749. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  10750. // s->opt_len, s->static_len));
  10751. return max_blindex;
  10752. }
  10753. /* ===========================================================================
  10754. * Send the header for a block using dynamic Huffman trees: the counts, the
  10755. * lengths of the bit length codes, the literal tree and the distance tree.
  10756. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10757. */
  10758. function send_all_trees(s, lcodes, dcodes, blcodes)
  10759. // deflate_state *s;
  10760. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  10761. {
  10762. var rank; /* index in bl_order */
  10763. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  10764. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  10765. // "too many codes");
  10766. //Tracev((stderr, "\nbl counts: "));
  10767. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  10768. send_bits(s, dcodes - 1, 5);
  10769. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  10770. for (rank = 0; rank < blcodes; rank++) {
  10771. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  10772. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  10773. }
  10774. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  10775. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  10776. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  10777. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  10778. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  10779. }
  10780. /* ===========================================================================
  10781. * Check if the data type is TEXT or BINARY, using the following algorithm:
  10782. * - TEXT if the two conditions below are satisfied:
  10783. * a) There are no non-portable control characters belonging to the
  10784. * "black list" (0..6, 14..25, 28..31).
  10785. * b) There is at least one printable character belonging to the
  10786. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  10787. * - BINARY otherwise.
  10788. * - The following partially-portable control characters form a
  10789. * "gray list" that is ignored in this detection algorithm:
  10790. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  10791. * IN assertion: the fields Freq of dyn_ltree are set.
  10792. */
  10793. function detect_data_type(s) {
  10794. /* black_mask is the bit mask of black-listed bytes
  10795. * set bits 0..6, 14..25, and 28..31
  10796. * 0xf3ffc07f = binary 11110011111111111100000001111111
  10797. */
  10798. var black_mask = 0xf3ffc07f;
  10799. var n;
  10800. /* Check for non-textual ("black-listed") bytes. */
  10801. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  10802. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  10803. return Z_BINARY;
  10804. }
  10805. }
  10806. /* Check for textual ("white-listed") bytes. */
  10807. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  10808. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  10809. return Z_TEXT;
  10810. }
  10811. for (n = 32; n < LITERALS; n++) {
  10812. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  10813. return Z_TEXT;
  10814. }
  10815. }
  10816. /* There are no "black-listed" or "white-listed" bytes:
  10817. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  10818. */
  10819. return Z_BINARY;
  10820. }
  10821. var static_init_done = false;
  10822. /* ===========================================================================
  10823. * Initialize the tree data structures for a new zlib stream.
  10824. */
  10825. function _tr_init(s)
  10826. {
  10827. if (!static_init_done) {
  10828. tr_static_init();
  10829. static_init_done = true;
  10830. }
  10831. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  10832. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  10833. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  10834. s.bi_buf = 0;
  10835. s.bi_valid = 0;
  10836. /* Initialize the first block of the first file: */
  10837. init_block(s);
  10838. }
  10839. /* ===========================================================================
  10840. * Send a stored block
  10841. */
  10842. function _tr_stored_block(s, buf, stored_len, last)
  10843. //DeflateState *s;
  10844. //charf *buf; /* input block */
  10845. //ulg stored_len; /* length of input block */
  10846. //int last; /* one if this is the last block for a file */
  10847. {
  10848. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  10849. copy_block(s, buf, stored_len, true); /* with header */
  10850. }
  10851. /* ===========================================================================
  10852. * Send one empty static block to give enough lookahead for inflate.
  10853. * This takes 10 bits, of which 7 may remain in the bit buffer.
  10854. */
  10855. function _tr_align(s) {
  10856. send_bits(s, STATIC_TREES << 1, 3);
  10857. send_code(s, END_BLOCK, static_ltree);
  10858. bi_flush(s);
  10859. }
  10860. /* ===========================================================================
  10861. * Determine the best encoding for the current block: dynamic trees, static
  10862. * trees or store, and output the encoded block to the zip file.
  10863. */
  10864. function _tr_flush_block(s, buf, stored_len, last)
  10865. //DeflateState *s;
  10866. //charf *buf; /* input block, or NULL if too old */
  10867. //ulg stored_len; /* length of input block */
  10868. //int last; /* one if this is the last block for a file */
  10869. {
  10870. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  10871. var max_blindex = 0; /* index of last bit length code of non zero freq */
  10872. /* Build the Huffman trees unless a stored block is forced */
  10873. if (s.level > 0) {
  10874. /* Check if the file is binary or text */
  10875. if (s.strm.data_type === Z_UNKNOWN) {
  10876. s.strm.data_type = detect_data_type(s);
  10877. }
  10878. /* Construct the literal and distance trees */
  10879. build_tree(s, s.l_desc);
  10880. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  10881. // s->static_len));
  10882. build_tree(s, s.d_desc);
  10883. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  10884. // s->static_len));
  10885. /* At this point, opt_len and static_len are the total bit lengths of
  10886. * the compressed block data, excluding the tree representations.
  10887. */
  10888. /* Build the bit length tree for the above two trees, and get the index
  10889. * in bl_order of the last bit length code to send.
  10890. */
  10891. max_blindex = build_bl_tree(s);
  10892. /* Determine the best encoding. Compute the block lengths in bytes. */
  10893. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  10894. static_lenb = (s.static_len + 3 + 7) >>> 3;
  10895. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  10896. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  10897. // s->last_lit));
  10898. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  10899. } else {
  10900. // Assert(buf != (char*)0, "lost buf");
  10901. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  10902. }
  10903. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  10904. /* 4: two words for the lengths */
  10905. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10906. * Otherwise we can't have processed more than WSIZE input bytes since
  10907. * the last block flush, because compression would have been
  10908. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10909. * transform a block into a stored block.
  10910. */
  10911. _tr_stored_block(s, buf, stored_len, last);
  10912. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  10913. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  10914. compress_block(s, static_ltree, static_dtree);
  10915. } else {
  10916. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  10917. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  10918. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  10919. }
  10920. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  10921. /* The above check is made mod 2^32, for files larger than 512 MB
  10922. * and uLong implemented on 32 bits.
  10923. */
  10924. init_block(s);
  10925. if (last) {
  10926. bi_windup(s);
  10927. }
  10928. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  10929. // s->compressed_len-7*last));
  10930. }
  10931. /* ===========================================================================
  10932. * Save the match info and tally the frequency counts. Return true if
  10933. * the current block must be flushed.
  10934. */
  10935. function _tr_tally(s, dist, lc)
  10936. // deflate_state *s;
  10937. // unsigned dist; /* distance of matched string */
  10938. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  10939. {
  10940. //var out_length, in_length, dcode;
  10941. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  10942. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  10943. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  10944. s.last_lit++;
  10945. if (dist === 0) {
  10946. /* lc is the unmatched char */
  10947. s.dyn_ltree[lc * 2]/*.Freq*/++;
  10948. } else {
  10949. s.matches++;
  10950. /* Here, lc is the match length - MIN_MATCH */
  10951. dist--; /* dist = match distance - 1 */
  10952. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  10953. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  10954. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  10955. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  10956. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  10957. }
  10958. // (!) This block is disabled in zlib defaults,
  10959. // don't enable it for binary compatibility
  10960. //#ifdef TRUNCATE_BLOCK
  10961. // /* Try to guess if it is profitable to stop the current block here */
  10962. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  10963. // /* Compute an upper bound for the compressed length */
  10964. // out_length = s.last_lit*8;
  10965. // in_length = s.strstart - s.block_start;
  10966. //
  10967. // for (dcode = 0; dcode < D_CODES; dcode++) {
  10968. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  10969. // }
  10970. // out_length >>>= 3;
  10971. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  10972. // // s->last_lit, in_length, out_length,
  10973. // // 100L - out_length*100L/in_length));
  10974. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  10975. // return true;
  10976. // }
  10977. // }
  10978. //#endif
  10979. return (s.last_lit === s.lit_bufsize - 1);
  10980. /* We avoid equality with lit_bufsize because of wraparound at 64K
  10981. * on 16 bit machines and because stored blocks are restricted to
  10982. * 64K-1 bytes.
  10983. */
  10984. }
  10985. exports._tr_init = _tr_init;
  10986. exports._tr_stored_block = _tr_stored_block;
  10987. exports._tr_flush_block = _tr_flush_block;
  10988. exports._tr_tally = _tr_tally;
  10989. exports._tr_align = _tr_align;
  10990. },{"../utils/common":39}],49:[function(require,module,exports){
  10991. 'use strict';
  10992. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10993. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10994. //
  10995. // This software is provided 'as-is', without any express or implied
  10996. // warranty. In no event will the authors be held liable for any damages
  10997. // arising from the use of this software.
  10998. //
  10999. // Permission is granted to anyone to use this software for any purpose,
  11000. // including commercial applications, and to alter it and redistribute it
  11001. // freely, subject to the following restrictions:
  11002. //
  11003. // 1. The origin of this software must not be misrepresented; you must not
  11004. // claim that you wrote the original software. If you use this software
  11005. // in a product, an acknowledgment in the product documentation would be
  11006. // appreciated but is not required.
  11007. // 2. Altered source versions must be plainly marked as such, and must not be
  11008. // misrepresented as being the original software.
  11009. // 3. This notice may not be removed or altered from any source distribution.
  11010. function ZStream() {
  11011. /* next input byte */
  11012. this.input = null; // JS specific, because we have no pointers
  11013. this.next_in = 0;
  11014. /* number of bytes available at input */
  11015. this.avail_in = 0;
  11016. /* total number of input bytes read so far */
  11017. this.total_in = 0;
  11018. /* next output byte should be put there */
  11019. this.output = null; // JS specific, because we have no pointers
  11020. this.next_out = 0;
  11021. /* remaining free space at output */
  11022. this.avail_out = 0;
  11023. /* total number of bytes output so far */
  11024. this.total_out = 0;
  11025. /* last error message, NULL if no error */
  11026. this.msg = ''/*Z_NULL*/;
  11027. /* not visible by applications */
  11028. this.state = null;
  11029. /* best guess about the data type: binary or text */
  11030. this.data_type = 2/*Z_UNKNOWN*/;
  11031. /* adler32 value of the uncompressed data */
  11032. this.adler = 0;
  11033. }
  11034. module.exports = ZStream;
  11035. },{}],50:[function(require,module,exports){
  11036. (function (process){
  11037. 'use strict';
  11038. if (!process.version ||
  11039. process.version.indexOf('v0.') === 0 ||
  11040. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  11041. module.exports = nextTick;
  11042. } else {
  11043. module.exports = process.nextTick;
  11044. }
  11045. function nextTick(fn, arg1, arg2, arg3) {
  11046. if (typeof fn !== 'function') {
  11047. throw new TypeError('"callback" argument must be a function');
  11048. }
  11049. var len = arguments.length;
  11050. var args, i;
  11051. switch (len) {
  11052. case 0:
  11053. case 1:
  11054. return process.nextTick(fn);
  11055. case 2:
  11056. return process.nextTick(function afterTickOne() {
  11057. fn.call(null, arg1);
  11058. });
  11059. case 3:
  11060. return process.nextTick(function afterTickTwo() {
  11061. fn.call(null, arg1, arg2);
  11062. });
  11063. case 4:
  11064. return process.nextTick(function afterTickThree() {
  11065. fn.call(null, arg1, arg2, arg3);
  11066. });
  11067. default:
  11068. args = new Array(len - 1);
  11069. i = 0;
  11070. while (i < args.length) {
  11071. args[i++] = arguments[i];
  11072. }
  11073. return process.nextTick(function afterTick() {
  11074. fn.apply(null, args);
  11075. });
  11076. }
  11077. }
  11078. }).call(this,require('_process'))
  11079. },{"_process":51}],51:[function(require,module,exports){
  11080. // shim for using process in browser
  11081. var process = module.exports = {};
  11082. // cached from whatever global is present so that test runners that stub it
  11083. // don't break things. But we need to wrap it in a try catch in case it is
  11084. // wrapped in strict mode code which doesn't define any globals. It's inside a
  11085. // function because try/catches deoptimize in certain engines.
  11086. var cachedSetTimeout;
  11087. var cachedClearTimeout;
  11088. function defaultSetTimout() {
  11089. throw new Error('setTimeout has not been defined');
  11090. }
  11091. function defaultClearTimeout () {
  11092. throw new Error('clearTimeout has not been defined');
  11093. }
  11094. (function () {
  11095. try {
  11096. if (typeof setTimeout === 'function') {
  11097. cachedSetTimeout = setTimeout;
  11098. } else {
  11099. cachedSetTimeout = defaultSetTimout;
  11100. }
  11101. } catch (e) {
  11102. cachedSetTimeout = defaultSetTimout;
  11103. }
  11104. try {
  11105. if (typeof clearTimeout === 'function') {
  11106. cachedClearTimeout = clearTimeout;
  11107. } else {
  11108. cachedClearTimeout = defaultClearTimeout;
  11109. }
  11110. } catch (e) {
  11111. cachedClearTimeout = defaultClearTimeout;
  11112. }
  11113. } ())
  11114. function runTimeout(fun) {
  11115. if (cachedSetTimeout === setTimeout) {
  11116. //normal enviroments in sane situations
  11117. return setTimeout(fun, 0);
  11118. }
  11119. // if setTimeout wasn't available but was latter defined
  11120. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11121. cachedSetTimeout = setTimeout;
  11122. return setTimeout(fun, 0);
  11123. }
  11124. try {
  11125. // when when somebody has screwed with setTimeout but no I.E. maddness
  11126. return cachedSetTimeout(fun, 0);
  11127. } catch(e){
  11128. try {
  11129. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11130. return cachedSetTimeout.call(null, fun, 0);
  11131. } catch(e){
  11132. // 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
  11133. return cachedSetTimeout.call(this, fun, 0);
  11134. }
  11135. }
  11136. }
  11137. function runClearTimeout(marker) {
  11138. if (cachedClearTimeout === clearTimeout) {
  11139. //normal enviroments in sane situations
  11140. return clearTimeout(marker);
  11141. }
  11142. // if clearTimeout wasn't available but was latter defined
  11143. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11144. cachedClearTimeout = clearTimeout;
  11145. return clearTimeout(marker);
  11146. }
  11147. try {
  11148. // when when somebody has screwed with setTimeout but no I.E. maddness
  11149. return cachedClearTimeout(marker);
  11150. } catch (e){
  11151. try {
  11152. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11153. return cachedClearTimeout.call(null, marker);
  11154. } catch (e){
  11155. // 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.
  11156. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  11157. return cachedClearTimeout.call(this, marker);
  11158. }
  11159. }
  11160. }
  11161. var queue = [];
  11162. var draining = false;
  11163. var currentQueue;
  11164. var queueIndex = -1;
  11165. function cleanUpNextTick() {
  11166. if (!draining || !currentQueue) {
  11167. return;
  11168. }
  11169. draining = false;
  11170. if (currentQueue.length) {
  11171. queue = currentQueue.concat(queue);
  11172. } else {
  11173. queueIndex = -1;
  11174. }
  11175. if (queue.length) {
  11176. drainQueue();
  11177. }
  11178. }
  11179. function drainQueue() {
  11180. if (draining) {
  11181. return;
  11182. }
  11183. var timeout = runTimeout(cleanUpNextTick);
  11184. draining = true;
  11185. var len = queue.length;
  11186. while(len) {
  11187. currentQueue = queue;
  11188. queue = [];
  11189. while (++queueIndex < len) {
  11190. if (currentQueue) {
  11191. currentQueue[queueIndex].run();
  11192. }
  11193. }
  11194. queueIndex = -1;
  11195. len = queue.length;
  11196. }
  11197. currentQueue = null;
  11198. draining = false;
  11199. runClearTimeout(timeout);
  11200. }
  11201. process.nextTick = function (fun) {
  11202. var args = new Array(arguments.length - 1);
  11203. if (arguments.length > 1) {
  11204. for (var i = 1; i < arguments.length; i++) {
  11205. args[i - 1] = arguments[i];
  11206. }
  11207. }
  11208. queue.push(new Item(fun, args));
  11209. if (queue.length === 1 && !draining) {
  11210. runTimeout(drainQueue);
  11211. }
  11212. };
  11213. // v8 likes predictible objects
  11214. function Item(fun, array) {
  11215. this.fun = fun;
  11216. this.array = array;
  11217. }
  11218. Item.prototype.run = function () {
  11219. this.fun.apply(null, this.array);
  11220. };
  11221. process.title = 'browser';
  11222. process.browser = true;
  11223. process.env = {};
  11224. process.argv = [];
  11225. process.version = ''; // empty string to avoid regexp issues
  11226. process.versions = {};
  11227. function noop() {}
  11228. process.on = noop;
  11229. process.addListener = noop;
  11230. process.once = noop;
  11231. process.off = noop;
  11232. process.removeListener = noop;
  11233. process.removeAllListeners = noop;
  11234. process.emit = noop;
  11235. process.prependListener = noop;
  11236. process.prependOnceListener = noop;
  11237. process.listeners = function (name) { return [] }
  11238. process.binding = function (name) {
  11239. throw new Error('process.binding is not supported');
  11240. };
  11241. process.cwd = function () { return '/' };
  11242. process.chdir = function (dir) {
  11243. throw new Error('process.chdir is not supported');
  11244. };
  11245. process.umask = function() { return 0; };
  11246. },{}],52:[function(require,module,exports){
  11247. module.exports = require('./lib/_stream_duplex.js');
  11248. },{"./lib/_stream_duplex.js":53}],53:[function(require,module,exports){
  11249. // a duplex stream is just a stream that is both readable and writable.
  11250. // Since JS doesn't have multiple prototypal inheritance, this class
  11251. // prototypally inherits from Readable, and then parasitically from
  11252. // Writable.
  11253. 'use strict';
  11254. /*<replacement>*/
  11255. var objectKeys = Object.keys || function (obj) {
  11256. var keys = [];
  11257. for (var key in obj) {
  11258. keys.push(key);
  11259. }return keys;
  11260. };
  11261. /*</replacement>*/
  11262. module.exports = Duplex;
  11263. /*<replacement>*/
  11264. var processNextTick = require('process-nextick-args');
  11265. /*</replacement>*/
  11266. /*<replacement>*/
  11267. var util = require('core-util-is');
  11268. util.inherits = require('inherits');
  11269. /*</replacement>*/
  11270. var Readable = require('./_stream_readable');
  11271. var Writable = require('./_stream_writable');
  11272. util.inherits(Duplex, Readable);
  11273. var keys = objectKeys(Writable.prototype);
  11274. for (var v = 0; v < keys.length; v++) {
  11275. var method = keys[v];
  11276. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  11277. }
  11278. function Duplex(options) {
  11279. if (!(this instanceof Duplex)) return new Duplex(options);
  11280. Readable.call(this, options);
  11281. Writable.call(this, options);
  11282. if (options && options.readable === false) this.readable = false;
  11283. if (options && options.writable === false) this.writable = false;
  11284. this.allowHalfOpen = true;
  11285. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  11286. this.once('end', onend);
  11287. }
  11288. // the no-half-open enforcer
  11289. function onend() {
  11290. // if we allow half-open state, or if the writable side ended,
  11291. // then we're ok.
  11292. if (this.allowHalfOpen || this._writableState.ended) return;
  11293. // no more data can be written.
  11294. // But allow more writes to happen in this tick.
  11295. processNextTick(onEndNT, this);
  11296. }
  11297. function onEndNT(self) {
  11298. self.end();
  11299. }
  11300. function forEach(xs, f) {
  11301. for (var i = 0, l = xs.length; i < l; i++) {
  11302. f(xs[i], i);
  11303. }
  11304. }
  11305. },{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":33,"inherits":36,"process-nextick-args":50}],54:[function(require,module,exports){
  11306. // a passthrough stream.
  11307. // basically just the most minimal sort of Transform stream.
  11308. // Every written chunk gets output as-is.
  11309. 'use strict';
  11310. module.exports = PassThrough;
  11311. var Transform = require('./_stream_transform');
  11312. /*<replacement>*/
  11313. var util = require('core-util-is');
  11314. util.inherits = require('inherits');
  11315. /*</replacement>*/
  11316. util.inherits(PassThrough, Transform);
  11317. function PassThrough(options) {
  11318. if (!(this instanceof PassThrough)) return new PassThrough(options);
  11319. Transform.call(this, options);
  11320. }
  11321. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  11322. cb(null, chunk);
  11323. };
  11324. },{"./_stream_transform":56,"core-util-is":33,"inherits":36}],55:[function(require,module,exports){
  11325. (function (process){
  11326. 'use strict';
  11327. module.exports = Readable;
  11328. /*<replacement>*/
  11329. var processNextTick = require('process-nextick-args');
  11330. /*</replacement>*/
  11331. /*<replacement>*/
  11332. var isArray = require('isarray');
  11333. /*</replacement>*/
  11334. /*<replacement>*/
  11335. var Duplex;
  11336. /*</replacement>*/
  11337. Readable.ReadableState = ReadableState;
  11338. /*<replacement>*/
  11339. var EE = require('events').EventEmitter;
  11340. var EElistenerCount = function (emitter, type) {
  11341. return emitter.listeners(type).length;
  11342. };
  11343. /*</replacement>*/
  11344. /*<replacement>*/
  11345. var Stream = require('./internal/streams/stream');
  11346. /*</replacement>*/
  11347. var Buffer = require('buffer').Buffer;
  11348. /*<replacement>*/
  11349. var bufferShim = require('buffer-shims');
  11350. /*</replacement>*/
  11351. /*<replacement>*/
  11352. var util = require('core-util-is');
  11353. util.inherits = require('inherits');
  11354. /*</replacement>*/
  11355. /*<replacement>*/
  11356. var debugUtil = require('util');
  11357. var debug = void 0;
  11358. if (debugUtil && debugUtil.debuglog) {
  11359. debug = debugUtil.debuglog('stream');
  11360. } else {
  11361. debug = function () {};
  11362. }
  11363. /*</replacement>*/
  11364. var BufferList = require('./internal/streams/BufferList');
  11365. var StringDecoder;
  11366. util.inherits(Readable, Stream);
  11367. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  11368. function prependListener(emitter, event, fn) {
  11369. // Sadly this is not cacheable as some libraries bundle their own
  11370. // event emitter implementation with them.
  11371. if (typeof emitter.prependListener === 'function') {
  11372. return emitter.prependListener(event, fn);
  11373. } else {
  11374. // This is a hack to make sure that our error handler is attached before any
  11375. // userland ones. NEVER DO THIS. This is here only because this code needs
  11376. // to continue to work with older versions of Node.js that do not include
  11377. // the prependListener() method. The goal is to eventually remove this hack.
  11378. 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]];
  11379. }
  11380. }
  11381. function ReadableState(options, stream) {
  11382. Duplex = Duplex || require('./_stream_duplex');
  11383. options = options || {};
  11384. // object stream flag. Used to make read(n) ignore n and to
  11385. // make all the buffer merging and length checks go away
  11386. this.objectMode = !!options.objectMode;
  11387. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  11388. // the point at which it stops calling _read() to fill the buffer
  11389. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  11390. var hwm = options.highWaterMark;
  11391. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  11392. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  11393. // cast to ints.
  11394. this.highWaterMark = ~~this.highWaterMark;
  11395. // A linked list is used to store data chunks instead of an array because the
  11396. // linked list can remove elements from the beginning faster than
  11397. // array.shift()
  11398. this.buffer = new BufferList();
  11399. this.length = 0;
  11400. this.pipes = null;
  11401. this.pipesCount = 0;
  11402. this.flowing = null;
  11403. this.ended = false;
  11404. this.endEmitted = false;
  11405. this.reading = false;
  11406. // a flag to be able to tell if the onwrite cb is called immediately,
  11407. // or on a later tick. We set this to true at first, because any
  11408. // actions that shouldn't happen until "later" should generally also
  11409. // not happen before the first write call.
  11410. this.sync = true;
  11411. // whenever we return null, then we set a flag to say
  11412. // that we're awaiting a 'readable' event emission.
  11413. this.needReadable = false;
  11414. this.emittedReadable = false;
  11415. this.readableListening = false;
  11416. this.resumeScheduled = false;
  11417. // Crypto is kind of old and crusty. Historically, its default string
  11418. // encoding is 'binary' so we have to make this configurable.
  11419. // Everything else in the universe uses 'utf8', though.
  11420. this.defaultEncoding = options.defaultEncoding || 'utf8';
  11421. // when piping, we only care about 'readable' events that happen
  11422. // after read()ing all the bytes and not getting any pushback.
  11423. this.ranOut = false;
  11424. // the number of writers that are awaiting a drain event in .pipe()s
  11425. this.awaitDrain = 0;
  11426. // if true, a maybeReadMore has been scheduled
  11427. this.readingMore = false;
  11428. this.decoder = null;
  11429. this.encoding = null;
  11430. if (options.encoding) {
  11431. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11432. this.decoder = new StringDecoder(options.encoding);
  11433. this.encoding = options.encoding;
  11434. }
  11435. }
  11436. function Readable(options) {
  11437. Duplex = Duplex || require('./_stream_duplex');
  11438. if (!(this instanceof Readable)) return new Readable(options);
  11439. this._readableState = new ReadableState(options, this);
  11440. // legacy
  11441. this.readable = true;
  11442. if (options && typeof options.read === 'function') this._read = options.read;
  11443. Stream.call(this);
  11444. }
  11445. // Manually shove something into the read() buffer.
  11446. // This returns true if the highWaterMark has not been hit yet,
  11447. // similar to how Writable.write() returns true if you should
  11448. // write() some more.
  11449. Readable.prototype.push = function (chunk, encoding) {
  11450. var state = this._readableState;
  11451. if (!state.objectMode && typeof chunk === 'string') {
  11452. encoding = encoding || state.defaultEncoding;
  11453. if (encoding !== state.encoding) {
  11454. chunk = bufferShim.from(chunk, encoding);
  11455. encoding = '';
  11456. }
  11457. }
  11458. return readableAddChunk(this, state, chunk, encoding, false);
  11459. };
  11460. // Unshift should *always* be something directly out of read()
  11461. Readable.prototype.unshift = function (chunk) {
  11462. var state = this._readableState;
  11463. return readableAddChunk(this, state, chunk, '', true);
  11464. };
  11465. Readable.prototype.isPaused = function () {
  11466. return this._readableState.flowing === false;
  11467. };
  11468. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  11469. var er = chunkInvalid(state, chunk);
  11470. if (er) {
  11471. stream.emit('error', er);
  11472. } else if (chunk === null) {
  11473. state.reading = false;
  11474. onEofChunk(stream, state);
  11475. } else if (state.objectMode || chunk && chunk.length > 0) {
  11476. if (state.ended && !addToFront) {
  11477. var e = new Error('stream.push() after EOF');
  11478. stream.emit('error', e);
  11479. } else if (state.endEmitted && addToFront) {
  11480. var _e = new Error('stream.unshift() after end event');
  11481. stream.emit('error', _e);
  11482. } else {
  11483. var skipAdd;
  11484. if (state.decoder && !addToFront && !encoding) {
  11485. chunk = state.decoder.write(chunk);
  11486. skipAdd = !state.objectMode && chunk.length === 0;
  11487. }
  11488. if (!addToFront) state.reading = false;
  11489. // Don't add to the buffer if we've decoded to an empty string chunk and
  11490. // we're not in object mode
  11491. if (!skipAdd) {
  11492. // if we want the data now, just emit it.
  11493. if (state.flowing && state.length === 0 && !state.sync) {
  11494. stream.emit('data', chunk);
  11495. stream.read(0);
  11496. } else {
  11497. // update the buffer info.
  11498. state.length += state.objectMode ? 1 : chunk.length;
  11499. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  11500. if (state.needReadable) emitReadable(stream);
  11501. }
  11502. }
  11503. maybeReadMore(stream, state);
  11504. }
  11505. } else if (!addToFront) {
  11506. state.reading = false;
  11507. }
  11508. return needMoreData(state);
  11509. }
  11510. // if it's past the high water mark, we can push in some more.
  11511. // Also, if we have no data yet, we can stand some
  11512. // more bytes. This is to work around cases where hwm=0,
  11513. // such as the repl. Also, if the push() triggered a
  11514. // readable event, and the user called read(largeNumber) such that
  11515. // needReadable was set, then we ought to push more, so that another
  11516. // 'readable' event will be triggered.
  11517. function needMoreData(state) {
  11518. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  11519. }
  11520. // backwards compatibility.
  11521. Readable.prototype.setEncoding = function (enc) {
  11522. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11523. this._readableState.decoder = new StringDecoder(enc);
  11524. this._readableState.encoding = enc;
  11525. return this;
  11526. };
  11527. // Don't raise the hwm > 8MB
  11528. var MAX_HWM = 0x800000;
  11529. function computeNewHighWaterMark(n) {
  11530. if (n >= MAX_HWM) {
  11531. n = MAX_HWM;
  11532. } else {
  11533. // Get the next highest power of 2 to prevent increasing hwm excessively in
  11534. // tiny amounts
  11535. n--;
  11536. n |= n >>> 1;
  11537. n |= n >>> 2;
  11538. n |= n >>> 4;
  11539. n |= n >>> 8;
  11540. n |= n >>> 16;
  11541. n++;
  11542. }
  11543. return n;
  11544. }
  11545. // This function is designed to be inlinable, so please take care when making
  11546. // changes to the function body.
  11547. function howMuchToRead(n, state) {
  11548. if (n <= 0 || state.length === 0 && state.ended) return 0;
  11549. if (state.objectMode) return 1;
  11550. if (n !== n) {
  11551. // Only flow one buffer at a time
  11552. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  11553. }
  11554. // If we're asking for more than the current hwm, then raise the hwm.
  11555. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  11556. if (n <= state.length) return n;
  11557. // Don't have enough
  11558. if (!state.ended) {
  11559. state.needReadable = true;
  11560. return 0;
  11561. }
  11562. return state.length;
  11563. }
  11564. // you can override either this method, or the async _read(n) below.
  11565. Readable.prototype.read = function (n) {
  11566. debug('read', n);
  11567. n = parseInt(n, 10);
  11568. var state = this._readableState;
  11569. var nOrig = n;
  11570. if (n !== 0) state.emittedReadable = false;
  11571. // if we're doing read(0) to trigger a readable event, but we
  11572. // already have a bunch of data in the buffer, then just trigger
  11573. // the 'readable' event and move on.
  11574. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  11575. debug('read: emitReadable', state.length, state.ended);
  11576. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  11577. return null;
  11578. }
  11579. n = howMuchToRead(n, state);
  11580. // if we've ended, and we're now clear, then finish it up.
  11581. if (n === 0 && state.ended) {
  11582. if (state.length === 0) endReadable(this);
  11583. return null;
  11584. }
  11585. // All the actual chunk generation logic needs to be
  11586. // *below* the call to _read. The reason is that in certain
  11587. // synthetic stream cases, such as passthrough streams, _read
  11588. // may be a completely synchronous operation which may change
  11589. // the state of the read buffer, providing enough data when
  11590. // before there was *not* enough.
  11591. //
  11592. // So, the steps are:
  11593. // 1. Figure out what the state of things will be after we do
  11594. // a read from the buffer.
  11595. //
  11596. // 2. If that resulting state will trigger a _read, then call _read.
  11597. // Note that this may be asynchronous, or synchronous. Yes, it is
  11598. // deeply ugly to write APIs this way, but that still doesn't mean
  11599. // that the Readable class should behave improperly, as streams are
  11600. // designed to be sync/async agnostic.
  11601. // Take note if the _read call is sync or async (ie, if the read call
  11602. // has returned yet), so that we know whether or not it's safe to emit
  11603. // 'readable' etc.
  11604. //
  11605. // 3. Actually pull the requested chunks out of the buffer and return.
  11606. // if we need a readable event, then we need to do some reading.
  11607. var doRead = state.needReadable;
  11608. debug('need readable', doRead);
  11609. // if we currently have less than the highWaterMark, then also read some
  11610. if (state.length === 0 || state.length - n < state.highWaterMark) {
  11611. doRead = true;
  11612. debug('length less than watermark', doRead);
  11613. }
  11614. // however, if we've ended, then there's no point, and if we're already
  11615. // reading, then it's unnecessary.
  11616. if (state.ended || state.reading) {
  11617. doRead = false;
  11618. debug('reading or ended', doRead);
  11619. } else if (doRead) {
  11620. debug('do read');
  11621. state.reading = true;
  11622. state.sync = true;
  11623. // if the length is currently zero, then we *need* a readable event.
  11624. if (state.length === 0) state.needReadable = true;
  11625. // call internal read method
  11626. this._read(state.highWaterMark);
  11627. state.sync = false;
  11628. // If _read pushed data synchronously, then `reading` will be false,
  11629. // and we need to re-evaluate how much data we can return to the user.
  11630. if (!state.reading) n = howMuchToRead(nOrig, state);
  11631. }
  11632. var ret;
  11633. if (n > 0) ret = fromList(n, state);else ret = null;
  11634. if (ret === null) {
  11635. state.needReadable = true;
  11636. n = 0;
  11637. } else {
  11638. state.length -= n;
  11639. }
  11640. if (state.length === 0) {
  11641. // If we have nothing in the buffer, then we want to know
  11642. // as soon as we *do* get something into the buffer.
  11643. if (!state.ended) state.needReadable = true;
  11644. // If we tried to read() past the EOF, then emit end on the next tick.
  11645. if (nOrig !== n && state.ended) endReadable(this);
  11646. }
  11647. if (ret !== null) this.emit('data', ret);
  11648. return ret;
  11649. };
  11650. function chunkInvalid(state, chunk) {
  11651. var er = null;
  11652. if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
  11653. er = new TypeError('Invalid non-string/buffer chunk');
  11654. }
  11655. return er;
  11656. }
  11657. function onEofChunk(stream, state) {
  11658. if (state.ended) return;
  11659. if (state.decoder) {
  11660. var chunk = state.decoder.end();
  11661. if (chunk && chunk.length) {
  11662. state.buffer.push(chunk);
  11663. state.length += state.objectMode ? 1 : chunk.length;
  11664. }
  11665. }
  11666. state.ended = true;
  11667. // emit 'readable' now to make sure it gets picked up.
  11668. emitReadable(stream);
  11669. }
  11670. // Don't emit readable right away in sync mode, because this can trigger
  11671. // another read() call => stack overflow. This way, it might trigger
  11672. // a nextTick recursion warning, but that's not so bad.
  11673. function emitReadable(stream) {
  11674. var state = stream._readableState;
  11675. state.needReadable = false;
  11676. if (!state.emittedReadable) {
  11677. debug('emitReadable', state.flowing);
  11678. state.emittedReadable = true;
  11679. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  11680. }
  11681. }
  11682. function emitReadable_(stream) {
  11683. debug('emit readable');
  11684. stream.emit('readable');
  11685. flow(stream);
  11686. }
  11687. // at this point, the user has presumably seen the 'readable' event,
  11688. // and called read() to consume some data. that may have triggered
  11689. // in turn another _read(n) call, in which case reading = true if
  11690. // it's in progress.
  11691. // However, if we're not ended, or reading, and the length < hwm,
  11692. // then go ahead and try to read some more preemptively.
  11693. function maybeReadMore(stream, state) {
  11694. if (!state.readingMore) {
  11695. state.readingMore = true;
  11696. processNextTick(maybeReadMore_, stream, state);
  11697. }
  11698. }
  11699. function maybeReadMore_(stream, state) {
  11700. var len = state.length;
  11701. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  11702. debug('maybeReadMore read 0');
  11703. stream.read(0);
  11704. if (len === state.length)
  11705. // didn't get any data, stop spinning.
  11706. break;else len = state.length;
  11707. }
  11708. state.readingMore = false;
  11709. }
  11710. // abstract method. to be overridden in specific implementation classes.
  11711. // call cb(er, data) where data is <= n in length.
  11712. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  11713. // arbitrary, and perhaps not very meaningful.
  11714. Readable.prototype._read = function (n) {
  11715. this.emit('error', new Error('_read() is not implemented'));
  11716. };
  11717. Readable.prototype.pipe = function (dest, pipeOpts) {
  11718. var src = this;
  11719. var state = this._readableState;
  11720. switch (state.pipesCount) {
  11721. case 0:
  11722. state.pipes = dest;
  11723. break;
  11724. case 1:
  11725. state.pipes = [state.pipes, dest];
  11726. break;
  11727. default:
  11728. state.pipes.push(dest);
  11729. break;
  11730. }
  11731. state.pipesCount += 1;
  11732. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  11733. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  11734. var endFn = doEnd ? onend : cleanup;
  11735. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  11736. dest.on('unpipe', onunpipe);
  11737. function onunpipe(readable) {
  11738. debug('onunpipe');
  11739. if (readable === src) {
  11740. cleanup();
  11741. }
  11742. }
  11743. function onend() {
  11744. debug('onend');
  11745. dest.end();
  11746. }
  11747. // when the dest drains, it reduces the awaitDrain counter
  11748. // on the source. This would be more elegant with a .once()
  11749. // handler in flow(), but adding and removing repeatedly is
  11750. // too slow.
  11751. var ondrain = pipeOnDrain(src);
  11752. dest.on('drain', ondrain);
  11753. var cleanedUp = false;
  11754. function cleanup() {
  11755. debug('cleanup');
  11756. // cleanup event handlers once the pipe is broken
  11757. dest.removeListener('close', onclose);
  11758. dest.removeListener('finish', onfinish);
  11759. dest.removeListener('drain', ondrain);
  11760. dest.removeListener('error', onerror);
  11761. dest.removeListener('unpipe', onunpipe);
  11762. src.removeListener('end', onend);
  11763. src.removeListener('end', cleanup);
  11764. src.removeListener('data', ondata);
  11765. cleanedUp = true;
  11766. // if the reader is waiting for a drain event from this
  11767. // specific writer, then it would cause it to never start
  11768. // flowing again.
  11769. // So, if this is awaiting a drain, then we just call it now.
  11770. // If we don't know, then assume that we are waiting for one.
  11771. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  11772. }
  11773. // If the user pushes more data while we're writing to dest then we'll end up
  11774. // in ondata again. However, we only want to increase awaitDrain once because
  11775. // dest will only emit one 'drain' event for the multiple writes.
  11776. // => Introduce a guard on increasing awaitDrain.
  11777. var increasedAwaitDrain = false;
  11778. src.on('data', ondata);
  11779. function ondata(chunk) {
  11780. debug('ondata');
  11781. increasedAwaitDrain = false;
  11782. var ret = dest.write(chunk);
  11783. if (false === ret && !increasedAwaitDrain) {
  11784. // If the user unpiped during `dest.write()`, it is possible
  11785. // to get stuck in a permanently paused state if that write
  11786. // also returned false.
  11787. // => Check whether `dest` is still a piping destination.
  11788. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  11789. debug('false write response, pause', src._readableState.awaitDrain);
  11790. src._readableState.awaitDrain++;
  11791. increasedAwaitDrain = true;
  11792. }
  11793. src.pause();
  11794. }
  11795. }
  11796. // if the dest has an error, then stop piping into it.
  11797. // however, don't suppress the throwing behavior for this.
  11798. function onerror(er) {
  11799. debug('onerror', er);
  11800. unpipe();
  11801. dest.removeListener('error', onerror);
  11802. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  11803. }
  11804. // Make sure our error handler is attached before userland ones.
  11805. prependListener(dest, 'error', onerror);
  11806. // Both close and finish should trigger unpipe, but only once.
  11807. function onclose() {
  11808. dest.removeListener('finish', onfinish);
  11809. unpipe();
  11810. }
  11811. dest.once('close', onclose);
  11812. function onfinish() {
  11813. debug('onfinish');
  11814. dest.removeListener('close', onclose);
  11815. unpipe();
  11816. }
  11817. dest.once('finish', onfinish);
  11818. function unpipe() {
  11819. debug('unpipe');
  11820. src.unpipe(dest);
  11821. }
  11822. // tell the dest that it's being piped to
  11823. dest.emit('pipe', src);
  11824. // start the flow if it hasn't been started already.
  11825. if (!state.flowing) {
  11826. debug('pipe resume');
  11827. src.resume();
  11828. }
  11829. return dest;
  11830. };
  11831. function pipeOnDrain(src) {
  11832. return function () {
  11833. var state = src._readableState;
  11834. debug('pipeOnDrain', state.awaitDrain);
  11835. if (state.awaitDrain) state.awaitDrain--;
  11836. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  11837. state.flowing = true;
  11838. flow(src);
  11839. }
  11840. };
  11841. }
  11842. Readable.prototype.unpipe = function (dest) {
  11843. var state = this._readableState;
  11844. // if we're not piping anywhere, then do nothing.
  11845. if (state.pipesCount === 0) return this;
  11846. // just one destination. most common case.
  11847. if (state.pipesCount === 1) {
  11848. // passed in one, but it's not the right one.
  11849. if (dest && dest !== state.pipes) return this;
  11850. if (!dest) dest = state.pipes;
  11851. // got a match.
  11852. state.pipes = null;
  11853. state.pipesCount = 0;
  11854. state.flowing = false;
  11855. if (dest) dest.emit('unpipe', this);
  11856. return this;
  11857. }
  11858. // slow case. multiple pipe destinations.
  11859. if (!dest) {
  11860. // remove all.
  11861. var dests = state.pipes;
  11862. var len = state.pipesCount;
  11863. state.pipes = null;
  11864. state.pipesCount = 0;
  11865. state.flowing = false;
  11866. for (var i = 0; i < len; i++) {
  11867. dests[i].emit('unpipe', this);
  11868. }return this;
  11869. }
  11870. // try to find the right one.
  11871. var index = indexOf(state.pipes, dest);
  11872. if (index === -1) return this;
  11873. state.pipes.splice(index, 1);
  11874. state.pipesCount -= 1;
  11875. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  11876. dest.emit('unpipe', this);
  11877. return this;
  11878. };
  11879. // set up data events if they are asked for
  11880. // Ensure readable listeners eventually get something
  11881. Readable.prototype.on = function (ev, fn) {
  11882. var res = Stream.prototype.on.call(this, ev, fn);
  11883. if (ev === 'data') {
  11884. // Start flowing on next tick if stream isn't explicitly paused
  11885. if (this._readableState.flowing !== false) this.resume();
  11886. } else if (ev === 'readable') {
  11887. var state = this._readableState;
  11888. if (!state.endEmitted && !state.readableListening) {
  11889. state.readableListening = state.needReadable = true;
  11890. state.emittedReadable = false;
  11891. if (!state.reading) {
  11892. processNextTick(nReadingNextTick, this);
  11893. } else if (state.length) {
  11894. emitReadable(this, state);
  11895. }
  11896. }
  11897. }
  11898. return res;
  11899. };
  11900. Readable.prototype.addListener = Readable.prototype.on;
  11901. function nReadingNextTick(self) {
  11902. debug('readable nexttick read 0');
  11903. self.read(0);
  11904. }
  11905. // pause() and resume() are remnants of the legacy readable stream API
  11906. // If the user uses them, then switch into old mode.
  11907. Readable.prototype.resume = function () {
  11908. var state = this._readableState;
  11909. if (!state.flowing) {
  11910. debug('resume');
  11911. state.flowing = true;
  11912. resume(this, state);
  11913. }
  11914. return this;
  11915. };
  11916. function resume(stream, state) {
  11917. if (!state.resumeScheduled) {
  11918. state.resumeScheduled = true;
  11919. processNextTick(resume_, stream, state);
  11920. }
  11921. }
  11922. function resume_(stream, state) {
  11923. if (!state.reading) {
  11924. debug('resume read 0');
  11925. stream.read(0);
  11926. }
  11927. state.resumeScheduled = false;
  11928. state.awaitDrain = 0;
  11929. stream.emit('resume');
  11930. flow(stream);
  11931. if (state.flowing && !state.reading) stream.read(0);
  11932. }
  11933. Readable.prototype.pause = function () {
  11934. debug('call pause flowing=%j', this._readableState.flowing);
  11935. if (false !== this._readableState.flowing) {
  11936. debug('pause');
  11937. this._readableState.flowing = false;
  11938. this.emit('pause');
  11939. }
  11940. return this;
  11941. };
  11942. function flow(stream) {
  11943. var state = stream._readableState;
  11944. debug('flow', state.flowing);
  11945. while (state.flowing && stream.read() !== null) {}
  11946. }
  11947. // wrap an old-style stream as the async data source.
  11948. // This is *not* part of the readable stream interface.
  11949. // It is an ugly unfortunate mess of history.
  11950. Readable.prototype.wrap = function (stream) {
  11951. var state = this._readableState;
  11952. var paused = false;
  11953. var self = this;
  11954. stream.on('end', function () {
  11955. debug('wrapped end');
  11956. if (state.decoder && !state.ended) {
  11957. var chunk = state.decoder.end();
  11958. if (chunk && chunk.length) self.push(chunk);
  11959. }
  11960. self.push(null);
  11961. });
  11962. stream.on('data', function (chunk) {
  11963. debug('wrapped data');
  11964. if (state.decoder) chunk = state.decoder.write(chunk);
  11965. // don't skip over falsy values in objectMode
  11966. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  11967. var ret = self.push(chunk);
  11968. if (!ret) {
  11969. paused = true;
  11970. stream.pause();
  11971. }
  11972. });
  11973. // proxy all the other methods.
  11974. // important when wrapping filters and duplexes.
  11975. for (var i in stream) {
  11976. if (this[i] === undefined && typeof stream[i] === 'function') {
  11977. this[i] = function (method) {
  11978. return function () {
  11979. return stream[method].apply(stream, arguments);
  11980. };
  11981. }(i);
  11982. }
  11983. }
  11984. // proxy certain important events.
  11985. for (var n = 0; n < kProxyEvents.length; n++) {
  11986. stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
  11987. }
  11988. // when we try to consume some more bytes, simply unpause the
  11989. // underlying stream.
  11990. self._read = function (n) {
  11991. debug('wrapped _read', n);
  11992. if (paused) {
  11993. paused = false;
  11994. stream.resume();
  11995. }
  11996. };
  11997. return self;
  11998. };
  11999. // exposed for testing purposes only.
  12000. Readable._fromList = fromList;
  12001. // Pluck off n bytes from an array of buffers.
  12002. // Length is the combined lengths of all the buffers in the list.
  12003. // This function is designed to be inlinable, so please take care when making
  12004. // changes to the function body.
  12005. function fromList(n, state) {
  12006. // nothing buffered
  12007. if (state.length === 0) return null;
  12008. var ret;
  12009. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  12010. // read it all, truncate the list
  12011. 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);
  12012. state.buffer.clear();
  12013. } else {
  12014. // read part of list
  12015. ret = fromListPartial(n, state.buffer, state.decoder);
  12016. }
  12017. return ret;
  12018. }
  12019. // Extracts only enough buffered data to satisfy the amount requested.
  12020. // This function is designed to be inlinable, so please take care when making
  12021. // changes to the function body.
  12022. function fromListPartial(n, list, hasStrings) {
  12023. var ret;
  12024. if (n < list.head.data.length) {
  12025. // slice is the same for buffers and strings
  12026. ret = list.head.data.slice(0, n);
  12027. list.head.data = list.head.data.slice(n);
  12028. } else if (n === list.head.data.length) {
  12029. // first chunk is a perfect match
  12030. ret = list.shift();
  12031. } else {
  12032. // result spans more than one buffer
  12033. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  12034. }
  12035. return ret;
  12036. }
  12037. // Copies a specified amount of characters from the list of buffered data
  12038. // chunks.
  12039. // This function is designed to be inlinable, so please take care when making
  12040. // changes to the function body.
  12041. function copyFromBufferString(n, list) {
  12042. var p = list.head;
  12043. var c = 1;
  12044. var ret = p.data;
  12045. n -= ret.length;
  12046. while (p = p.next) {
  12047. var str = p.data;
  12048. var nb = n > str.length ? str.length : n;
  12049. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  12050. n -= nb;
  12051. if (n === 0) {
  12052. if (nb === str.length) {
  12053. ++c;
  12054. if (p.next) list.head = p.next;else list.head = list.tail = null;
  12055. } else {
  12056. list.head = p;
  12057. p.data = str.slice(nb);
  12058. }
  12059. break;
  12060. }
  12061. ++c;
  12062. }
  12063. list.length -= c;
  12064. return ret;
  12065. }
  12066. // Copies a specified amount of bytes from the list of buffered data chunks.
  12067. // This function is designed to be inlinable, so please take care when making
  12068. // changes to the function body.
  12069. function copyFromBuffer(n, list) {
  12070. var ret = bufferShim.allocUnsafe(n);
  12071. var p = list.head;
  12072. var c = 1;
  12073. p.data.copy(ret);
  12074. n -= p.data.length;
  12075. while (p = p.next) {
  12076. var buf = p.data;
  12077. var nb = n > buf.length ? buf.length : n;
  12078. buf.copy(ret, ret.length - n, 0, nb);
  12079. n -= nb;
  12080. if (n === 0) {
  12081. if (nb === buf.length) {
  12082. ++c;
  12083. if (p.next) list.head = p.next;else list.head = list.tail = null;
  12084. } else {
  12085. list.head = p;
  12086. p.data = buf.slice(nb);
  12087. }
  12088. break;
  12089. }
  12090. ++c;
  12091. }
  12092. list.length -= c;
  12093. return ret;
  12094. }
  12095. function endReadable(stream) {
  12096. var state = stream._readableState;
  12097. // If we get here before consuming all the bytes, then that is a
  12098. // bug in node. Should never happen.
  12099. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  12100. if (!state.endEmitted) {
  12101. state.ended = true;
  12102. processNextTick(endReadableNT, state, stream);
  12103. }
  12104. }
  12105. function endReadableNT(state, stream) {
  12106. // Check that we didn't get one last unshift.
  12107. if (!state.endEmitted && state.length === 0) {
  12108. state.endEmitted = true;
  12109. stream.readable = false;
  12110. stream.emit('end');
  12111. }
  12112. }
  12113. function forEach(xs, f) {
  12114. for (var i = 0, l = xs.length; i < l; i++) {
  12115. f(xs[i], i);
  12116. }
  12117. }
  12118. function indexOf(xs, x) {
  12119. for (var i = 0, l = xs.length; i < l; i++) {
  12120. if (xs[i] === x) return i;
  12121. }
  12122. return -1;
  12123. }
  12124. }).call(this,require('_process'))
  12125. },{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"events":34,"inherits":36,"isarray":38,"process-nextick-args":50,"string_decoder/":65,"util":28}],56:[function(require,module,exports){
  12126. // a transform stream is a readable/writable stream where you do
  12127. // something with the data. Sometimes it's called a "filter",
  12128. // but that's not a great name for it, since that implies a thing where
  12129. // some bits pass through, and others are simply ignored. (That would
  12130. // be a valid example of a transform, of course.)
  12131. //
  12132. // While the output is causally related to the input, it's not a
  12133. // necessarily symmetric or synchronous transformation. For example,
  12134. // a zlib stream might take multiple plain-text writes(), and then
  12135. // emit a single compressed chunk some time in the future.
  12136. //
  12137. // Here's how this works:
  12138. //
  12139. // The Transform stream has all the aspects of the readable and writable
  12140. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  12141. // internally, and returns false if there's a lot of pending writes
  12142. // buffered up. When you call read(), that calls _read(n) until
  12143. // there's enough pending readable data buffered up.
  12144. //
  12145. // In a transform stream, the written data is placed in a buffer. When
  12146. // _read(n) is called, it transforms the queued up data, calling the
  12147. // buffered _write cb's as it consumes chunks. If consuming a single
  12148. // written chunk would result in multiple output chunks, then the first
  12149. // outputted bit calls the readcb, and subsequent chunks just go into
  12150. // the read buffer, and will cause it to emit 'readable' if necessary.
  12151. //
  12152. // This way, back-pressure is actually determined by the reading side,
  12153. // since _read has to be called to start processing a new chunk. However,
  12154. // a pathological inflate type of transform can cause excessive buffering
  12155. // here. For example, imagine a stream where every byte of input is
  12156. // interpreted as an integer from 0-255, and then results in that many
  12157. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  12158. // 1kb of data being output. In this case, you could write a very small
  12159. // amount of input, and end up with a very large amount of output. In
  12160. // such a pathological inflating mechanism, there'd be no way to tell
  12161. // the system to stop doing the transform. A single 4MB write could
  12162. // cause the system to run out of memory.
  12163. //
  12164. // However, even in such a pathological case, only a single written chunk
  12165. // would be consumed, and then the rest would wait (un-transformed) until
  12166. // the results of the previous transformed chunk were consumed.
  12167. 'use strict';
  12168. module.exports = Transform;
  12169. var Duplex = require('./_stream_duplex');
  12170. /*<replacement>*/
  12171. var util = require('core-util-is');
  12172. util.inherits = require('inherits');
  12173. /*</replacement>*/
  12174. util.inherits(Transform, Duplex);
  12175. function TransformState(stream) {
  12176. this.afterTransform = function (er, data) {
  12177. return afterTransform(stream, er, data);
  12178. };
  12179. this.needTransform = false;
  12180. this.transforming = false;
  12181. this.writecb = null;
  12182. this.writechunk = null;
  12183. this.writeencoding = null;
  12184. }
  12185. function afterTransform(stream, er, data) {
  12186. var ts = stream._transformState;
  12187. ts.transforming = false;
  12188. var cb = ts.writecb;
  12189. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  12190. ts.writechunk = null;
  12191. ts.writecb = null;
  12192. if (data !== null && data !== undefined) stream.push(data);
  12193. cb(er);
  12194. var rs = stream._readableState;
  12195. rs.reading = false;
  12196. if (rs.needReadable || rs.length < rs.highWaterMark) {
  12197. stream._read(rs.highWaterMark);
  12198. }
  12199. }
  12200. function Transform(options) {
  12201. if (!(this instanceof Transform)) return new Transform(options);
  12202. Duplex.call(this, options);
  12203. this._transformState = new TransformState(this);
  12204. var stream = this;
  12205. // start out asking for a readable event once data is transformed.
  12206. this._readableState.needReadable = true;
  12207. // we have implemented the _read method, and done the other things
  12208. // that Readable wants before the first _read call, so unset the
  12209. // sync guard flag.
  12210. this._readableState.sync = false;
  12211. if (options) {
  12212. if (typeof options.transform === 'function') this._transform = options.transform;
  12213. if (typeof options.flush === 'function') this._flush = options.flush;
  12214. }
  12215. // When the writable side finishes, then flush out anything remaining.
  12216. this.once('prefinish', function () {
  12217. if (typeof this._flush === 'function') this._flush(function (er, data) {
  12218. done(stream, er, data);
  12219. });else done(stream);
  12220. });
  12221. }
  12222. Transform.prototype.push = function (chunk, encoding) {
  12223. this._transformState.needTransform = false;
  12224. return Duplex.prototype.push.call(this, chunk, encoding);
  12225. };
  12226. // This is the part where you do stuff!
  12227. // override this function in implementation classes.
  12228. // 'chunk' is an input chunk.
  12229. //
  12230. // Call `push(newChunk)` to pass along transformed output
  12231. // to the readable side. You may call 'push' zero or more times.
  12232. //
  12233. // Call `cb(err)` when you are done with this chunk. If you pass
  12234. // an error, then that'll put the hurt on the whole operation. If you
  12235. // never call cb(), then you'll never get another chunk.
  12236. Transform.prototype._transform = function (chunk, encoding, cb) {
  12237. throw new Error('_transform() is not implemented');
  12238. };
  12239. Transform.prototype._write = function (chunk, encoding, cb) {
  12240. var ts = this._transformState;
  12241. ts.writecb = cb;
  12242. ts.writechunk = chunk;
  12243. ts.writeencoding = encoding;
  12244. if (!ts.transforming) {
  12245. var rs = this._readableState;
  12246. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  12247. }
  12248. };
  12249. // Doesn't matter what the args are here.
  12250. // _transform does all the work.
  12251. // That we got here means that the readable side wants more data.
  12252. Transform.prototype._read = function (n) {
  12253. var ts = this._transformState;
  12254. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  12255. ts.transforming = true;
  12256. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  12257. } else {
  12258. // mark that we need a transform, so that any data that comes in
  12259. // will get processed, now that we've asked for it.
  12260. ts.needTransform = true;
  12261. }
  12262. };
  12263. function done(stream, er, data) {
  12264. if (er) return stream.emit('error', er);
  12265. if (data !== null && data !== undefined) stream.push(data);
  12266. // if there's nothing in the write buffer, then that means
  12267. // that nothing more will ever be provided
  12268. var ws = stream._writableState;
  12269. var ts = stream._transformState;
  12270. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  12271. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  12272. return stream.push(null);
  12273. }
  12274. },{"./_stream_duplex":53,"core-util-is":33,"inherits":36}],57:[function(require,module,exports){
  12275. (function (process,setImmediate){
  12276. // A bit simpler than readable streams.
  12277. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  12278. // the drain event emission and buffering.
  12279. 'use strict';
  12280. module.exports = Writable;
  12281. /*<replacement>*/
  12282. var processNextTick = require('process-nextick-args');
  12283. /*</replacement>*/
  12284. /*<replacement>*/
  12285. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  12286. /*</replacement>*/
  12287. /*<replacement>*/
  12288. var Duplex;
  12289. /*</replacement>*/
  12290. Writable.WritableState = WritableState;
  12291. /*<replacement>*/
  12292. var util = require('core-util-is');
  12293. util.inherits = require('inherits');
  12294. /*</replacement>*/
  12295. /*<replacement>*/
  12296. var internalUtil = {
  12297. deprecate: require('util-deprecate')
  12298. };
  12299. /*</replacement>*/
  12300. /*<replacement>*/
  12301. var Stream = require('./internal/streams/stream');
  12302. /*</replacement>*/
  12303. var Buffer = require('buffer').Buffer;
  12304. /*<replacement>*/
  12305. var bufferShim = require('buffer-shims');
  12306. /*</replacement>*/
  12307. util.inherits(Writable, Stream);
  12308. function nop() {}
  12309. function WriteReq(chunk, encoding, cb) {
  12310. this.chunk = chunk;
  12311. this.encoding = encoding;
  12312. this.callback = cb;
  12313. this.next = null;
  12314. }
  12315. function WritableState(options, stream) {
  12316. Duplex = Duplex || require('./_stream_duplex');
  12317. options = options || {};
  12318. // object stream flag to indicate whether or not this stream
  12319. // contains buffers or objects.
  12320. this.objectMode = !!options.objectMode;
  12321. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  12322. // the point at which write() starts returning false
  12323. // Note: 0 is a valid value, means that we always return false if
  12324. // the entire buffer is not flushed immediately on write()
  12325. var hwm = options.highWaterMark;
  12326. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  12327. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  12328. // cast to ints.
  12329. this.highWaterMark = ~~this.highWaterMark;
  12330. // drain event flag.
  12331. this.needDrain = false;
  12332. // at the start of calling end()
  12333. this.ending = false;
  12334. // when end() has been called, and returned
  12335. this.ended = false;
  12336. // when 'finish' is emitted
  12337. this.finished = false;
  12338. // should we decode strings into buffers before passing to _write?
  12339. // this is here so that some node-core streams can optimize string
  12340. // handling at a lower level.
  12341. var noDecode = options.decodeStrings === false;
  12342. this.decodeStrings = !noDecode;
  12343. // Crypto is kind of old and crusty. Historically, its default string
  12344. // encoding is 'binary' so we have to make this configurable.
  12345. // Everything else in the universe uses 'utf8', though.
  12346. this.defaultEncoding = options.defaultEncoding || 'utf8';
  12347. // not an actual buffer we keep track of, but a measurement
  12348. // of how much we're waiting to get pushed to some underlying
  12349. // socket or file.
  12350. this.length = 0;
  12351. // a flag to see when we're in the middle of a write.
  12352. this.writing = false;
  12353. // when true all writes will be buffered until .uncork() call
  12354. this.corked = 0;
  12355. // a flag to be able to tell if the onwrite cb is called immediately,
  12356. // or on a later tick. We set this to true at first, because any
  12357. // actions that shouldn't happen until "later" should generally also
  12358. // not happen before the first write call.
  12359. this.sync = true;
  12360. // a flag to know if we're processing previously buffered items, which
  12361. // may call the _write() callback in the same tick, so that we don't
  12362. // end up in an overlapped onwrite situation.
  12363. this.bufferProcessing = false;
  12364. // the callback that's passed to _write(chunk,cb)
  12365. this.onwrite = function (er) {
  12366. onwrite(stream, er);
  12367. };
  12368. // the callback that the user supplies to write(chunk,encoding,cb)
  12369. this.writecb = null;
  12370. // the amount that is being written when _write is called.
  12371. this.writelen = 0;
  12372. this.bufferedRequest = null;
  12373. this.lastBufferedRequest = null;
  12374. // number of pending user-supplied write callbacks
  12375. // this must be 0 before 'finish' can be emitted
  12376. this.pendingcb = 0;
  12377. // emit prefinish if the only thing we're waiting for is _write cbs
  12378. // This is relevant for synchronous Transform streams
  12379. this.prefinished = false;
  12380. // True if the error was already emitted and should not be thrown again
  12381. this.errorEmitted = false;
  12382. // count buffered requests
  12383. this.bufferedRequestCount = 0;
  12384. // allocate the first CorkedRequest, there is always
  12385. // one allocated and free to use, and we maintain at most two
  12386. this.corkedRequestsFree = new CorkedRequest(this);
  12387. }
  12388. WritableState.prototype.getBuffer = function getBuffer() {
  12389. var current = this.bufferedRequest;
  12390. var out = [];
  12391. while (current) {
  12392. out.push(current);
  12393. current = current.next;
  12394. }
  12395. return out;
  12396. };
  12397. (function () {
  12398. try {
  12399. Object.defineProperty(WritableState.prototype, 'buffer', {
  12400. get: internalUtil.deprecate(function () {
  12401. return this.getBuffer();
  12402. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
  12403. });
  12404. } catch (_) {}
  12405. })();
  12406. // Test _writableState for inheritance to account for Duplex streams,
  12407. // whose prototype chain only points to Readable.
  12408. var realHasInstance;
  12409. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  12410. realHasInstance = Function.prototype[Symbol.hasInstance];
  12411. Object.defineProperty(Writable, Symbol.hasInstance, {
  12412. value: function (object) {
  12413. if (realHasInstance.call(this, object)) return true;
  12414. return object && object._writableState instanceof WritableState;
  12415. }
  12416. });
  12417. } else {
  12418. realHasInstance = function (object) {
  12419. return object instanceof this;
  12420. };
  12421. }
  12422. function Writable(options) {
  12423. Duplex = Duplex || require('./_stream_duplex');
  12424. // Writable ctor is applied to Duplexes, too.
  12425. // `realHasInstance` is necessary because using plain `instanceof`
  12426. // would return false, as no `_writableState` property is attached.
  12427. // Trying to use the custom `instanceof` for Writable here will also break the
  12428. // Node.js LazyTransform implementation, which has a non-trivial getter for
  12429. // `_writableState` that would lead to infinite recursion.
  12430. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  12431. return new Writable(options);
  12432. }
  12433. this._writableState = new WritableState(options, this);
  12434. // legacy.
  12435. this.writable = true;
  12436. if (options) {
  12437. if (typeof options.write === 'function') this._write = options.write;
  12438. if (typeof options.writev === 'function') this._writev = options.writev;
  12439. }
  12440. Stream.call(this);
  12441. }
  12442. // Otherwise people can pipe Writable streams, which is just wrong.
  12443. Writable.prototype.pipe = function () {
  12444. this.emit('error', new Error('Cannot pipe, not readable'));
  12445. };
  12446. function writeAfterEnd(stream, cb) {
  12447. var er = new Error('write after end');
  12448. // TODO: defer error events consistently everywhere, not just the cb
  12449. stream.emit('error', er);
  12450. processNextTick(cb, er);
  12451. }
  12452. // Checks that a user-supplied chunk is valid, especially for the particular
  12453. // mode the stream is in. Currently this means that `null` is never accepted
  12454. // and undefined/non-string values are only allowed in object mode.
  12455. function validChunk(stream, state, chunk, cb) {
  12456. var valid = true;
  12457. var er = false;
  12458. if (chunk === null) {
  12459. er = new TypeError('May not write null values to stream');
  12460. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12461. er = new TypeError('Invalid non-string/buffer chunk');
  12462. }
  12463. if (er) {
  12464. stream.emit('error', er);
  12465. processNextTick(cb, er);
  12466. valid = false;
  12467. }
  12468. return valid;
  12469. }
  12470. Writable.prototype.write = function (chunk, encoding, cb) {
  12471. var state = this._writableState;
  12472. var ret = false;
  12473. var isBuf = Buffer.isBuffer(chunk);
  12474. if (typeof encoding === 'function') {
  12475. cb = encoding;
  12476. encoding = null;
  12477. }
  12478. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  12479. if (typeof cb !== 'function') cb = nop;
  12480. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  12481. state.pendingcb++;
  12482. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  12483. }
  12484. return ret;
  12485. };
  12486. Writable.prototype.cork = function () {
  12487. var state = this._writableState;
  12488. state.corked++;
  12489. };
  12490. Writable.prototype.uncork = function () {
  12491. var state = this._writableState;
  12492. if (state.corked) {
  12493. state.corked--;
  12494. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  12495. }
  12496. };
  12497. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  12498. // node::ParseEncoding() requires lower case.
  12499. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  12500. 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);
  12501. this._writableState.defaultEncoding = encoding;
  12502. return this;
  12503. };
  12504. function decodeChunk(state, chunk, encoding) {
  12505. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  12506. chunk = bufferShim.from(chunk, encoding);
  12507. }
  12508. return chunk;
  12509. }
  12510. // if we're already writing something, then just put this
  12511. // in the queue, and wait our turn. Otherwise, call _write
  12512. // If we return false, then we need a drain event, so set that flag.
  12513. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  12514. if (!isBuf) {
  12515. chunk = decodeChunk(state, chunk, encoding);
  12516. if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  12517. }
  12518. var len = state.objectMode ? 1 : chunk.length;
  12519. state.length += len;
  12520. var ret = state.length < state.highWaterMark;
  12521. // we must ensure that previous needDrain will not be reset to false.
  12522. if (!ret) state.needDrain = true;
  12523. if (state.writing || state.corked) {
  12524. var last = state.lastBufferedRequest;
  12525. state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
  12526. if (last) {
  12527. last.next = state.lastBufferedRequest;
  12528. } else {
  12529. state.bufferedRequest = state.lastBufferedRequest;
  12530. }
  12531. state.bufferedRequestCount += 1;
  12532. } else {
  12533. doWrite(stream, state, false, len, chunk, encoding, cb);
  12534. }
  12535. return ret;
  12536. }
  12537. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  12538. state.writelen = len;
  12539. state.writecb = cb;
  12540. state.writing = true;
  12541. state.sync = true;
  12542. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  12543. state.sync = false;
  12544. }
  12545. function onwriteError(stream, state, sync, er, cb) {
  12546. --state.pendingcb;
  12547. if (sync) processNextTick(cb, er);else cb(er);
  12548. stream._writableState.errorEmitted = true;
  12549. stream.emit('error', er);
  12550. }
  12551. function onwriteStateUpdate(state) {
  12552. state.writing = false;
  12553. state.writecb = null;
  12554. state.length -= state.writelen;
  12555. state.writelen = 0;
  12556. }
  12557. function onwrite(stream, er) {
  12558. var state = stream._writableState;
  12559. var sync = state.sync;
  12560. var cb = state.writecb;
  12561. onwriteStateUpdate(state);
  12562. if (er) onwriteError(stream, state, sync, er, cb);else {
  12563. // Check if we're actually ready to finish, but don't emit yet
  12564. var finished = needFinish(state);
  12565. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  12566. clearBuffer(stream, state);
  12567. }
  12568. if (sync) {
  12569. /*<replacement>*/
  12570. asyncWrite(afterWrite, stream, state, finished, cb);
  12571. /*</replacement>*/
  12572. } else {
  12573. afterWrite(stream, state, finished, cb);
  12574. }
  12575. }
  12576. }
  12577. function afterWrite(stream, state, finished, cb) {
  12578. if (!finished) onwriteDrain(stream, state);
  12579. state.pendingcb--;
  12580. cb();
  12581. finishMaybe(stream, state);
  12582. }
  12583. // Must force callback to be called on nextTick, so that we don't
  12584. // emit 'drain' before the write() consumer gets the 'false' return
  12585. // value, and has a chance to attach a 'drain' listener.
  12586. function onwriteDrain(stream, state) {
  12587. if (state.length === 0 && state.needDrain) {
  12588. state.needDrain = false;
  12589. stream.emit('drain');
  12590. }
  12591. }
  12592. // if there's something in the buffer waiting, then process it
  12593. function clearBuffer(stream, state) {
  12594. state.bufferProcessing = true;
  12595. var entry = state.bufferedRequest;
  12596. if (stream._writev && entry && entry.next) {
  12597. // Fast case, write everything using _writev()
  12598. var l = state.bufferedRequestCount;
  12599. var buffer = new Array(l);
  12600. var holder = state.corkedRequestsFree;
  12601. holder.entry = entry;
  12602. var count = 0;
  12603. while (entry) {
  12604. buffer[count] = entry;
  12605. entry = entry.next;
  12606. count += 1;
  12607. }
  12608. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  12609. // doWrite is almost always async, defer these to save a bit of time
  12610. // as the hot path ends with doWrite
  12611. state.pendingcb++;
  12612. state.lastBufferedRequest = null;
  12613. if (holder.next) {
  12614. state.corkedRequestsFree = holder.next;
  12615. holder.next = null;
  12616. } else {
  12617. state.corkedRequestsFree = new CorkedRequest(state);
  12618. }
  12619. } else {
  12620. // Slow case, write chunks one-by-one
  12621. while (entry) {
  12622. var chunk = entry.chunk;
  12623. var encoding = entry.encoding;
  12624. var cb = entry.callback;
  12625. var len = state.objectMode ? 1 : chunk.length;
  12626. doWrite(stream, state, false, len, chunk, encoding, cb);
  12627. entry = entry.next;
  12628. // if we didn't call the onwrite immediately, then
  12629. // it means that we need to wait until it does.
  12630. // also, that means that the chunk and cb are currently
  12631. // being processed, so move the buffer counter past them.
  12632. if (state.writing) {
  12633. break;
  12634. }
  12635. }
  12636. if (entry === null) state.lastBufferedRequest = null;
  12637. }
  12638. state.bufferedRequestCount = 0;
  12639. state.bufferedRequest = entry;
  12640. state.bufferProcessing = false;
  12641. }
  12642. Writable.prototype._write = function (chunk, encoding, cb) {
  12643. cb(new Error('_write() is not implemented'));
  12644. };
  12645. Writable.prototype._writev = null;
  12646. Writable.prototype.end = function (chunk, encoding, cb) {
  12647. var state = this._writableState;
  12648. if (typeof chunk === 'function') {
  12649. cb = chunk;
  12650. chunk = null;
  12651. encoding = null;
  12652. } else if (typeof encoding === 'function') {
  12653. cb = encoding;
  12654. encoding = null;
  12655. }
  12656. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  12657. // .end() fully uncorks
  12658. if (state.corked) {
  12659. state.corked = 1;
  12660. this.uncork();
  12661. }
  12662. // ignore unnecessary end() calls.
  12663. if (!state.ending && !state.finished) endWritable(this, state, cb);
  12664. };
  12665. function needFinish(state) {
  12666. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  12667. }
  12668. function prefinish(stream, state) {
  12669. if (!state.prefinished) {
  12670. state.prefinished = true;
  12671. stream.emit('prefinish');
  12672. }
  12673. }
  12674. function finishMaybe(stream, state) {
  12675. var need = needFinish(state);
  12676. if (need) {
  12677. if (state.pendingcb === 0) {
  12678. prefinish(stream, state);
  12679. state.finished = true;
  12680. stream.emit('finish');
  12681. } else {
  12682. prefinish(stream, state);
  12683. }
  12684. }
  12685. return need;
  12686. }
  12687. function endWritable(stream, state, cb) {
  12688. state.ending = true;
  12689. finishMaybe(stream, state);
  12690. if (cb) {
  12691. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  12692. }
  12693. state.ended = true;
  12694. stream.writable = false;
  12695. }
  12696. // It seems a linked list but it is not
  12697. // there will be only 2 of these for each stream
  12698. function CorkedRequest(state) {
  12699. var _this = this;
  12700. this.next = null;
  12701. this.entry = null;
  12702. this.finish = function (err) {
  12703. var entry = _this.entry;
  12704. _this.entry = null;
  12705. while (entry) {
  12706. var cb = entry.callback;
  12707. state.pendingcb--;
  12708. cb(err);
  12709. entry = entry.next;
  12710. }
  12711. if (state.corkedRequestsFree) {
  12712. state.corkedRequestsFree.next = _this;
  12713. } else {
  12714. state.corkedRequestsFree = _this;
  12715. }
  12716. };
  12717. }
  12718. }).call(this,require('_process'),require("timers").setImmediate)
  12719. },{"./_stream_duplex":53,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"inherits":36,"process-nextick-args":50,"timers":66,"util-deprecate":67}],58:[function(require,module,exports){
  12720. 'use strict';
  12721. var Buffer = require('buffer').Buffer;
  12722. /*<replacement>*/
  12723. var bufferShim = require('buffer-shims');
  12724. /*</replacement>*/
  12725. module.exports = BufferList;
  12726. function BufferList() {
  12727. this.head = null;
  12728. this.tail = null;
  12729. this.length = 0;
  12730. }
  12731. BufferList.prototype.push = function (v) {
  12732. var entry = { data: v, next: null };
  12733. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  12734. this.tail = entry;
  12735. ++this.length;
  12736. };
  12737. BufferList.prototype.unshift = function (v) {
  12738. var entry = { data: v, next: this.head };
  12739. if (this.length === 0) this.tail = entry;
  12740. this.head = entry;
  12741. ++this.length;
  12742. };
  12743. BufferList.prototype.shift = function () {
  12744. if (this.length === 0) return;
  12745. var ret = this.head.data;
  12746. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  12747. --this.length;
  12748. return ret;
  12749. };
  12750. BufferList.prototype.clear = function () {
  12751. this.head = this.tail = null;
  12752. this.length = 0;
  12753. };
  12754. BufferList.prototype.join = function (s) {
  12755. if (this.length === 0) return '';
  12756. var p = this.head;
  12757. var ret = '' + p.data;
  12758. while (p = p.next) {
  12759. ret += s + p.data;
  12760. }return ret;
  12761. };
  12762. BufferList.prototype.concat = function (n) {
  12763. if (this.length === 0) return bufferShim.alloc(0);
  12764. if (this.length === 1) return this.head.data;
  12765. var ret = bufferShim.allocUnsafe(n >>> 0);
  12766. var p = this.head;
  12767. var i = 0;
  12768. while (p) {
  12769. p.data.copy(ret, i);
  12770. i += p.data.length;
  12771. p = p.next;
  12772. }
  12773. return ret;
  12774. };
  12775. },{"buffer":32,"buffer-shims":31}],59:[function(require,module,exports){
  12776. module.exports = require('events').EventEmitter;
  12777. },{"events":34}],60:[function(require,module,exports){
  12778. module.exports = require('./readable').PassThrough
  12779. },{"./readable":61}],61:[function(require,module,exports){
  12780. exports = module.exports = require('./lib/_stream_readable.js');
  12781. exports.Stream = exports;
  12782. exports.Readable = exports;
  12783. exports.Writable = require('./lib/_stream_writable.js');
  12784. exports.Duplex = require('./lib/_stream_duplex.js');
  12785. exports.Transform = require('./lib/_stream_transform.js');
  12786. exports.PassThrough = require('./lib/_stream_passthrough.js');
  12787. },{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],62:[function(require,module,exports){
  12788. module.exports = require('./readable').Transform
  12789. },{"./readable":61}],63:[function(require,module,exports){
  12790. module.exports = require('./lib/_stream_writable.js');
  12791. },{"./lib/_stream_writable.js":57}],64:[function(require,module,exports){
  12792. // Copyright Joyent, Inc. and other Node contributors.
  12793. //
  12794. // Permission is hereby granted, free of charge, to any person obtaining a
  12795. // copy of this software and associated documentation files (the
  12796. // "Software"), to deal in the Software without restriction, including
  12797. // without limitation the rights to use, copy, modify, merge, publish,
  12798. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12799. // persons to whom the Software is furnished to do so, subject to the
  12800. // following conditions:
  12801. //
  12802. // The above copyright notice and this permission notice shall be included
  12803. // in all copies or substantial portions of the Software.
  12804. //
  12805. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12806. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12807. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12808. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12809. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12810. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12811. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12812. module.exports = Stream;
  12813. var EE = require('events').EventEmitter;
  12814. var inherits = require('inherits');
  12815. inherits(Stream, EE);
  12816. Stream.Readable = require('readable-stream/readable.js');
  12817. Stream.Writable = require('readable-stream/writable.js');
  12818. Stream.Duplex = require('readable-stream/duplex.js');
  12819. Stream.Transform = require('readable-stream/transform.js');
  12820. Stream.PassThrough = require('readable-stream/passthrough.js');
  12821. // Backwards-compat with node 0.4.x
  12822. Stream.Stream = Stream;
  12823. // old-style streams. Note that the pipe method (the only relevant
  12824. // part of this class) is overridden in the Readable class.
  12825. function Stream() {
  12826. EE.call(this);
  12827. }
  12828. Stream.prototype.pipe = function(dest, options) {
  12829. var source = this;
  12830. function ondata(chunk) {
  12831. if (dest.writable) {
  12832. if (false === dest.write(chunk) && source.pause) {
  12833. source.pause();
  12834. }
  12835. }
  12836. }
  12837. source.on('data', ondata);
  12838. function ondrain() {
  12839. if (source.readable && source.resume) {
  12840. source.resume();
  12841. }
  12842. }
  12843. dest.on('drain', ondrain);
  12844. // If the 'end' option is not supplied, dest.end() will be called when
  12845. // source gets the 'end' or 'close' events. Only dest.end() once.
  12846. if (!dest._isStdio && (!options || options.end !== false)) {
  12847. source.on('end', onend);
  12848. source.on('close', onclose);
  12849. }
  12850. var didOnEnd = false;
  12851. function onend() {
  12852. if (didOnEnd) return;
  12853. didOnEnd = true;
  12854. dest.end();
  12855. }
  12856. function onclose() {
  12857. if (didOnEnd) return;
  12858. didOnEnd = true;
  12859. if (typeof dest.destroy === 'function') dest.destroy();
  12860. }
  12861. // don't leave dangling pipes when there are errors.
  12862. function onerror(er) {
  12863. cleanup();
  12864. if (EE.listenerCount(this, 'error') === 0) {
  12865. throw er; // Unhandled stream error in pipe.
  12866. }
  12867. }
  12868. source.on('error', onerror);
  12869. dest.on('error', onerror);
  12870. // remove all the event listeners that were added.
  12871. function cleanup() {
  12872. source.removeListener('data', ondata);
  12873. dest.removeListener('drain', ondrain);
  12874. source.removeListener('end', onend);
  12875. source.removeListener('close', onclose);
  12876. source.removeListener('error', onerror);
  12877. dest.removeListener('error', onerror);
  12878. source.removeListener('end', cleanup);
  12879. source.removeListener('close', cleanup);
  12880. dest.removeListener('close', cleanup);
  12881. }
  12882. source.on('end', cleanup);
  12883. source.on('close', cleanup);
  12884. dest.on('close', cleanup);
  12885. dest.emit('pipe', source);
  12886. // Allow for unix-like usage: A.pipe(B).pipe(C)
  12887. return dest;
  12888. };
  12889. },{"events":34,"inherits":36,"readable-stream/duplex.js":52,"readable-stream/passthrough.js":60,"readable-stream/readable.js":61,"readable-stream/transform.js":62,"readable-stream/writable.js":63}],65:[function(require,module,exports){
  12890. 'use strict';
  12891. var Buffer = require('buffer').Buffer;
  12892. var bufferShim = require('buffer-shims');
  12893. var isEncoding = Buffer.isEncoding || function (encoding) {
  12894. encoding = '' + encoding;
  12895. switch (encoding && encoding.toLowerCase()) {
  12896. 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':
  12897. return true;
  12898. default:
  12899. return false;
  12900. }
  12901. };
  12902. function _normalizeEncoding(enc) {
  12903. if (!enc) return 'utf8';
  12904. var retried;
  12905. while (true) {
  12906. switch (enc) {
  12907. case 'utf8':
  12908. case 'utf-8':
  12909. return 'utf8';
  12910. case 'ucs2':
  12911. case 'ucs-2':
  12912. case 'utf16le':
  12913. case 'utf-16le':
  12914. return 'utf16le';
  12915. case 'latin1':
  12916. case 'binary':
  12917. return 'latin1';
  12918. case 'base64':
  12919. case 'ascii':
  12920. case 'hex':
  12921. return enc;
  12922. default:
  12923. if (retried) return; // undefined
  12924. enc = ('' + enc).toLowerCase();
  12925. retried = true;
  12926. }
  12927. }
  12928. };
  12929. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  12930. // modules monkey-patch it to support additional encodings
  12931. function normalizeEncoding(enc) {
  12932. var nenc = _normalizeEncoding(enc);
  12933. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  12934. return nenc || enc;
  12935. }
  12936. // StringDecoder provides an interface for efficiently splitting a series of
  12937. // buffers into a series of JS strings without breaking apart multi-byte
  12938. // characters.
  12939. exports.StringDecoder = StringDecoder;
  12940. function StringDecoder(encoding) {
  12941. this.encoding = normalizeEncoding(encoding);
  12942. var nb;
  12943. switch (this.encoding) {
  12944. case 'utf16le':
  12945. this.text = utf16Text;
  12946. this.end = utf16End;
  12947. nb = 4;
  12948. break;
  12949. case 'utf8':
  12950. this.fillLast = utf8FillLast;
  12951. nb = 4;
  12952. break;
  12953. case 'base64':
  12954. this.text = base64Text;
  12955. this.end = base64End;
  12956. nb = 3;
  12957. break;
  12958. default:
  12959. this.write = simpleWrite;
  12960. this.end = simpleEnd;
  12961. return;
  12962. }
  12963. this.lastNeed = 0;
  12964. this.lastTotal = 0;
  12965. this.lastChar = bufferShim.allocUnsafe(nb);
  12966. }
  12967. StringDecoder.prototype.write = function (buf) {
  12968. if (buf.length === 0) return '';
  12969. var r;
  12970. var i;
  12971. if (this.lastNeed) {
  12972. r = this.fillLast(buf);
  12973. if (r === undefined) return '';
  12974. i = this.lastNeed;
  12975. this.lastNeed = 0;
  12976. } else {
  12977. i = 0;
  12978. }
  12979. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  12980. return r || '';
  12981. };
  12982. StringDecoder.prototype.end = utf8End;
  12983. // Returns only complete characters in a Buffer
  12984. StringDecoder.prototype.text = utf8Text;
  12985. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  12986. StringDecoder.prototype.fillLast = function (buf) {
  12987. if (this.lastNeed <= buf.length) {
  12988. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  12989. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  12990. }
  12991. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  12992. this.lastNeed -= buf.length;
  12993. };
  12994. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  12995. // continuation byte.
  12996. function utf8CheckByte(byte) {
  12997. 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;
  12998. return -1;
  12999. }
  13000. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  13001. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  13002. // needed to complete the UTF-8 character (if applicable) are returned.
  13003. function utf8CheckIncomplete(self, buf, i) {
  13004. var j = buf.length - 1;
  13005. if (j < i) return 0;
  13006. var nb = utf8CheckByte(buf[j]);
  13007. if (nb >= 0) {
  13008. if (nb > 0) self.lastNeed = nb - 1;
  13009. return nb;
  13010. }
  13011. if (--j < i) return 0;
  13012. nb = utf8CheckByte(buf[j]);
  13013. if (nb >= 0) {
  13014. if (nb > 0) self.lastNeed = nb - 2;
  13015. return nb;
  13016. }
  13017. if (--j < i) return 0;
  13018. nb = utf8CheckByte(buf[j]);
  13019. if (nb >= 0) {
  13020. if (nb > 0) {
  13021. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  13022. }
  13023. return nb;
  13024. }
  13025. return 0;
  13026. }
  13027. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  13028. // needed or are available. If we see a non-continuation byte where we expect
  13029. // one, we "replace" the validated continuation bytes we've seen so far with
  13030. // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
  13031. // behavior. The continuation byte check is included three times in the case
  13032. // where all of the continuation bytes for a character exist in the same buffer.
  13033. // It is also done this way as a slight performance increase instead of using a
  13034. // loop.
  13035. function utf8CheckExtraBytes(self, buf, p) {
  13036. if ((buf[0] & 0xC0) !== 0x80) {
  13037. self.lastNeed = 0;
  13038. return '\ufffd'.repeat(p);
  13039. }
  13040. if (self.lastNeed > 1 && buf.length > 1) {
  13041. if ((buf[1] & 0xC0) !== 0x80) {
  13042. self.lastNeed = 1;
  13043. return '\ufffd'.repeat(p + 1);
  13044. }
  13045. if (self.lastNeed > 2 && buf.length > 2) {
  13046. if ((buf[2] & 0xC0) !== 0x80) {
  13047. self.lastNeed = 2;
  13048. return '\ufffd'.repeat(p + 2);
  13049. }
  13050. }
  13051. }
  13052. }
  13053. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  13054. function utf8FillLast(buf) {
  13055. var p = this.lastTotal - this.lastNeed;
  13056. var r = utf8CheckExtraBytes(this, buf, p);
  13057. if (r !== undefined) return r;
  13058. if (this.lastNeed <= buf.length) {
  13059. buf.copy(this.lastChar, p, 0, this.lastNeed);
  13060. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  13061. }
  13062. buf.copy(this.lastChar, p, 0, buf.length);
  13063. this.lastNeed -= buf.length;
  13064. }
  13065. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  13066. // partial character, the character's bytes are buffered until the required
  13067. // number of bytes are available.
  13068. function utf8Text(buf, i) {
  13069. var total = utf8CheckIncomplete(this, buf, i);
  13070. if (!this.lastNeed) return buf.toString('utf8', i);
  13071. this.lastTotal = total;
  13072. var end = buf.length - (total - this.lastNeed);
  13073. buf.copy(this.lastChar, 0, end);
  13074. return buf.toString('utf8', i, end);
  13075. }
  13076. // For UTF-8, a replacement character for each buffered byte of a (partial)
  13077. // character needs to be added to the output.
  13078. function utf8End(buf) {
  13079. var r = buf && buf.length ? this.write(buf) : '';
  13080. if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
  13081. return r;
  13082. }
  13083. // UTF-16LE typically needs two bytes per character, but even if we have an even
  13084. // number of bytes available, we need to check if we end on a leading/high
  13085. // surrogate. In that case, we need to wait for the next two bytes in order to
  13086. // decode the last character properly.
  13087. function utf16Text(buf, i) {
  13088. if ((buf.length - i) % 2 === 0) {
  13089. var r = buf.toString('utf16le', i);
  13090. if (r) {
  13091. var c = r.charCodeAt(r.length - 1);
  13092. if (c >= 0xD800 && c <= 0xDBFF) {
  13093. this.lastNeed = 2;
  13094. this.lastTotal = 4;
  13095. this.lastChar[0] = buf[buf.length - 2];
  13096. this.lastChar[1] = buf[buf.length - 1];
  13097. return r.slice(0, -1);
  13098. }
  13099. }
  13100. return r;
  13101. }
  13102. this.lastNeed = 1;
  13103. this.lastTotal = 2;
  13104. this.lastChar[0] = buf[buf.length - 1];
  13105. return buf.toString('utf16le', i, buf.length - 1);
  13106. }
  13107. // For UTF-16LE we do not explicitly append special replacement characters if we
  13108. // end on a partial character, we simply let v8 handle that.
  13109. function utf16End(buf) {
  13110. var r = buf && buf.length ? this.write(buf) : '';
  13111. if (this.lastNeed) {
  13112. var end = this.lastTotal - this.lastNeed;
  13113. return r + this.lastChar.toString('utf16le', 0, end);
  13114. }
  13115. return r;
  13116. }
  13117. function base64Text(buf, i) {
  13118. var n = (buf.length - i) % 3;
  13119. if (n === 0) return buf.toString('base64', i);
  13120. this.lastNeed = 3 - n;
  13121. this.lastTotal = 3;
  13122. if (n === 1) {
  13123. this.lastChar[0] = buf[buf.length - 1];
  13124. } else {
  13125. this.lastChar[0] = buf[buf.length - 2];
  13126. this.lastChar[1] = buf[buf.length - 1];
  13127. }
  13128. return buf.toString('base64', i, buf.length - n);
  13129. }
  13130. function base64End(buf) {
  13131. var r = buf && buf.length ? this.write(buf) : '';
  13132. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  13133. return r;
  13134. }
  13135. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  13136. function simpleWrite(buf) {
  13137. return buf.toString(this.encoding);
  13138. }
  13139. function simpleEnd(buf) {
  13140. return buf && buf.length ? this.write(buf) : '';
  13141. }
  13142. },{"buffer":32,"buffer-shims":31}],66:[function(require,module,exports){
  13143. (function (setImmediate,clearImmediate){
  13144. var nextTick = require('process/browser.js').nextTick;
  13145. var apply = Function.prototype.apply;
  13146. var slice = Array.prototype.slice;
  13147. var immediateIds = {};
  13148. var nextImmediateId = 0;
  13149. // DOM APIs, for completeness
  13150. exports.setTimeout = function() {
  13151. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  13152. };
  13153. exports.setInterval = function() {
  13154. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  13155. };
  13156. exports.clearTimeout =
  13157. exports.clearInterval = function(timeout) { timeout.close(); };
  13158. function Timeout(id, clearFn) {
  13159. this._id = id;
  13160. this._clearFn = clearFn;
  13161. }
  13162. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  13163. Timeout.prototype.close = function() {
  13164. this._clearFn.call(window, this._id);
  13165. };
  13166. // Does not start the time, just sets up the members needed.
  13167. exports.enroll = function(item, msecs) {
  13168. clearTimeout(item._idleTimeoutId);
  13169. item._idleTimeout = msecs;
  13170. };
  13171. exports.unenroll = function(item) {
  13172. clearTimeout(item._idleTimeoutId);
  13173. item._idleTimeout = -1;
  13174. };
  13175. exports._unrefActive = exports.active = function(item) {
  13176. clearTimeout(item._idleTimeoutId);
  13177. var msecs = item._idleTimeout;
  13178. if (msecs >= 0) {
  13179. item._idleTimeoutId = setTimeout(function onTimeout() {
  13180. if (item._onTimeout)
  13181. item._onTimeout();
  13182. }, msecs);
  13183. }
  13184. };
  13185. // That's not how node.js implements it but the exposed api is the same.
  13186. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  13187. var id = nextImmediateId++;
  13188. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13189. immediateIds[id] = true;
  13190. nextTick(function onNextTick() {
  13191. if (immediateIds[id]) {
  13192. // fn.call() is faster so we optimize for the common use-case
  13193. // @see http://jsperf.com/call-apply-segu
  13194. if (args) {
  13195. fn.apply(null, args);
  13196. } else {
  13197. fn.call(null);
  13198. }
  13199. // Prevent ids from leaking
  13200. exports.clearImmediate(id);
  13201. }
  13202. });
  13203. return id;
  13204. };
  13205. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  13206. delete immediateIds[id];
  13207. };
  13208. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  13209. },{"process/browser.js":51,"timers":66}],67:[function(require,module,exports){
  13210. (function (global){
  13211. /**
  13212. * Module exports.
  13213. */
  13214. module.exports = deprecate;
  13215. /**
  13216. * Mark that a method should not be used.
  13217. * Returns a modified function which warns once by default.
  13218. *
  13219. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  13220. *
  13221. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  13222. * will throw an Error when invoked.
  13223. *
  13224. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  13225. * will invoke `console.trace()` instead of `console.error()`.
  13226. *
  13227. * @param {Function} fn - the function to deprecate
  13228. * @param {String} msg - the string to print to the console when `fn` is invoked
  13229. * @returns {Function} a new "deprecated" version of `fn`
  13230. * @api public
  13231. */
  13232. function deprecate (fn, msg) {
  13233. if (config('noDeprecation')) {
  13234. return fn;
  13235. }
  13236. var warned = false;
  13237. function deprecated() {
  13238. if (!warned) {
  13239. if (config('throwDeprecation')) {
  13240. throw new Error(msg);
  13241. } else if (config('traceDeprecation')) {
  13242. console.trace(msg);
  13243. } else {
  13244. console.warn(msg);
  13245. }
  13246. warned = true;
  13247. }
  13248. return fn.apply(this, arguments);
  13249. }
  13250. return deprecated;
  13251. }
  13252. /**
  13253. * Checks `localStorage` for boolean values for the given `name`.
  13254. *
  13255. * @param {String} name
  13256. * @returns {Boolean}
  13257. * @api private
  13258. */
  13259. function config (name) {
  13260. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  13261. try {
  13262. if (!global.localStorage) return false;
  13263. } catch (_) {
  13264. return false;
  13265. }
  13266. var val = global.localStorage[name];
  13267. if (null == val) return false;
  13268. return String(val).toLowerCase() === 'true';
  13269. }
  13270. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13271. },{}],68:[function(require,module,exports){
  13272. arguments[4][25][0].apply(exports,arguments)
  13273. },{"dup":25}],69:[function(require,module,exports){
  13274. arguments[4][26][0].apply(exports,arguments)
  13275. },{"./support/isBuffer":68,"_process":51,"dup":26,"inherits":36}]},{},[20])(20)
  13276. });