browser.js 470 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096
  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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (Buffer){
  3. "use strict";
  4. let interlaceUtils = require("./interlace");
  5. let 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. let 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. let 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. let 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. let 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. let 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. let leftOver = [];
  95. let i = 0;
  96. function split() {
  97. if (i === data.length) {
  98. throw new Error("Ran out of data");
  99. }
  100. let byte = data[i];
  101. i++;
  102. let 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. let 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) {
  156. // eslint-disable-line max-params
  157. let imageWidth = image.width;
  158. let imageHeight = image.height;
  159. let imagePass = image.index;
  160. for (let y = 0; y < imageHeight; y++) {
  161. for (let x = 0; x < imageWidth; x++) {
  162. let pxPos = getPxPos(x, y, imagePass);
  163. pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
  164. rawPos += bpp; //eslint-disable-line no-param-reassign
  165. }
  166. }
  167. return rawPos;
  168. }
  169. function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {
  170. // eslint-disable-line max-params
  171. let imageWidth = image.width;
  172. let imageHeight = image.height;
  173. let imagePass = image.index;
  174. for (let y = 0; y < imageHeight; y++) {
  175. for (let x = 0; x < imageWidth; x++) {
  176. let pixelData = bits.get(bpp);
  177. let pxPos = getPxPos(x, y, imagePass);
  178. pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
  179. }
  180. bits.resetAfterLine();
  181. }
  182. }
  183. exports.dataToBitMap = function (data, bitmapInfo) {
  184. let width = bitmapInfo.width;
  185. let height = bitmapInfo.height;
  186. let depth = bitmapInfo.depth;
  187. let bpp = bitmapInfo.bpp;
  188. let interlace = bitmapInfo.interlace;
  189. let bits;
  190. if (depth !== 8) {
  191. bits = bitRetriever(data, depth);
  192. }
  193. let pxData;
  194. if (depth <= 8) {
  195. pxData = Buffer.alloc(width * height * 4);
  196. } else {
  197. pxData = new Uint16Array(width * height * 4);
  198. }
  199. let maxBit = Math.pow(2, depth) - 1;
  200. let rawPos = 0;
  201. let images;
  202. let getPxPos;
  203. if (interlace) {
  204. images = interlaceUtils.getImagePasses(width, height);
  205. getPxPos = interlaceUtils.getInterlaceIterator(width, height);
  206. } else {
  207. let nonInterlacedPxPos = 0;
  208. getPxPos = function () {
  209. let returner = nonInterlacedPxPos;
  210. nonInterlacedPxPos += 4;
  211. return returner;
  212. };
  213. images = [{ width: width, height: height }];
  214. }
  215. for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
  216. if (depth === 8) {
  217. rawPos = mapImage8Bit(
  218. images[imageIndex],
  219. pxData,
  220. getPxPos,
  221. bpp,
  222. data,
  223. rawPos
  224. );
  225. } else {
  226. mapImageCustomBit(
  227. images[imageIndex],
  228. pxData,
  229. getPxPos,
  230. bpp,
  231. bits,
  232. maxBit
  233. );
  234. }
  235. }
  236. if (depth === 8) {
  237. if (rawPos !== data.length) {
  238. throw new Error("extra data found");
  239. }
  240. } else {
  241. bits.end();
  242. }
  243. return pxData;
  244. };
  245. }).call(this,require("buffer").Buffer)
  246. },{"./interlace":11,"buffer":28}],2:[function(require,module,exports){
  247. (function (Buffer){
  248. "use strict";
  249. let constants = require("./constants");
  250. module.exports = function (dataIn, width, height, options) {
  251. let outHasAlpha =
  252. [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
  253. options.colorType
  254. ) !== -1;
  255. if (options.colorType === options.inputColorType) {
  256. let bigEndian = (function () {
  257. let buffer = new ArrayBuffer(2);
  258. new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
  259. // Int16Array uses the platform's endianness.
  260. return new Int16Array(buffer)[0] !== 256;
  261. })();
  262. // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
  263. if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
  264. return dataIn;
  265. }
  266. }
  267. // map to a UInt16 array if data is 16bit, fix endianness below
  268. let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
  269. let maxValue = 255;
  270. let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
  271. if (inBpp === 4 && !options.inputHasAlpha) {
  272. inBpp = 3;
  273. }
  274. let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
  275. if (options.bitDepth === 16) {
  276. maxValue = 65535;
  277. outBpp *= 2;
  278. }
  279. let outData = Buffer.alloc(width * height * outBpp);
  280. let inIndex = 0;
  281. let outIndex = 0;
  282. let bgColor = options.bgColor || {};
  283. if (bgColor.red === undefined) {
  284. bgColor.red = maxValue;
  285. }
  286. if (bgColor.green === undefined) {
  287. bgColor.green = maxValue;
  288. }
  289. if (bgColor.blue === undefined) {
  290. bgColor.blue = maxValue;
  291. }
  292. function getRGBA() {
  293. let red;
  294. let green;
  295. let blue;
  296. let alpha = maxValue;
  297. switch (options.inputColorType) {
  298. case constants.COLORTYPE_COLOR_ALPHA:
  299. alpha = data[inIndex + 3];
  300. red = data[inIndex];
  301. green = data[inIndex + 1];
  302. blue = data[inIndex + 2];
  303. break;
  304. case constants.COLORTYPE_COLOR:
  305. red = data[inIndex];
  306. green = data[inIndex + 1];
  307. blue = data[inIndex + 2];
  308. break;
  309. case constants.COLORTYPE_ALPHA:
  310. alpha = data[inIndex + 1];
  311. red = data[inIndex];
  312. green = red;
  313. blue = red;
  314. break;
  315. case constants.COLORTYPE_GRAYSCALE:
  316. red = data[inIndex];
  317. green = red;
  318. blue = red;
  319. break;
  320. default:
  321. throw new Error(
  322. "input color type:" +
  323. options.inputColorType +
  324. " is not supported at present"
  325. );
  326. }
  327. if (options.inputHasAlpha) {
  328. if (!outHasAlpha) {
  329. alpha /= maxValue;
  330. red = Math.min(
  331. Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),
  332. maxValue
  333. );
  334. green = Math.min(
  335. Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),
  336. maxValue
  337. );
  338. blue = Math.min(
  339. Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),
  340. maxValue
  341. );
  342. }
  343. }
  344. return { red: red, green: green, blue: blue, alpha: alpha };
  345. }
  346. for (let y = 0; y < height; y++) {
  347. for (let x = 0; x < width; x++) {
  348. let rgba = getRGBA(data, inIndex);
  349. switch (options.colorType) {
  350. case constants.COLORTYPE_COLOR_ALPHA:
  351. case constants.COLORTYPE_COLOR:
  352. if (options.bitDepth === 8) {
  353. outData[outIndex] = rgba.red;
  354. outData[outIndex + 1] = rgba.green;
  355. outData[outIndex + 2] = rgba.blue;
  356. if (outHasAlpha) {
  357. outData[outIndex + 3] = rgba.alpha;
  358. }
  359. } else {
  360. outData.writeUInt16BE(rgba.red, outIndex);
  361. outData.writeUInt16BE(rgba.green, outIndex + 2);
  362. outData.writeUInt16BE(rgba.blue, outIndex + 4);
  363. if (outHasAlpha) {
  364. outData.writeUInt16BE(rgba.alpha, outIndex + 6);
  365. }
  366. }
  367. break;
  368. case constants.COLORTYPE_ALPHA:
  369. case constants.COLORTYPE_GRAYSCALE: {
  370. // Convert to grayscale and alpha
  371. let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
  372. if (options.bitDepth === 8) {
  373. outData[outIndex] = grayscale;
  374. if (outHasAlpha) {
  375. outData[outIndex + 1] = rgba.alpha;
  376. }
  377. } else {
  378. outData.writeUInt16BE(grayscale, outIndex);
  379. if (outHasAlpha) {
  380. outData.writeUInt16BE(rgba.alpha, outIndex + 2);
  381. }
  382. }
  383. break;
  384. }
  385. default:
  386. throw new Error("unrecognised color Type " + options.colorType);
  387. }
  388. inIndex += inBpp;
  389. outIndex += outBpp;
  390. }
  391. }
  392. return outData;
  393. };
  394. }).call(this,require("buffer").Buffer)
  395. },{"./constants":4,"buffer":28}],3:[function(require,module,exports){
  396. (function (process,Buffer){
  397. "use strict";
  398. let util = require("util");
  399. let Stream = require("stream");
  400. let ChunkStream = (module.exports = function () {
  401. Stream.call(this);
  402. this._buffers = [];
  403. this._buffered = 0;
  404. this._reads = [];
  405. this._paused = false;
  406. this._encoding = "utf8";
  407. this.writable = true;
  408. });
  409. util.inherits(ChunkStream, Stream);
  410. ChunkStream.prototype.read = function (length, callback) {
  411. this._reads.push({
  412. length: Math.abs(length), // if length < 0 then at most this length
  413. allowLess: length < 0,
  414. func: callback,
  415. });
  416. process.nextTick(
  417. function () {
  418. this._process();
  419. // its paused and there is not enought data then ask for more
  420. if (this._paused && this._reads && this._reads.length > 0) {
  421. this._paused = false;
  422. this.emit("drain");
  423. }
  424. }.bind(this)
  425. );
  426. };
  427. ChunkStream.prototype.write = function (data, encoding) {
  428. if (!this.writable) {
  429. this.emit("error", new Error("Stream not writable"));
  430. return false;
  431. }
  432. let dataBuffer;
  433. if (Buffer.isBuffer(data)) {
  434. dataBuffer = data;
  435. } else {
  436. dataBuffer = Buffer.from(data, encoding || this._encoding);
  437. }
  438. this._buffers.push(dataBuffer);
  439. this._buffered += dataBuffer.length;
  440. this._process();
  441. // ok if there are no more read requests
  442. if (this._reads && this._reads.length === 0) {
  443. this._paused = true;
  444. }
  445. return this.writable && !this._paused;
  446. };
  447. ChunkStream.prototype.end = function (data, encoding) {
  448. if (data) {
  449. this.write(data, encoding);
  450. }
  451. this.writable = false;
  452. // already destroyed
  453. if (!this._buffers) {
  454. return;
  455. }
  456. // enqueue or handle end
  457. if (this._buffers.length === 0) {
  458. this._end();
  459. } else {
  460. this._buffers.push(null);
  461. this._process();
  462. }
  463. };
  464. ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
  465. ChunkStream.prototype._end = function () {
  466. if (this._reads.length > 0) {
  467. this.emit("error", new Error("Unexpected end of input"));
  468. }
  469. this.destroy();
  470. };
  471. ChunkStream.prototype.destroy = function () {
  472. if (!this._buffers) {
  473. return;
  474. }
  475. this.writable = false;
  476. this._reads = null;
  477. this._buffers = null;
  478. this.emit("close");
  479. };
  480. ChunkStream.prototype._processReadAllowingLess = function (read) {
  481. // ok there is any data so that we can satisfy this request
  482. this._reads.shift(); // == read
  483. // first we need to peek into first buffer
  484. let smallerBuf = this._buffers[0];
  485. // ok there is more data than we need
  486. if (smallerBuf.length > read.length) {
  487. this._buffered -= read.length;
  488. this._buffers[0] = smallerBuf.slice(read.length);
  489. read.func.call(this, smallerBuf.slice(0, read.length));
  490. } else {
  491. // ok this is less than maximum length so use it all
  492. this._buffered -= smallerBuf.length;
  493. this._buffers.shift(); // == smallerBuf
  494. read.func.call(this, smallerBuf);
  495. }
  496. };
  497. ChunkStream.prototype._processRead = function (read) {
  498. this._reads.shift(); // == read
  499. let pos = 0;
  500. let count = 0;
  501. let data = Buffer.alloc(read.length);
  502. // create buffer for all data
  503. while (pos < read.length) {
  504. let buf = this._buffers[count++];
  505. let len = Math.min(buf.length, read.length - pos);
  506. buf.copy(data, pos, 0, len);
  507. pos += len;
  508. // last buffer wasn't used all so just slice it and leave
  509. if (len !== buf.length) {
  510. this._buffers[--count] = buf.slice(len);
  511. }
  512. }
  513. // remove all used buffers
  514. if (count > 0) {
  515. this._buffers.splice(0, count);
  516. }
  517. this._buffered -= read.length;
  518. read.func.call(this, data);
  519. };
  520. ChunkStream.prototype._process = function () {
  521. try {
  522. // as long as there is any data and read requests
  523. while (this._buffered > 0 && this._reads && this._reads.length > 0) {
  524. let read = this._reads[0];
  525. // read any data (but no more than length)
  526. if (read.allowLess) {
  527. this._processReadAllowingLess(read);
  528. } else if (this._buffered >= read.length) {
  529. // ok we can meet some expectations
  530. this._processRead(read);
  531. } else {
  532. // not enought data to satisfy first request in queue
  533. // so we need to wait for more
  534. break;
  535. }
  536. }
  537. if (this._buffers && !this.writable) {
  538. this._end();
  539. }
  540. } catch (ex) {
  541. this.emit("error", ex);
  542. }
  543. };
  544. }).call(this,require('_process'),require("buffer").Buffer)
  545. },{"_process":47,"buffer":28,"stream":63,"util":67}],4:[function(require,module,exports){
  546. "use strict";
  547. module.exports = {
  548. PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
  549. TYPE_IHDR: 0x49484452,
  550. TYPE_IEND: 0x49454e44,
  551. TYPE_IDAT: 0x49444154,
  552. TYPE_PLTE: 0x504c5445,
  553. TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
  554. TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
  555. // color-type bits
  556. COLORTYPE_GRAYSCALE: 0,
  557. COLORTYPE_PALETTE: 1,
  558. COLORTYPE_COLOR: 2,
  559. COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
  560. // color-type combinations
  561. COLORTYPE_PALETTE_COLOR: 3,
  562. COLORTYPE_COLOR_ALPHA: 6,
  563. COLORTYPE_TO_BPP_MAP: {
  564. 0: 1,
  565. 2: 3,
  566. 3: 1,
  567. 4: 2,
  568. 6: 4,
  569. },
  570. GAMMA_DIVISION: 100000,
  571. };
  572. },{}],5:[function(require,module,exports){
  573. "use strict";
  574. let crcTable = [];
  575. (function () {
  576. for (let i = 0; i < 256; i++) {
  577. let currentCrc = i;
  578. for (let j = 0; j < 8; j++) {
  579. if (currentCrc & 1) {
  580. currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
  581. } else {
  582. currentCrc = currentCrc >>> 1;
  583. }
  584. }
  585. crcTable[i] = currentCrc;
  586. }
  587. })();
  588. let CrcCalculator = (module.exports = function () {
  589. this._crc = -1;
  590. });
  591. CrcCalculator.prototype.write = function (data) {
  592. for (let i = 0; i < data.length; i++) {
  593. this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
  594. }
  595. return true;
  596. };
  597. CrcCalculator.prototype.crc32 = function () {
  598. return this._crc ^ -1;
  599. };
  600. CrcCalculator.crc32 = function (buf) {
  601. let crc = -1;
  602. for (let i = 0; i < buf.length; i++) {
  603. crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
  604. }
  605. return crc ^ -1;
  606. };
  607. },{}],6:[function(require,module,exports){
  608. (function (Buffer){
  609. "use strict";
  610. let paethPredictor = require("./paeth-predictor");
  611. function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
  612. for (let x = 0; x < byteWidth; x++) {
  613. rawData[rawPos + x] = pxData[pxPos + x];
  614. }
  615. }
  616. function filterSumNone(pxData, pxPos, byteWidth) {
  617. let sum = 0;
  618. let length = pxPos + byteWidth;
  619. for (let i = pxPos; i < length; i++) {
  620. sum += Math.abs(pxData[i]);
  621. }
  622. return sum;
  623. }
  624. function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  625. for (let x = 0; x < byteWidth; x++) {
  626. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  627. let val = pxData[pxPos + x] - left;
  628. rawData[rawPos + x] = val;
  629. }
  630. }
  631. function filterSumSub(pxData, pxPos, byteWidth, bpp) {
  632. let sum = 0;
  633. for (let x = 0; x < byteWidth; x++) {
  634. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  635. let val = pxData[pxPos + x] - left;
  636. sum += Math.abs(val);
  637. }
  638. return sum;
  639. }
  640. function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
  641. for (let x = 0; x < byteWidth; x++) {
  642. let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  643. let val = pxData[pxPos + x] - up;
  644. rawData[rawPos + x] = val;
  645. }
  646. }
  647. function filterSumUp(pxData, pxPos, byteWidth) {
  648. let sum = 0;
  649. let length = pxPos + byteWidth;
  650. for (let x = pxPos; x < length; x++) {
  651. let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
  652. let val = pxData[x] - up;
  653. sum += Math.abs(val);
  654. }
  655. return sum;
  656. }
  657. function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  658. for (let x = 0; x < byteWidth; x++) {
  659. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  660. let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  661. let val = pxData[pxPos + x] - ((left + up) >> 1);
  662. rawData[rawPos + x] = val;
  663. }
  664. }
  665. function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
  666. let sum = 0;
  667. for (let x = 0; x < byteWidth; x++) {
  668. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  669. let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  670. let val = pxData[pxPos + x] - ((left + up) >> 1);
  671. sum += Math.abs(val);
  672. }
  673. return sum;
  674. }
  675. function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
  676. for (let x = 0; x < byteWidth; x++) {
  677. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  678. let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  679. let upleft =
  680. pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  681. let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  682. rawData[rawPos + x] = val;
  683. }
  684. }
  685. function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
  686. let sum = 0;
  687. for (let x = 0; x < byteWidth; x++) {
  688. let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
  689. let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
  690. let upleft =
  691. pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
  692. let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
  693. sum += Math.abs(val);
  694. }
  695. return sum;
  696. }
  697. let filters = {
  698. 0: filterNone,
  699. 1: filterSub,
  700. 2: filterUp,
  701. 3: filterAvg,
  702. 4: filterPaeth,
  703. };
  704. let filterSums = {
  705. 0: filterSumNone,
  706. 1: filterSumSub,
  707. 2: filterSumUp,
  708. 3: filterSumAvg,
  709. 4: filterSumPaeth,
  710. };
  711. module.exports = function (pxData, width, height, options, bpp) {
  712. let filterTypes;
  713. if (!("filterType" in options) || options.filterType === -1) {
  714. filterTypes = [0, 1, 2, 3, 4];
  715. } else if (typeof options.filterType === "number") {
  716. filterTypes = [options.filterType];
  717. } else {
  718. throw new Error("unrecognised filter types");
  719. }
  720. if (options.bitDepth === 16) {
  721. bpp *= 2;
  722. }
  723. let byteWidth = width * bpp;
  724. let rawPos = 0;
  725. let pxPos = 0;
  726. let rawData = Buffer.alloc((byteWidth + 1) * height);
  727. let sel = filterTypes[0];
  728. for (let y = 0; y < height; y++) {
  729. if (filterTypes.length > 1) {
  730. // find best filter for this line (with lowest sum of values)
  731. let min = Infinity;
  732. for (let i = 0; i < filterTypes.length; i++) {
  733. let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
  734. if (sum < min) {
  735. sel = filterTypes[i];
  736. min = sum;
  737. }
  738. }
  739. }
  740. rawData[rawPos] = sel;
  741. rawPos++;
  742. filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
  743. rawPos += byteWidth;
  744. pxPos += byteWidth;
  745. }
  746. return rawData;
  747. };
  748. }).call(this,require("buffer").Buffer)
  749. },{"./paeth-predictor":15,"buffer":28}],7:[function(require,module,exports){
  750. (function (Buffer){
  751. "use strict";
  752. let util = require("util");
  753. let ChunkStream = require("./chunkstream");
  754. let Filter = require("./filter-parse");
  755. let FilterAsync = (module.exports = function (bitmapInfo) {
  756. ChunkStream.call(this);
  757. let buffers = [];
  758. let that = this;
  759. this._filter = new Filter(bitmapInfo, {
  760. read: this.read.bind(this),
  761. write: function (buffer) {
  762. buffers.push(buffer);
  763. },
  764. complete: function () {
  765. that.emit("complete", Buffer.concat(buffers));
  766. },
  767. });
  768. this._filter.start();
  769. });
  770. util.inherits(FilterAsync, ChunkStream);
  771. }).call(this,require("buffer").Buffer)
  772. },{"./chunkstream":3,"./filter-parse":9,"buffer":28,"util":67}],8:[function(require,module,exports){
  773. (function (Buffer){
  774. "use strict";
  775. let SyncReader = require("./sync-reader");
  776. let Filter = require("./filter-parse");
  777. exports.process = function (inBuffer, bitmapInfo) {
  778. let outBuffers = [];
  779. let reader = new SyncReader(inBuffer);
  780. let filter = new Filter(bitmapInfo, {
  781. read: reader.read.bind(reader),
  782. write: function (bufferPart) {
  783. outBuffers.push(bufferPart);
  784. },
  785. complete: function () {},
  786. });
  787. filter.start();
  788. reader.process();
  789. return Buffer.concat(outBuffers);
  790. };
  791. }).call(this,require("buffer").Buffer)
  792. },{"./filter-parse":9,"./sync-reader":22,"buffer":28}],9:[function(require,module,exports){
  793. (function (Buffer){
  794. "use strict";
  795. let interlaceUtils = require("./interlace");
  796. let paethPredictor = require("./paeth-predictor");
  797. function getByteWidth(width, bpp, depth) {
  798. let byteWidth = width * bpp;
  799. if (depth !== 8) {
  800. byteWidth = Math.ceil(byteWidth / (8 / depth));
  801. }
  802. return byteWidth;
  803. }
  804. let Filter = (module.exports = function (bitmapInfo, dependencies) {
  805. let width = bitmapInfo.width;
  806. let height = bitmapInfo.height;
  807. let interlace = bitmapInfo.interlace;
  808. let bpp = bitmapInfo.bpp;
  809. let depth = bitmapInfo.depth;
  810. this.read = dependencies.read;
  811. this.write = dependencies.write;
  812. this.complete = dependencies.complete;
  813. this._imageIndex = 0;
  814. this._images = [];
  815. if (interlace) {
  816. let passes = interlaceUtils.getImagePasses(width, height);
  817. for (let i = 0; i < passes.length; i++) {
  818. this._images.push({
  819. byteWidth: getByteWidth(passes[i].width, bpp, depth),
  820. height: passes[i].height,
  821. lineIndex: 0,
  822. });
  823. }
  824. } else {
  825. this._images.push({
  826. byteWidth: getByteWidth(width, bpp, depth),
  827. height: height,
  828. lineIndex: 0,
  829. });
  830. }
  831. // when filtering the line we look at the pixel to the left
  832. // the spec also says it is done on a byte level regardless of the number of pixels
  833. // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
  834. // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
  835. if (depth === 8) {
  836. this._xComparison = bpp;
  837. } else if (depth === 16) {
  838. this._xComparison = bpp * 2;
  839. } else {
  840. this._xComparison = 1;
  841. }
  842. });
  843. Filter.prototype.start = function () {
  844. this.read(
  845. this._images[this._imageIndex].byteWidth + 1,
  846. this._reverseFilterLine.bind(this)
  847. );
  848. };
  849. Filter.prototype._unFilterType1 = function (
  850. rawData,
  851. unfilteredLine,
  852. byteWidth
  853. ) {
  854. let xComparison = this._xComparison;
  855. let xBiggerThan = xComparison - 1;
  856. for (let x = 0; x < byteWidth; x++) {
  857. let rawByte = rawData[1 + x];
  858. let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  859. unfilteredLine[x] = rawByte + f1Left;
  860. }
  861. };
  862. Filter.prototype._unFilterType2 = function (
  863. rawData,
  864. unfilteredLine,
  865. byteWidth
  866. ) {
  867. let lastLine = this._lastLine;
  868. for (let x = 0; x < byteWidth; x++) {
  869. let rawByte = rawData[1 + x];
  870. let f2Up = lastLine ? lastLine[x] : 0;
  871. unfilteredLine[x] = rawByte + f2Up;
  872. }
  873. };
  874. Filter.prototype._unFilterType3 = function (
  875. rawData,
  876. unfilteredLine,
  877. byteWidth
  878. ) {
  879. let xComparison = this._xComparison;
  880. let xBiggerThan = xComparison - 1;
  881. let lastLine = this._lastLine;
  882. for (let x = 0; x < byteWidth; x++) {
  883. let rawByte = rawData[1 + x];
  884. let f3Up = lastLine ? lastLine[x] : 0;
  885. let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  886. let f3Add = Math.floor((f3Left + f3Up) / 2);
  887. unfilteredLine[x] = rawByte + f3Add;
  888. }
  889. };
  890. Filter.prototype._unFilterType4 = function (
  891. rawData,
  892. unfilteredLine,
  893. byteWidth
  894. ) {
  895. let xComparison = this._xComparison;
  896. let xBiggerThan = xComparison - 1;
  897. let lastLine = this._lastLine;
  898. for (let x = 0; x < byteWidth; x++) {
  899. let rawByte = rawData[1 + x];
  900. let f4Up = lastLine ? lastLine[x] : 0;
  901. let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
  902. let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
  903. let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
  904. unfilteredLine[x] = rawByte + f4Add;
  905. }
  906. };
  907. Filter.prototype._reverseFilterLine = function (rawData) {
  908. let filter = rawData[0];
  909. let unfilteredLine;
  910. let currentImage = this._images[this._imageIndex];
  911. let byteWidth = currentImage.byteWidth;
  912. if (filter === 0) {
  913. unfilteredLine = rawData.slice(1, byteWidth + 1);
  914. } else {
  915. unfilteredLine = Buffer.alloc(byteWidth);
  916. switch (filter) {
  917. case 1:
  918. this._unFilterType1(rawData, unfilteredLine, byteWidth);
  919. break;
  920. case 2:
  921. this._unFilterType2(rawData, unfilteredLine, byteWidth);
  922. break;
  923. case 3:
  924. this._unFilterType3(rawData, unfilteredLine, byteWidth);
  925. break;
  926. case 4:
  927. this._unFilterType4(rawData, unfilteredLine, byteWidth);
  928. break;
  929. default:
  930. throw new Error("Unrecognised filter type - " + filter);
  931. }
  932. }
  933. this.write(unfilteredLine);
  934. currentImage.lineIndex++;
  935. if (currentImage.lineIndex >= currentImage.height) {
  936. this._lastLine = null;
  937. this._imageIndex++;
  938. currentImage = this._images[this._imageIndex];
  939. } else {
  940. this._lastLine = unfilteredLine;
  941. }
  942. if (currentImage) {
  943. // read, using the byte width that may be from the new current image
  944. this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
  945. } else {
  946. this._lastLine = null;
  947. this.complete();
  948. }
  949. };
  950. }).call(this,require("buffer").Buffer)
  951. },{"./interlace":11,"./paeth-predictor":15,"buffer":28}],10:[function(require,module,exports){
  952. (function (Buffer){
  953. "use strict";
  954. function dePalette(indata, outdata, width, height, palette) {
  955. let pxPos = 0;
  956. // use values from palette
  957. for (let y = 0; y < height; y++) {
  958. for (let x = 0; x < width; x++) {
  959. let color = palette[indata[pxPos]];
  960. if (!color) {
  961. throw new Error("index " + indata[pxPos] + " not in palette");
  962. }
  963. for (let i = 0; i < 4; i++) {
  964. outdata[pxPos + i] = color[i];
  965. }
  966. pxPos += 4;
  967. }
  968. }
  969. }
  970. function replaceTransparentColor(indata, outdata, width, height, transColor) {
  971. let pxPos = 0;
  972. for (let y = 0; y < height; y++) {
  973. for (let x = 0; x < width; x++) {
  974. let makeTrans = false;
  975. if (transColor.length === 1) {
  976. if (transColor[0] === indata[pxPos]) {
  977. makeTrans = true;
  978. }
  979. } else if (
  980. transColor[0] === indata[pxPos] &&
  981. transColor[1] === indata[pxPos + 1] &&
  982. transColor[2] === indata[pxPos + 2]
  983. ) {
  984. makeTrans = true;
  985. }
  986. if (makeTrans) {
  987. for (let i = 0; i < 4; i++) {
  988. outdata[pxPos + i] = 0;
  989. }
  990. }
  991. pxPos += 4;
  992. }
  993. }
  994. }
  995. function scaleDepth(indata, outdata, width, height, depth) {
  996. let maxOutSample = 255;
  997. let maxInSample = Math.pow(2, depth) - 1;
  998. let pxPos = 0;
  999. for (let y = 0; y < height; y++) {
  1000. for (let x = 0; x < width; x++) {
  1001. for (let i = 0; i < 4; i++) {
  1002. outdata[pxPos + i] = Math.floor(
  1003. (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5
  1004. );
  1005. }
  1006. pxPos += 4;
  1007. }
  1008. }
  1009. }
  1010. module.exports = function (indata, imageData) {
  1011. let depth = imageData.depth;
  1012. let width = imageData.width;
  1013. let height = imageData.height;
  1014. let colorType = imageData.colorType;
  1015. let transColor = imageData.transColor;
  1016. let palette = imageData.palette;
  1017. let outdata = indata; // only different for 16 bits
  1018. if (colorType === 3) {
  1019. // paletted
  1020. dePalette(indata, outdata, width, height, palette);
  1021. } else {
  1022. if (transColor) {
  1023. replaceTransparentColor(indata, outdata, width, height, transColor);
  1024. }
  1025. // if it needs scaling
  1026. if (depth !== 8) {
  1027. // if we need to change the buffer size
  1028. if (depth === 16) {
  1029. outdata = Buffer.alloc(width * height * 4);
  1030. }
  1031. scaleDepth(indata, outdata, width, height, depth);
  1032. }
  1033. }
  1034. return outdata;
  1035. };
  1036. }).call(this,require("buffer").Buffer)
  1037. },{"buffer":28}],11:[function(require,module,exports){
  1038. "use strict";
  1039. // Adam 7
  1040. // 0 1 2 3 4 5 6 7
  1041. // 0 x 6 4 6 x 6 4 6
  1042. // 1 7 7 7 7 7 7 7 7
  1043. // 2 5 6 5 6 5 6 5 6
  1044. // 3 7 7 7 7 7 7 7 7
  1045. // 4 3 6 4 6 3 6 4 6
  1046. // 5 7 7 7 7 7 7 7 7
  1047. // 6 5 6 5 6 5 6 5 6
  1048. // 7 7 7 7 7 7 7 7 7
  1049. let imagePasses = [
  1050. {
  1051. // pass 1 - 1px
  1052. x: [0],
  1053. y: [0],
  1054. },
  1055. {
  1056. // pass 2 - 1px
  1057. x: [4],
  1058. y: [0],
  1059. },
  1060. {
  1061. // pass 3 - 2px
  1062. x: [0, 4],
  1063. y: [4],
  1064. },
  1065. {
  1066. // pass 4 - 4px
  1067. x: [2, 6],
  1068. y: [0, 4],
  1069. },
  1070. {
  1071. // pass 5 - 8px
  1072. x: [0, 2, 4, 6],
  1073. y: [2, 6],
  1074. },
  1075. {
  1076. // pass 6 - 16px
  1077. x: [1, 3, 5, 7],
  1078. y: [0, 2, 4, 6],
  1079. },
  1080. {
  1081. // pass 7 - 32px
  1082. x: [0, 1, 2, 3, 4, 5, 6, 7],
  1083. y: [1, 3, 5, 7],
  1084. },
  1085. ];
  1086. exports.getImagePasses = function (width, height) {
  1087. let images = [];
  1088. let xLeftOver = width % 8;
  1089. let yLeftOver = height % 8;
  1090. let xRepeats = (width - xLeftOver) / 8;
  1091. let yRepeats = (height - yLeftOver) / 8;
  1092. for (let i = 0; i < imagePasses.length; i++) {
  1093. let pass = imagePasses[i];
  1094. let passWidth = xRepeats * pass.x.length;
  1095. let passHeight = yRepeats * pass.y.length;
  1096. for (let j = 0; j < pass.x.length; j++) {
  1097. if (pass.x[j] < xLeftOver) {
  1098. passWidth++;
  1099. } else {
  1100. break;
  1101. }
  1102. }
  1103. for (let j = 0; j < pass.y.length; j++) {
  1104. if (pass.y[j] < yLeftOver) {
  1105. passHeight++;
  1106. } else {
  1107. break;
  1108. }
  1109. }
  1110. if (passWidth > 0 && passHeight > 0) {
  1111. images.push({ width: passWidth, height: passHeight, index: i });
  1112. }
  1113. }
  1114. return images;
  1115. };
  1116. exports.getInterlaceIterator = function (width) {
  1117. return function (x, y, pass) {
  1118. let outerXLeftOver = x % imagePasses[pass].x.length;
  1119. let outerX =
  1120. ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 +
  1121. imagePasses[pass].x[outerXLeftOver];
  1122. let outerYLeftOver = y % imagePasses[pass].y.length;
  1123. let outerY =
  1124. ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 +
  1125. imagePasses[pass].y[outerYLeftOver];
  1126. return outerX * 4 + outerY * width * 4;
  1127. };
  1128. };
  1129. },{}],12:[function(require,module,exports){
  1130. (function (Buffer){
  1131. "use strict";
  1132. let util = require("util");
  1133. let Stream = require("stream");
  1134. let constants = require("./constants");
  1135. let Packer = require("./packer");
  1136. let PackerAsync = (module.exports = function (opt) {
  1137. Stream.call(this);
  1138. let options = opt || {};
  1139. this._packer = new Packer(options);
  1140. this._deflate = this._packer.createDeflate();
  1141. this.readable = true;
  1142. });
  1143. util.inherits(PackerAsync, Stream);
  1144. PackerAsync.prototype.pack = function (data, width, height, gamma) {
  1145. // Signature
  1146. this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
  1147. this.emit("data", this._packer.packIHDR(width, height));
  1148. if (gamma) {
  1149. this.emit("data", this._packer.packGAMA(gamma));
  1150. }
  1151. let filteredData = this._packer.filterData(data, width, height);
  1152. // compress it
  1153. this._deflate.on("error", this.emit.bind(this, "error"));
  1154. this._deflate.on(
  1155. "data",
  1156. function (compressedData) {
  1157. this.emit("data", this._packer.packIDAT(compressedData));
  1158. }.bind(this)
  1159. );
  1160. this._deflate.on(
  1161. "end",
  1162. function () {
  1163. this.emit("data", this._packer.packIEND());
  1164. this.emit("end");
  1165. }.bind(this)
  1166. );
  1167. this._deflate.end(filteredData);
  1168. };
  1169. }).call(this,require("buffer").Buffer)
  1170. },{"./constants":4,"./packer":14,"buffer":28,"stream":63,"util":67}],13:[function(require,module,exports){
  1171. (function (Buffer){
  1172. "use strict";
  1173. let hasSyncZlib = true;
  1174. let zlib = require("zlib");
  1175. if (!zlib.deflateSync) {
  1176. hasSyncZlib = false;
  1177. }
  1178. let constants = require("./constants");
  1179. let Packer = require("./packer");
  1180. module.exports = function (metaData, opt) {
  1181. if (!hasSyncZlib) {
  1182. throw new Error(
  1183. "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
  1184. );
  1185. }
  1186. let options = opt || {};
  1187. let packer = new Packer(options);
  1188. let chunks = [];
  1189. // Signature
  1190. chunks.push(Buffer.from(constants.PNG_SIGNATURE));
  1191. // Header
  1192. chunks.push(packer.packIHDR(metaData.width, metaData.height));
  1193. if (metaData.gamma) {
  1194. chunks.push(packer.packGAMA(metaData.gamma));
  1195. }
  1196. let filteredData = packer.filterData(
  1197. metaData.data,
  1198. metaData.width,
  1199. metaData.height
  1200. );
  1201. // compress it
  1202. let compressedData = zlib.deflateSync(
  1203. filteredData,
  1204. packer.getDeflateOptions()
  1205. );
  1206. filteredData = null;
  1207. if (!compressedData || !compressedData.length) {
  1208. throw new Error("bad png - invalid compressed data response");
  1209. }
  1210. chunks.push(packer.packIDAT(compressedData));
  1211. // End
  1212. chunks.push(packer.packIEND());
  1213. return Buffer.concat(chunks);
  1214. };
  1215. }).call(this,require("buffer").Buffer)
  1216. },{"./constants":4,"./packer":14,"buffer":28,"zlib":27}],14:[function(require,module,exports){
  1217. (function (Buffer){
  1218. "use strict";
  1219. let constants = require("./constants");
  1220. let CrcStream = require("./crc");
  1221. let bitPacker = require("./bitpacker");
  1222. let filter = require("./filter-pack");
  1223. let zlib = require("zlib");
  1224. let Packer = (module.exports = function (options) {
  1225. this._options = options;
  1226. options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
  1227. options.deflateLevel =
  1228. options.deflateLevel != null ? options.deflateLevel : 9;
  1229. options.deflateStrategy =
  1230. options.deflateStrategy != null ? options.deflateStrategy : 3;
  1231. options.inputHasAlpha =
  1232. options.inputHasAlpha != null ? options.inputHasAlpha : true;
  1233. options.deflateFactory = options.deflateFactory || zlib.createDeflate;
  1234. options.bitDepth = options.bitDepth || 8;
  1235. // This is outputColorType
  1236. options.colorType =
  1237. typeof options.colorType === "number"
  1238. ? options.colorType
  1239. : constants.COLORTYPE_COLOR_ALPHA;
  1240. options.inputColorType =
  1241. typeof options.inputColorType === "number"
  1242. ? options.inputColorType
  1243. : constants.COLORTYPE_COLOR_ALPHA;
  1244. if (
  1245. [
  1246. constants.COLORTYPE_GRAYSCALE,
  1247. constants.COLORTYPE_COLOR,
  1248. constants.COLORTYPE_COLOR_ALPHA,
  1249. constants.COLORTYPE_ALPHA,
  1250. ].indexOf(options.colorType) === -1
  1251. ) {
  1252. throw new Error(
  1253. "option color type:" + options.colorType + " is not supported at present"
  1254. );
  1255. }
  1256. if (
  1257. [
  1258. constants.COLORTYPE_GRAYSCALE,
  1259. constants.COLORTYPE_COLOR,
  1260. constants.COLORTYPE_COLOR_ALPHA,
  1261. constants.COLORTYPE_ALPHA,
  1262. ].indexOf(options.inputColorType) === -1
  1263. ) {
  1264. throw new Error(
  1265. "option input color type:" +
  1266. options.inputColorType +
  1267. " is not supported at present"
  1268. );
  1269. }
  1270. if (options.bitDepth !== 8 && options.bitDepth !== 16) {
  1271. throw new Error(
  1272. "option bit depth:" + options.bitDepth + " is not supported at present"
  1273. );
  1274. }
  1275. });
  1276. Packer.prototype.getDeflateOptions = function () {
  1277. return {
  1278. chunkSize: this._options.deflateChunkSize,
  1279. level: this._options.deflateLevel,
  1280. strategy: this._options.deflateStrategy,
  1281. };
  1282. };
  1283. Packer.prototype.createDeflate = function () {
  1284. return this._options.deflateFactory(this.getDeflateOptions());
  1285. };
  1286. Packer.prototype.filterData = function (data, width, height) {
  1287. // convert to correct format for filtering (e.g. right bpp and bit depth)
  1288. let packedData = bitPacker(data, width, height, this._options);
  1289. // filter pixel data
  1290. let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
  1291. let filteredData = filter(packedData, width, height, this._options, bpp);
  1292. return filteredData;
  1293. };
  1294. Packer.prototype._packChunk = function (type, data) {
  1295. let len = data ? data.length : 0;
  1296. let buf = Buffer.alloc(len + 12);
  1297. buf.writeUInt32BE(len, 0);
  1298. buf.writeUInt32BE(type, 4);
  1299. if (data) {
  1300. data.copy(buf, 8);
  1301. }
  1302. buf.writeInt32BE(
  1303. CrcStream.crc32(buf.slice(4, buf.length - 4)),
  1304. buf.length - 4
  1305. );
  1306. return buf;
  1307. };
  1308. Packer.prototype.packGAMA = function (gamma) {
  1309. let buf = Buffer.alloc(4);
  1310. buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
  1311. return this._packChunk(constants.TYPE_gAMA, buf);
  1312. };
  1313. Packer.prototype.packIHDR = function (width, height) {
  1314. let buf = Buffer.alloc(13);
  1315. buf.writeUInt32BE(width, 0);
  1316. buf.writeUInt32BE(height, 4);
  1317. buf[8] = this._options.bitDepth; // Bit depth
  1318. buf[9] = this._options.colorType; // colorType
  1319. buf[10] = 0; // compression
  1320. buf[11] = 0; // filter
  1321. buf[12] = 0; // interlace
  1322. return this._packChunk(constants.TYPE_IHDR, buf);
  1323. };
  1324. Packer.prototype.packIDAT = function (data) {
  1325. return this._packChunk(constants.TYPE_IDAT, data);
  1326. };
  1327. Packer.prototype.packIEND = function () {
  1328. return this._packChunk(constants.TYPE_IEND, null);
  1329. };
  1330. }).call(this,require("buffer").Buffer)
  1331. },{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":28,"zlib":27}],15:[function(require,module,exports){
  1332. "use strict";
  1333. module.exports = function paethPredictor(left, above, upLeft) {
  1334. let paeth = left + above - upLeft;
  1335. let pLeft = Math.abs(paeth - left);
  1336. let pAbove = Math.abs(paeth - above);
  1337. let pUpLeft = Math.abs(paeth - upLeft);
  1338. if (pLeft <= pAbove && pLeft <= pUpLeft) {
  1339. return left;
  1340. }
  1341. if (pAbove <= pUpLeft) {
  1342. return above;
  1343. }
  1344. return upLeft;
  1345. };
  1346. },{}],16:[function(require,module,exports){
  1347. "use strict";
  1348. let util = require("util");
  1349. let zlib = require("zlib");
  1350. let ChunkStream = require("./chunkstream");
  1351. let FilterAsync = require("./filter-parse-async");
  1352. let Parser = require("./parser");
  1353. let bitmapper = require("./bitmapper");
  1354. let formatNormaliser = require("./format-normaliser");
  1355. let ParserAsync = (module.exports = function (options) {
  1356. ChunkStream.call(this);
  1357. this._parser = new Parser(options, {
  1358. read: this.read.bind(this),
  1359. error: this._handleError.bind(this),
  1360. metadata: this._handleMetaData.bind(this),
  1361. gamma: this.emit.bind(this, "gamma"),
  1362. palette: this._handlePalette.bind(this),
  1363. transColor: this._handleTransColor.bind(this),
  1364. finished: this._finished.bind(this),
  1365. inflateData: this._inflateData.bind(this),
  1366. simpleTransparency: this._simpleTransparency.bind(this),
  1367. headersFinished: this._headersFinished.bind(this),
  1368. });
  1369. this._options = options;
  1370. this.writable = true;
  1371. this._parser.start();
  1372. });
  1373. util.inherits(ParserAsync, ChunkStream);
  1374. ParserAsync.prototype._handleError = function (err) {
  1375. this.emit("error", err);
  1376. this.writable = false;
  1377. this.destroy();
  1378. if (this._inflate && this._inflate.destroy) {
  1379. this._inflate.destroy();
  1380. }
  1381. if (this._filter) {
  1382. this._filter.destroy();
  1383. // For backward compatibility with Node 7 and below.
  1384. // Suppress errors due to _inflate calling write() even after
  1385. // it's destroy()'ed.
  1386. this._filter.on("error", function () {});
  1387. }
  1388. this.errord = true;
  1389. };
  1390. ParserAsync.prototype._inflateData = function (data) {
  1391. if (!this._inflate) {
  1392. if (this._bitmapInfo.interlace) {
  1393. this._inflate = zlib.createInflate();
  1394. this._inflate.on("error", this.emit.bind(this, "error"));
  1395. this._filter.on("complete", this._complete.bind(this));
  1396. this._inflate.pipe(this._filter);
  1397. } else {
  1398. let rowSize =
  1399. ((this._bitmapInfo.width *
  1400. this._bitmapInfo.bpp *
  1401. this._bitmapInfo.depth +
  1402. 7) >>
  1403. 3) +
  1404. 1;
  1405. let imageSize = rowSize * this._bitmapInfo.height;
  1406. let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
  1407. this._inflate = zlib.createInflate({ chunkSize: chunkSize });
  1408. let leftToInflate = imageSize;
  1409. let emitError = this.emit.bind(this, "error");
  1410. this._inflate.on("error", function (err) {
  1411. if (!leftToInflate) {
  1412. return;
  1413. }
  1414. emitError(err);
  1415. });
  1416. this._filter.on("complete", this._complete.bind(this));
  1417. let filterWrite = this._filter.write.bind(this._filter);
  1418. this._inflate.on("data", function (chunk) {
  1419. if (!leftToInflate) {
  1420. return;
  1421. }
  1422. if (chunk.length > leftToInflate) {
  1423. chunk = chunk.slice(0, leftToInflate);
  1424. }
  1425. leftToInflate -= chunk.length;
  1426. filterWrite(chunk);
  1427. });
  1428. this._inflate.on("end", this._filter.end.bind(this._filter));
  1429. }
  1430. }
  1431. this._inflate.write(data);
  1432. };
  1433. ParserAsync.prototype._handleMetaData = function (metaData) {
  1434. this._metaData = metaData;
  1435. this._bitmapInfo = Object.create(metaData);
  1436. this._filter = new FilterAsync(this._bitmapInfo);
  1437. };
  1438. ParserAsync.prototype._handleTransColor = function (transColor) {
  1439. this._bitmapInfo.transColor = transColor;
  1440. };
  1441. ParserAsync.prototype._handlePalette = function (palette) {
  1442. this._bitmapInfo.palette = palette;
  1443. };
  1444. ParserAsync.prototype._simpleTransparency = function () {
  1445. this._metaData.alpha = true;
  1446. };
  1447. ParserAsync.prototype._headersFinished = function () {
  1448. // Up until this point, we don't know if we have a tRNS chunk (alpha)
  1449. // so we can't emit metadata any earlier
  1450. this.emit("metadata", this._metaData);
  1451. };
  1452. ParserAsync.prototype._finished = function () {
  1453. if (this.errord) {
  1454. return;
  1455. }
  1456. if (!this._inflate) {
  1457. this.emit("error", "No Inflate block");
  1458. } else {
  1459. // no more data to inflate
  1460. this._inflate.end();
  1461. }
  1462. };
  1463. ParserAsync.prototype._complete = function (filteredData) {
  1464. if (this.errord) {
  1465. return;
  1466. }
  1467. let normalisedBitmapData;
  1468. try {
  1469. let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
  1470. normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
  1471. bitmapData = null;
  1472. } catch (ex) {
  1473. this._handleError(ex);
  1474. return;
  1475. }
  1476. this.emit("parsed", normalisedBitmapData);
  1477. };
  1478. },{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":67,"zlib":27}],17:[function(require,module,exports){
  1479. (function (Buffer){
  1480. "use strict";
  1481. let hasSyncZlib = true;
  1482. let zlib = require("zlib");
  1483. let inflateSync = require("./sync-inflate");
  1484. if (!zlib.deflateSync) {
  1485. hasSyncZlib = false;
  1486. }
  1487. let SyncReader = require("./sync-reader");
  1488. let FilterSync = require("./filter-parse-sync");
  1489. let Parser = require("./parser");
  1490. let bitmapper = require("./bitmapper");
  1491. let formatNormaliser = require("./format-normaliser");
  1492. module.exports = function (buffer, options) {
  1493. if (!hasSyncZlib) {
  1494. throw new Error(
  1495. "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
  1496. );
  1497. }
  1498. let err;
  1499. function handleError(_err_) {
  1500. err = _err_;
  1501. }
  1502. let metaData;
  1503. function handleMetaData(_metaData_) {
  1504. metaData = _metaData_;
  1505. }
  1506. function handleTransColor(transColor) {
  1507. metaData.transColor = transColor;
  1508. }
  1509. function handlePalette(palette) {
  1510. metaData.palette = palette;
  1511. }
  1512. function handleSimpleTransparency() {
  1513. metaData.alpha = true;
  1514. }
  1515. let gamma;
  1516. function handleGamma(_gamma_) {
  1517. gamma = _gamma_;
  1518. }
  1519. let inflateDataList = [];
  1520. function handleInflateData(inflatedData) {
  1521. inflateDataList.push(inflatedData);
  1522. }
  1523. let reader = new SyncReader(buffer);
  1524. let parser = new Parser(options, {
  1525. read: reader.read.bind(reader),
  1526. error: handleError,
  1527. metadata: handleMetaData,
  1528. gamma: handleGamma,
  1529. palette: handlePalette,
  1530. transColor: handleTransColor,
  1531. inflateData: handleInflateData,
  1532. simpleTransparency: handleSimpleTransparency,
  1533. });
  1534. parser.start();
  1535. reader.process();
  1536. if (err) {
  1537. throw err;
  1538. }
  1539. //join together the inflate datas
  1540. let inflateData = Buffer.concat(inflateDataList);
  1541. inflateDataList.length = 0;
  1542. let inflatedData;
  1543. if (metaData.interlace) {
  1544. inflatedData = zlib.inflateSync(inflateData);
  1545. } else {
  1546. let rowSize =
  1547. ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
  1548. let imageSize = rowSize * metaData.height;
  1549. inflatedData = inflateSync(inflateData, {
  1550. chunkSize: imageSize,
  1551. maxLength: imageSize,
  1552. });
  1553. }
  1554. inflateData = null;
  1555. if (!inflatedData || !inflatedData.length) {
  1556. throw new Error("bad png - invalid inflate data response");
  1557. }
  1558. let unfilteredData = FilterSync.process(inflatedData, metaData);
  1559. inflateData = null;
  1560. let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
  1561. unfilteredData = null;
  1562. let normalisedBitmapData = formatNormaliser(bitmapData, metaData);
  1563. metaData.data = normalisedBitmapData;
  1564. metaData.gamma = gamma || 0;
  1565. return metaData;
  1566. };
  1567. }).call(this,require("buffer").Buffer)
  1568. },{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":28,"zlib":27}],18:[function(require,module,exports){
  1569. (function (Buffer){
  1570. "use strict";
  1571. let constants = require("./constants");
  1572. let CrcCalculator = require("./crc");
  1573. let Parser = (module.exports = function (options, dependencies) {
  1574. this._options = options;
  1575. options.checkCRC = options.checkCRC !== false;
  1576. this._hasIHDR = false;
  1577. this._hasIEND = false;
  1578. this._emittedHeadersFinished = false;
  1579. // input flags/metadata
  1580. this._palette = [];
  1581. this._colorType = 0;
  1582. this._chunks = {};
  1583. this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
  1584. this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
  1585. this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
  1586. this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
  1587. this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
  1588. this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
  1589. this.read = dependencies.read;
  1590. this.error = dependencies.error;
  1591. this.metadata = dependencies.metadata;
  1592. this.gamma = dependencies.gamma;
  1593. this.transColor = dependencies.transColor;
  1594. this.palette = dependencies.palette;
  1595. this.parsed = dependencies.parsed;
  1596. this.inflateData = dependencies.inflateData;
  1597. this.finished = dependencies.finished;
  1598. this.simpleTransparency = dependencies.simpleTransparency;
  1599. this.headersFinished = dependencies.headersFinished || function () {};
  1600. });
  1601. Parser.prototype.start = function () {
  1602. this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
  1603. };
  1604. Parser.prototype._parseSignature = function (data) {
  1605. let signature = constants.PNG_SIGNATURE;
  1606. for (let i = 0; i < signature.length; i++) {
  1607. if (data[i] !== signature[i]) {
  1608. this.error(new Error("Invalid file signature"));
  1609. return;
  1610. }
  1611. }
  1612. this.read(8, this._parseChunkBegin.bind(this));
  1613. };
  1614. Parser.prototype._parseChunkBegin = function (data) {
  1615. // chunk content length
  1616. let length = data.readUInt32BE(0);
  1617. // chunk type
  1618. let type = data.readUInt32BE(4);
  1619. let name = "";
  1620. for (let i = 4; i < 8; i++) {
  1621. name += String.fromCharCode(data[i]);
  1622. }
  1623. //console.log('chunk ', name, length);
  1624. // chunk flags
  1625. let ancillary = Boolean(data[4] & 0x20); // or critical
  1626. // priv = Boolean(data[5] & 0x20), // or public
  1627. // safeToCopy = Boolean(data[7] & 0x20); // or unsafe
  1628. if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
  1629. this.error(new Error("Expected IHDR on beggining"));
  1630. return;
  1631. }
  1632. this._crc = new CrcCalculator();
  1633. this._crc.write(Buffer.from(name));
  1634. if (this._chunks[type]) {
  1635. return this._chunks[type](length);
  1636. }
  1637. if (!ancillary) {
  1638. this.error(new Error("Unsupported critical chunk type " + name));
  1639. return;
  1640. }
  1641. this.read(length + 4, this._skipChunk.bind(this));
  1642. };
  1643. Parser.prototype._skipChunk = function (/*data*/) {
  1644. this.read(8, this._parseChunkBegin.bind(this));
  1645. };
  1646. Parser.prototype._handleChunkEnd = function () {
  1647. this.read(4, this._parseChunkEnd.bind(this));
  1648. };
  1649. Parser.prototype._parseChunkEnd = function (data) {
  1650. let fileCrc = data.readInt32BE(0);
  1651. let calcCrc = this._crc.crc32();
  1652. // check CRC
  1653. if (this._options.checkCRC && calcCrc !== fileCrc) {
  1654. this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
  1655. return;
  1656. }
  1657. if (!this._hasIEND) {
  1658. this.read(8, this._parseChunkBegin.bind(this));
  1659. }
  1660. };
  1661. Parser.prototype._handleIHDR = function (length) {
  1662. this.read(length, this._parseIHDR.bind(this));
  1663. };
  1664. Parser.prototype._parseIHDR = function (data) {
  1665. this._crc.write(data);
  1666. let width = data.readUInt32BE(0);
  1667. let height = data.readUInt32BE(4);
  1668. let depth = data[8];
  1669. let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
  1670. let compr = data[10];
  1671. let filter = data[11];
  1672. let interlace = data[12];
  1673. // console.log(' width', width, 'height', height,
  1674. // 'depth', depth, 'colorType', colorType,
  1675. // 'compr', compr, 'filter', filter, 'interlace', interlace
  1676. // );
  1677. if (
  1678. depth !== 8 &&
  1679. depth !== 4 &&
  1680. depth !== 2 &&
  1681. depth !== 1 &&
  1682. depth !== 16
  1683. ) {
  1684. this.error(new Error("Unsupported bit depth " + depth));
  1685. return;
  1686. }
  1687. if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
  1688. this.error(new Error("Unsupported color type"));
  1689. return;
  1690. }
  1691. if (compr !== 0) {
  1692. this.error(new Error("Unsupported compression method"));
  1693. return;
  1694. }
  1695. if (filter !== 0) {
  1696. this.error(new Error("Unsupported filter method"));
  1697. return;
  1698. }
  1699. if (interlace !== 0 && interlace !== 1) {
  1700. this.error(new Error("Unsupported interlace method"));
  1701. return;
  1702. }
  1703. this._colorType = colorType;
  1704. let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
  1705. this._hasIHDR = true;
  1706. this.metadata({
  1707. width: width,
  1708. height: height,
  1709. depth: depth,
  1710. interlace: Boolean(interlace),
  1711. palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
  1712. color: Boolean(colorType & constants.COLORTYPE_COLOR),
  1713. alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
  1714. bpp: bpp,
  1715. colorType: colorType,
  1716. });
  1717. this._handleChunkEnd();
  1718. };
  1719. Parser.prototype._handlePLTE = function (length) {
  1720. this.read(length, this._parsePLTE.bind(this));
  1721. };
  1722. Parser.prototype._parsePLTE = function (data) {
  1723. this._crc.write(data);
  1724. let entries = Math.floor(data.length / 3);
  1725. // console.log('Palette:', entries);
  1726. for (let i = 0; i < entries; i++) {
  1727. this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]);
  1728. }
  1729. this.palette(this._palette);
  1730. this._handleChunkEnd();
  1731. };
  1732. Parser.prototype._handleTRNS = function (length) {
  1733. this.simpleTransparency();
  1734. this.read(length, this._parseTRNS.bind(this));
  1735. };
  1736. Parser.prototype._parseTRNS = function (data) {
  1737. this._crc.write(data);
  1738. // palette
  1739. if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
  1740. if (this._palette.length === 0) {
  1741. this.error(new Error("Transparency chunk must be after palette"));
  1742. return;
  1743. }
  1744. if (data.length > this._palette.length) {
  1745. this.error(new Error("More transparent colors than palette size"));
  1746. return;
  1747. }
  1748. for (let i = 0; i < data.length; i++) {
  1749. this._palette[i][3] = data[i];
  1750. }
  1751. this.palette(this._palette);
  1752. }
  1753. // for colorType 0 (grayscale) and 2 (rgb)
  1754. // there might be one gray/color defined as transparent
  1755. if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
  1756. // grey, 2 bytes
  1757. this.transColor([data.readUInt16BE(0)]);
  1758. }
  1759. if (this._colorType === constants.COLORTYPE_COLOR) {
  1760. this.transColor([
  1761. data.readUInt16BE(0),
  1762. data.readUInt16BE(2),
  1763. data.readUInt16BE(4),
  1764. ]);
  1765. }
  1766. this._handleChunkEnd();
  1767. };
  1768. Parser.prototype._handleGAMA = function (length) {
  1769. this.read(length, this._parseGAMA.bind(this));
  1770. };
  1771. Parser.prototype._parseGAMA = function (data) {
  1772. this._crc.write(data);
  1773. this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
  1774. this._handleChunkEnd();
  1775. };
  1776. Parser.prototype._handleIDAT = function (length) {
  1777. if (!this._emittedHeadersFinished) {
  1778. this._emittedHeadersFinished = true;
  1779. this.headersFinished();
  1780. }
  1781. this.read(-length, this._parseIDAT.bind(this, length));
  1782. };
  1783. Parser.prototype._parseIDAT = function (length, data) {
  1784. this._crc.write(data);
  1785. if (
  1786. this._colorType === constants.COLORTYPE_PALETTE_COLOR &&
  1787. this._palette.length === 0
  1788. ) {
  1789. throw new Error("Expected palette not found");
  1790. }
  1791. this.inflateData(data);
  1792. let leftOverLength = length - data.length;
  1793. if (leftOverLength > 0) {
  1794. this._handleIDAT(leftOverLength);
  1795. } else {
  1796. this._handleChunkEnd();
  1797. }
  1798. };
  1799. Parser.prototype._handleIEND = function (length) {
  1800. this.read(length, this._parseIEND.bind(this));
  1801. };
  1802. Parser.prototype._parseIEND = function (data) {
  1803. this._crc.write(data);
  1804. this._hasIEND = true;
  1805. this._handleChunkEnd();
  1806. if (this.finished) {
  1807. this.finished();
  1808. }
  1809. };
  1810. }).call(this,require("buffer").Buffer)
  1811. },{"./constants":4,"./crc":5,"buffer":28}],19:[function(require,module,exports){
  1812. "use strict";
  1813. let parse = require("./parser-sync");
  1814. let pack = require("./packer-sync");
  1815. exports.read = function (buffer, options) {
  1816. return parse(buffer, options || {});
  1817. };
  1818. exports.write = function (png, options) {
  1819. return pack(png, options);
  1820. };
  1821. },{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){
  1822. (function (process,Buffer){
  1823. "use strict";
  1824. let util = require("util");
  1825. let Stream = require("stream");
  1826. let Parser = require("./parser-async");
  1827. let Packer = require("./packer-async");
  1828. let PNGSync = require("./png-sync");
  1829. let PNG = (exports.PNG = function (options) {
  1830. Stream.call(this);
  1831. options = options || {}; // eslint-disable-line no-param-reassign
  1832. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  1833. this.width = options.width | 0;
  1834. this.height = options.height | 0;
  1835. this.data =
  1836. this.width > 0 && this.height > 0
  1837. ? Buffer.alloc(4 * this.width * this.height)
  1838. : null;
  1839. if (options.fill && this.data) {
  1840. this.data.fill(0);
  1841. }
  1842. this.gamma = 0;
  1843. this.readable = this.writable = true;
  1844. this._parser = new Parser(options);
  1845. this._parser.on("error", this.emit.bind(this, "error"));
  1846. this._parser.on("close", this._handleClose.bind(this));
  1847. this._parser.on("metadata", this._metadata.bind(this));
  1848. this._parser.on("gamma", this._gamma.bind(this));
  1849. this._parser.on(
  1850. "parsed",
  1851. function (data) {
  1852. this.data = data;
  1853. this.emit("parsed", data);
  1854. }.bind(this)
  1855. );
  1856. this._packer = new Packer(options);
  1857. this._packer.on("data", this.emit.bind(this, "data"));
  1858. this._packer.on("end", this.emit.bind(this, "end"));
  1859. this._parser.on("close", this._handleClose.bind(this));
  1860. this._packer.on("error", this.emit.bind(this, "error"));
  1861. });
  1862. util.inherits(PNG, Stream);
  1863. PNG.sync = PNGSync;
  1864. PNG.prototype.pack = function () {
  1865. if (!this.data || !this.data.length) {
  1866. this.emit("error", "No data provided");
  1867. return this;
  1868. }
  1869. process.nextTick(
  1870. function () {
  1871. this._packer.pack(this.data, this.width, this.height, this.gamma);
  1872. }.bind(this)
  1873. );
  1874. return this;
  1875. };
  1876. PNG.prototype.parse = function (data, callback) {
  1877. if (callback) {
  1878. let onParsed, onError;
  1879. onParsed = function (parsedData) {
  1880. this.removeListener("error", onError);
  1881. this.data = parsedData;
  1882. callback(null, this);
  1883. }.bind(this);
  1884. onError = function (err) {
  1885. this.removeListener("parsed", onParsed);
  1886. callback(err, null);
  1887. }.bind(this);
  1888. this.once("parsed", onParsed);
  1889. this.once("error", onError);
  1890. }
  1891. this.end(data);
  1892. return this;
  1893. };
  1894. PNG.prototype.write = function (data) {
  1895. this._parser.write(data);
  1896. return true;
  1897. };
  1898. PNG.prototype.end = function (data) {
  1899. this._parser.end(data);
  1900. };
  1901. PNG.prototype._metadata = function (metadata) {
  1902. this.width = metadata.width;
  1903. this.height = metadata.height;
  1904. this.emit("metadata", metadata);
  1905. };
  1906. PNG.prototype._gamma = function (gamma) {
  1907. this.gamma = gamma;
  1908. };
  1909. PNG.prototype._handleClose = function () {
  1910. if (!this._parser.writable && !this._packer.readable) {
  1911. this.emit("close");
  1912. }
  1913. };
  1914. PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) {
  1915. // eslint-disable-line max-params
  1916. // coerce pixel dimensions to integers (also coerces undefined -> 0):
  1917. /* eslint-disable no-param-reassign */
  1918. srcX |= 0;
  1919. srcY |= 0;
  1920. width |= 0;
  1921. height |= 0;
  1922. deltaX |= 0;
  1923. deltaY |= 0;
  1924. /* eslint-enable no-param-reassign */
  1925. if (
  1926. srcX > src.width ||
  1927. srcY > src.height ||
  1928. srcX + width > src.width ||
  1929. srcY + height > src.height
  1930. ) {
  1931. throw new Error("bitblt reading outside image");
  1932. }
  1933. if (
  1934. deltaX > dst.width ||
  1935. deltaY > dst.height ||
  1936. deltaX + width > dst.width ||
  1937. deltaY + height > dst.height
  1938. ) {
  1939. throw new Error("bitblt writing outside image");
  1940. }
  1941. for (let y = 0; y < height; y++) {
  1942. src.data.copy(
  1943. dst.data,
  1944. ((deltaY + y) * dst.width + deltaX) << 2,
  1945. ((srcY + y) * src.width + srcX) << 2,
  1946. ((srcY + y) * src.width + srcX + width) << 2
  1947. );
  1948. }
  1949. };
  1950. PNG.prototype.bitblt = function (
  1951. dst,
  1952. srcX,
  1953. srcY,
  1954. width,
  1955. height,
  1956. deltaX,
  1957. deltaY
  1958. ) {
  1959. // eslint-disable-line max-params
  1960. PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
  1961. return this;
  1962. };
  1963. PNG.adjustGamma = function (src) {
  1964. if (src.gamma) {
  1965. for (let y = 0; y < src.height; y++) {
  1966. for (let x = 0; x < src.width; x++) {
  1967. let idx = (src.width * y + x) << 2;
  1968. for (let i = 0; i < 3; i++) {
  1969. let sample = src.data[idx + i] / 255;
  1970. sample = Math.pow(sample, 1 / 2.2 / src.gamma);
  1971. src.data[idx + i] = Math.round(sample * 255);
  1972. }
  1973. }
  1974. }
  1975. src.gamma = 0;
  1976. }
  1977. };
  1978. PNG.prototype.adjustGamma = function () {
  1979. PNG.adjustGamma(this);
  1980. };
  1981. }).call(this,require('_process'),require("buffer").Buffer)
  1982. },{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":47,"buffer":28,"stream":63,"util":67}],21:[function(require,module,exports){
  1983. (function (process,Buffer){
  1984. "use strict";
  1985. let assert = require("assert").ok;
  1986. let zlib = require("zlib");
  1987. let util = require("util");
  1988. let kMaxLength = require("buffer").kMaxLength;
  1989. function Inflate(opts) {
  1990. if (!(this instanceof Inflate)) {
  1991. return new Inflate(opts);
  1992. }
  1993. if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
  1994. opts.chunkSize = zlib.Z_MIN_CHUNK;
  1995. }
  1996. zlib.Inflate.call(this, opts);
  1997. // Node 8 --> 9 compatibility check
  1998. this._offset = this._offset === undefined ? this._outOffset : this._offset;
  1999. this._buffer = this._buffer || this._outBuffer;
  2000. if (opts && opts.maxLength != null) {
  2001. this._maxLength = opts.maxLength;
  2002. }
  2003. }
  2004. function createInflate(opts) {
  2005. return new Inflate(opts);
  2006. }
  2007. function _close(engine, callback) {
  2008. if (callback) {
  2009. process.nextTick(callback);
  2010. }
  2011. // Caller may invoke .close after a zlib error (which will null _handle).
  2012. if (!engine._handle) {
  2013. return;
  2014. }
  2015. engine._handle.close();
  2016. engine._handle = null;
  2017. }
  2018. Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) {
  2019. if (typeof asyncCb === "function") {
  2020. return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
  2021. }
  2022. let self = this;
  2023. let availInBefore = chunk && chunk.length;
  2024. let availOutBefore = this._chunkSize - this._offset;
  2025. let leftToInflate = this._maxLength;
  2026. let inOff = 0;
  2027. let buffers = [];
  2028. let nread = 0;
  2029. let error;
  2030. this.on("error", function (err) {
  2031. error = err;
  2032. });
  2033. function handleChunk(availInAfter, availOutAfter) {
  2034. if (self._hadError) {
  2035. return;
  2036. }
  2037. let have = availOutBefore - availOutAfter;
  2038. assert(have >= 0, "have should not go down");
  2039. if (have > 0) {
  2040. let out = self._buffer.slice(self._offset, self._offset + have);
  2041. self._offset += have;
  2042. if (out.length > leftToInflate) {
  2043. out = out.slice(0, leftToInflate);
  2044. }
  2045. buffers.push(out);
  2046. nread += out.length;
  2047. leftToInflate -= out.length;
  2048. if (leftToInflate === 0) {
  2049. return false;
  2050. }
  2051. }
  2052. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  2053. availOutBefore = self._chunkSize;
  2054. self._offset = 0;
  2055. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  2056. }
  2057. if (availOutAfter === 0) {
  2058. inOff += availInBefore - availInAfter;
  2059. availInBefore = availInAfter;
  2060. return true;
  2061. }
  2062. return false;
  2063. }
  2064. assert(this._handle, "zlib binding closed");
  2065. let res;
  2066. do {
  2067. res = this._handle.writeSync(
  2068. flushFlag,
  2069. chunk, // in
  2070. inOff, // in_off
  2071. availInBefore, // in_len
  2072. this._buffer, // out
  2073. this._offset, //out_off
  2074. availOutBefore
  2075. ); // out_len
  2076. // Node 8 --> 9 compatibility check
  2077. res = res || this._writeState;
  2078. } while (!this._hadError && handleChunk(res[0], res[1]));
  2079. if (this._hadError) {
  2080. throw error;
  2081. }
  2082. if (nread >= kMaxLength) {
  2083. _close(this);
  2084. throw new RangeError(
  2085. "Cannot create final Buffer. It would be larger than 0x" +
  2086. kMaxLength.toString(16) +
  2087. " bytes"
  2088. );
  2089. }
  2090. let buf = Buffer.concat(buffers, nread);
  2091. _close(this);
  2092. return buf;
  2093. };
  2094. util.inherits(Inflate, zlib.Inflate);
  2095. function zlibBufferSync(engine, buffer) {
  2096. if (typeof buffer === "string") {
  2097. buffer = Buffer.from(buffer);
  2098. }
  2099. if (!(buffer instanceof Buffer)) {
  2100. throw new TypeError("Not a string or buffer");
  2101. }
  2102. let flushFlag = engine._finishFlushFlag;
  2103. if (flushFlag == null) {
  2104. flushFlag = zlib.Z_FINISH;
  2105. }
  2106. return engine._processChunk(buffer, flushFlag);
  2107. }
  2108. function inflateSync(buffer, opts) {
  2109. return zlibBufferSync(new Inflate(opts), buffer);
  2110. }
  2111. module.exports = exports = inflateSync;
  2112. exports.Inflate = Inflate;
  2113. exports.createInflate = createInflate;
  2114. exports.inflateSync = inflateSync;
  2115. }).call(this,require('_process'),require("buffer").Buffer)
  2116. },{"_process":47,"assert":23,"buffer":28,"util":67,"zlib":27}],22:[function(require,module,exports){
  2117. "use strict";
  2118. let SyncReader = (module.exports = function (buffer) {
  2119. this._buffer = buffer;
  2120. this._reads = [];
  2121. });
  2122. SyncReader.prototype.read = function (length, callback) {
  2123. this._reads.push({
  2124. length: Math.abs(length), // if length < 0 then at most this length
  2125. allowLess: length < 0,
  2126. func: callback,
  2127. });
  2128. };
  2129. SyncReader.prototype.process = function () {
  2130. // as long as there is any data and read requests
  2131. while (this._reads.length > 0 && this._buffer.length) {
  2132. let read = this._reads[0];
  2133. if (
  2134. this._buffer.length &&
  2135. (this._buffer.length >= read.length || read.allowLess)
  2136. ) {
  2137. // ok there is any data so that we can satisfy this request
  2138. this._reads.shift(); // == read
  2139. let buf = this._buffer;
  2140. this._buffer = buf.slice(read.length);
  2141. read.func.call(this, buf.slice(0, read.length));
  2142. } else {
  2143. break;
  2144. }
  2145. }
  2146. if (this._reads.length > 0) {
  2147. return new Error("There are some read requests waitng on finished stream");
  2148. }
  2149. if (this._buffer.length > 0) {
  2150. return new Error("unrecognised content at end of stream");
  2151. }
  2152. };
  2153. },{}],23:[function(require,module,exports){
  2154. (function (global){
  2155. 'use strict';
  2156. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  2157. // original notice:
  2158. /*!
  2159. * The buffer module from node.js, for the browser.
  2160. *
  2161. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2162. * @license MIT
  2163. */
  2164. function compare(a, b) {
  2165. if (a === b) {
  2166. return 0;
  2167. }
  2168. var x = a.length;
  2169. var y = b.length;
  2170. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2171. if (a[i] !== b[i]) {
  2172. x = a[i];
  2173. y = b[i];
  2174. break;
  2175. }
  2176. }
  2177. if (x < y) {
  2178. return -1;
  2179. }
  2180. if (y < x) {
  2181. return 1;
  2182. }
  2183. return 0;
  2184. }
  2185. function isBuffer(b) {
  2186. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  2187. return global.Buffer.isBuffer(b);
  2188. }
  2189. return !!(b != null && b._isBuffer);
  2190. }
  2191. // based on node assert, original notice:
  2192. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  2193. //
  2194. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  2195. //
  2196. // Originally from narwhal.js (http://narwhaljs.org)
  2197. // Copyright (c) 2009 Thomas Robinson <280north.com>
  2198. //
  2199. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2200. // of this software and associated documentation files (the 'Software'), to
  2201. // deal in the Software without restriction, including without limitation the
  2202. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  2203. // sell copies of the Software, and to permit persons to whom the Software is
  2204. // furnished to do so, subject to the following conditions:
  2205. //
  2206. // The above copyright notice and this permission notice shall be included in
  2207. // all copies or substantial portions of the Software.
  2208. //
  2209. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2210. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2211. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2212. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  2213. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  2214. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2215. var util = require('util/');
  2216. var hasOwn = Object.prototype.hasOwnProperty;
  2217. var pSlice = Array.prototype.slice;
  2218. var functionsHaveNames = (function () {
  2219. return function foo() {}.name === 'foo';
  2220. }());
  2221. function pToString (obj) {
  2222. return Object.prototype.toString.call(obj);
  2223. }
  2224. function isView(arrbuf) {
  2225. if (isBuffer(arrbuf)) {
  2226. return false;
  2227. }
  2228. if (typeof global.ArrayBuffer !== 'function') {
  2229. return false;
  2230. }
  2231. if (typeof ArrayBuffer.isView === 'function') {
  2232. return ArrayBuffer.isView(arrbuf);
  2233. }
  2234. if (!arrbuf) {
  2235. return false;
  2236. }
  2237. if (arrbuf instanceof DataView) {
  2238. return true;
  2239. }
  2240. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  2241. return true;
  2242. }
  2243. return false;
  2244. }
  2245. // 1. The assert module provides functions that throw
  2246. // AssertionError's when particular conditions are not met. The
  2247. // assert module must conform to the following interface.
  2248. var assert = module.exports = ok;
  2249. // 2. The AssertionError is defined in assert.
  2250. // new assert.AssertionError({ message: message,
  2251. // actual: actual,
  2252. // expected: expected })
  2253. var regex = /\s*function\s+([^\(\s]*)\s*/;
  2254. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  2255. function getName(func) {
  2256. if (!util.isFunction(func)) {
  2257. return;
  2258. }
  2259. if (functionsHaveNames) {
  2260. return func.name;
  2261. }
  2262. var str = func.toString();
  2263. var match = str.match(regex);
  2264. return match && match[1];
  2265. }
  2266. assert.AssertionError = function AssertionError(options) {
  2267. this.name = 'AssertionError';
  2268. this.actual = options.actual;
  2269. this.expected = options.expected;
  2270. this.operator = options.operator;
  2271. if (options.message) {
  2272. this.message = options.message;
  2273. this.generatedMessage = false;
  2274. } else {
  2275. this.message = getMessage(this);
  2276. this.generatedMessage = true;
  2277. }
  2278. var stackStartFunction = options.stackStartFunction || fail;
  2279. if (Error.captureStackTrace) {
  2280. Error.captureStackTrace(this, stackStartFunction);
  2281. } else {
  2282. // non v8 browsers so we can have a stacktrace
  2283. var err = new Error();
  2284. if (err.stack) {
  2285. var out = err.stack;
  2286. // try to strip useless frames
  2287. var fn_name = getName(stackStartFunction);
  2288. var idx = out.indexOf('\n' + fn_name);
  2289. if (idx >= 0) {
  2290. // once we have located the function frame
  2291. // we need to strip out everything before it (and its line)
  2292. var next_line = out.indexOf('\n', idx + 1);
  2293. out = out.substring(next_line + 1);
  2294. }
  2295. this.stack = out;
  2296. }
  2297. }
  2298. };
  2299. // assert.AssertionError instanceof Error
  2300. util.inherits(assert.AssertionError, Error);
  2301. function truncate(s, n) {
  2302. if (typeof s === 'string') {
  2303. return s.length < n ? s : s.slice(0, n);
  2304. } else {
  2305. return s;
  2306. }
  2307. }
  2308. function inspect(something) {
  2309. if (functionsHaveNames || !util.isFunction(something)) {
  2310. return util.inspect(something);
  2311. }
  2312. var rawname = getName(something);
  2313. var name = rawname ? ': ' + rawname : '';
  2314. return '[Function' + name + ']';
  2315. }
  2316. function getMessage(self) {
  2317. return truncate(inspect(self.actual), 128) + ' ' +
  2318. self.operator + ' ' +
  2319. truncate(inspect(self.expected), 128);
  2320. }
  2321. // At present only the three keys mentioned above are used and
  2322. // understood by the spec. Implementations or sub modules can pass
  2323. // other keys to the AssertionError's constructor - they will be
  2324. // ignored.
  2325. // 3. All of the following functions must throw an AssertionError
  2326. // when a corresponding condition is not met, with a message that
  2327. // may be undefined if not provided. All assertion methods provide
  2328. // both the actual and expected values to the assertion error for
  2329. // display purposes.
  2330. function fail(actual, expected, message, operator, stackStartFunction) {
  2331. throw new assert.AssertionError({
  2332. message: message,
  2333. actual: actual,
  2334. expected: expected,
  2335. operator: operator,
  2336. stackStartFunction: stackStartFunction
  2337. });
  2338. }
  2339. // EXTENSION! allows for well behaved errors defined elsewhere.
  2340. assert.fail = fail;
  2341. // 4. Pure assertion tests whether a value is truthy, as determined
  2342. // by !!guard.
  2343. // assert.ok(guard, message_opt);
  2344. // This statement is equivalent to assert.equal(true, !!guard,
  2345. // message_opt);. To test strictly for the value true, use
  2346. // assert.strictEqual(true, guard, message_opt);.
  2347. function ok(value, message) {
  2348. if (!value) fail(value, true, message, '==', assert.ok);
  2349. }
  2350. assert.ok = ok;
  2351. // 5. The equality assertion tests shallow, coercive equality with
  2352. // ==.
  2353. // assert.equal(actual, expected, message_opt);
  2354. assert.equal = function equal(actual, expected, message) {
  2355. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  2356. };
  2357. // 6. The non-equality assertion tests for whether two objects are not equal
  2358. // with != assert.notEqual(actual, expected, message_opt);
  2359. assert.notEqual = function notEqual(actual, expected, message) {
  2360. if (actual == expected) {
  2361. fail(actual, expected, message, '!=', assert.notEqual);
  2362. }
  2363. };
  2364. // 7. The equivalence assertion tests a deep equality relation.
  2365. // assert.deepEqual(actual, expected, message_opt);
  2366. assert.deepEqual = function deepEqual(actual, expected, message) {
  2367. if (!_deepEqual(actual, expected, false)) {
  2368. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  2369. }
  2370. };
  2371. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  2372. if (!_deepEqual(actual, expected, true)) {
  2373. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  2374. }
  2375. };
  2376. function _deepEqual(actual, expected, strict, memos) {
  2377. // 7.1. All identical values are equivalent, as determined by ===.
  2378. if (actual === expected) {
  2379. return true;
  2380. } else if (isBuffer(actual) && isBuffer(expected)) {
  2381. return compare(actual, expected) === 0;
  2382. // 7.2. If the expected value is a Date object, the actual value is
  2383. // equivalent if it is also a Date object that refers to the same time.
  2384. } else if (util.isDate(actual) && util.isDate(expected)) {
  2385. return actual.getTime() === expected.getTime();
  2386. // 7.3 If the expected value is a RegExp object, the actual value is
  2387. // equivalent if it is also a RegExp object with the same source and
  2388. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  2389. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  2390. return actual.source === expected.source &&
  2391. actual.global === expected.global &&
  2392. actual.multiline === expected.multiline &&
  2393. actual.lastIndex === expected.lastIndex &&
  2394. actual.ignoreCase === expected.ignoreCase;
  2395. // 7.4. Other pairs that do not both pass typeof value == 'object',
  2396. // equivalence is determined by ==.
  2397. } else if ((actual === null || typeof actual !== 'object') &&
  2398. (expected === null || typeof expected !== 'object')) {
  2399. return strict ? actual === expected : actual == expected;
  2400. // If both values are instances of typed arrays, wrap their underlying
  2401. // ArrayBuffers in a Buffer each to increase performance
  2402. // This optimization requires the arrays to have the same type as checked by
  2403. // Object.prototype.toString (aka pToString). Never perform binary
  2404. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  2405. // bit patterns are not identical.
  2406. } else if (isView(actual) && isView(expected) &&
  2407. pToString(actual) === pToString(expected) &&
  2408. !(actual instanceof Float32Array ||
  2409. actual instanceof Float64Array)) {
  2410. return compare(new Uint8Array(actual.buffer),
  2411. new Uint8Array(expected.buffer)) === 0;
  2412. // 7.5 For all other Object pairs, including Array objects, equivalence is
  2413. // determined by having the same number of owned properties (as verified
  2414. // with Object.prototype.hasOwnProperty.call), the same set of keys
  2415. // (although not necessarily the same order), equivalent values for every
  2416. // corresponding key, and an identical 'prototype' property. Note: this
  2417. // accounts for both named and indexed properties on Arrays.
  2418. } else if (isBuffer(actual) !== isBuffer(expected)) {
  2419. return false;
  2420. } else {
  2421. memos = memos || {actual: [], expected: []};
  2422. var actualIndex = memos.actual.indexOf(actual);
  2423. if (actualIndex !== -1) {
  2424. if (actualIndex === memos.expected.indexOf(expected)) {
  2425. return true;
  2426. }
  2427. }
  2428. memos.actual.push(actual);
  2429. memos.expected.push(expected);
  2430. return objEquiv(actual, expected, strict, memos);
  2431. }
  2432. }
  2433. function isArguments(object) {
  2434. return Object.prototype.toString.call(object) == '[object Arguments]';
  2435. }
  2436. function objEquiv(a, b, strict, actualVisitedObjects) {
  2437. if (a === null || a === undefined || b === null || b === undefined)
  2438. return false;
  2439. // if one is a primitive, the other must be same
  2440. if (util.isPrimitive(a) || util.isPrimitive(b))
  2441. return a === b;
  2442. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  2443. return false;
  2444. var aIsArgs = isArguments(a);
  2445. var bIsArgs = isArguments(b);
  2446. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  2447. return false;
  2448. if (aIsArgs) {
  2449. a = pSlice.call(a);
  2450. b = pSlice.call(b);
  2451. return _deepEqual(a, b, strict);
  2452. }
  2453. var ka = objectKeys(a);
  2454. var kb = objectKeys(b);
  2455. var key, i;
  2456. // having the same number of owned properties (keys incorporates
  2457. // hasOwnProperty)
  2458. if (ka.length !== kb.length)
  2459. return false;
  2460. //the same set of keys (although not necessarily the same order),
  2461. ka.sort();
  2462. kb.sort();
  2463. //~~~cheap key test
  2464. for (i = ka.length - 1; i >= 0; i--) {
  2465. if (ka[i] !== kb[i])
  2466. return false;
  2467. }
  2468. //equivalent values for every corresponding key, and
  2469. //~~~possibly expensive deep test
  2470. for (i = ka.length - 1; i >= 0; i--) {
  2471. key = ka[i];
  2472. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  2473. return false;
  2474. }
  2475. return true;
  2476. }
  2477. // 8. The non-equivalence assertion tests for any deep inequality.
  2478. // assert.notDeepEqual(actual, expected, message_opt);
  2479. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  2480. if (_deepEqual(actual, expected, false)) {
  2481. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  2482. }
  2483. };
  2484. assert.notDeepStrictEqual = notDeepStrictEqual;
  2485. function notDeepStrictEqual(actual, expected, message) {
  2486. if (_deepEqual(actual, expected, true)) {
  2487. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  2488. }
  2489. }
  2490. // 9. The strict equality assertion tests strict equality, as determined by ===.
  2491. // assert.strictEqual(actual, expected, message_opt);
  2492. assert.strictEqual = function strictEqual(actual, expected, message) {
  2493. if (actual !== expected) {
  2494. fail(actual, expected, message, '===', assert.strictEqual);
  2495. }
  2496. };
  2497. // 10. The strict non-equality assertion tests for strict inequality, as
  2498. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  2499. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  2500. if (actual === expected) {
  2501. fail(actual, expected, message, '!==', assert.notStrictEqual);
  2502. }
  2503. };
  2504. function expectedException(actual, expected) {
  2505. if (!actual || !expected) {
  2506. return false;
  2507. }
  2508. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  2509. return expected.test(actual);
  2510. }
  2511. try {
  2512. if (actual instanceof expected) {
  2513. return true;
  2514. }
  2515. } catch (e) {
  2516. // Ignore. The instanceof check doesn't work for arrow functions.
  2517. }
  2518. if (Error.isPrototypeOf(expected)) {
  2519. return false;
  2520. }
  2521. return expected.call({}, actual) === true;
  2522. }
  2523. function _tryBlock(block) {
  2524. var error;
  2525. try {
  2526. block();
  2527. } catch (e) {
  2528. error = e;
  2529. }
  2530. return error;
  2531. }
  2532. function _throws(shouldThrow, block, expected, message) {
  2533. var actual;
  2534. if (typeof block !== 'function') {
  2535. throw new TypeError('"block" argument must be a function');
  2536. }
  2537. if (typeof expected === 'string') {
  2538. message = expected;
  2539. expected = null;
  2540. }
  2541. actual = _tryBlock(block);
  2542. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  2543. (message ? ' ' + message : '.');
  2544. if (shouldThrow && !actual) {
  2545. fail(actual, expected, 'Missing expected exception' + message);
  2546. }
  2547. var userProvidedMessage = typeof message === 'string';
  2548. var isUnwantedException = !shouldThrow && util.isError(actual);
  2549. var isUnexpectedException = !shouldThrow && actual && !expected;
  2550. if ((isUnwantedException &&
  2551. userProvidedMessage &&
  2552. expectedException(actual, expected)) ||
  2553. isUnexpectedException) {
  2554. fail(actual, expected, 'Got unwanted exception' + message);
  2555. }
  2556. if ((shouldThrow && actual && expected &&
  2557. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  2558. throw actual;
  2559. }
  2560. }
  2561. // 11. Expected to throw an error:
  2562. // assert.throws(block, Error_opt, message_opt);
  2563. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  2564. _throws(true, block, error, message);
  2565. };
  2566. // EXTENSION! This is annoying to write outside this module.
  2567. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  2568. _throws(false, block, error, message);
  2569. };
  2570. assert.ifError = function(err) { if (err) throw err; };
  2571. var objectKeys = Object.keys || function (obj) {
  2572. var keys = [];
  2573. for (var key in obj) {
  2574. if (hasOwn.call(obj, key)) keys.push(key);
  2575. }
  2576. return keys;
  2577. };
  2578. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2579. },{"util/":67}],24:[function(require,module,exports){
  2580. 'use strict'
  2581. exports.byteLength = byteLength
  2582. exports.toByteArray = toByteArray
  2583. exports.fromByteArray = fromByteArray
  2584. var lookup = []
  2585. var revLookup = []
  2586. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2587. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2588. for (var i = 0, len = code.length; i < len; ++i) {
  2589. lookup[i] = code[i]
  2590. revLookup[code.charCodeAt(i)] = i
  2591. }
  2592. revLookup['-'.charCodeAt(0)] = 62
  2593. revLookup['_'.charCodeAt(0)] = 63
  2594. function placeHoldersCount (b64) {
  2595. var len = b64.length
  2596. if (len % 4 > 0) {
  2597. throw new Error('Invalid string. Length must be a multiple of 4')
  2598. }
  2599. // the number of equal signs (place holders)
  2600. // if there are two placeholders, than the two characters before it
  2601. // represent one byte
  2602. // if there is only one, then the three characters before it represent 2 bytes
  2603. // this is just a cheap hack to not do indexOf twice
  2604. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  2605. }
  2606. function byteLength (b64) {
  2607. // base64 is 4/3 + up to two characters of the original data
  2608. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  2609. }
  2610. function toByteArray (b64) {
  2611. var i, l, tmp, placeHolders, arr
  2612. var len = b64.length
  2613. placeHolders = placeHoldersCount(b64)
  2614. arr = new Arr((len * 3 / 4) - placeHolders)
  2615. // if there are placeholders, only get up to the last complete 4 chars
  2616. l = placeHolders > 0 ? len - 4 : len
  2617. var L = 0
  2618. for (i = 0; i < l; i += 4) {
  2619. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  2620. arr[L++] = (tmp >> 16) & 0xFF
  2621. arr[L++] = (tmp >> 8) & 0xFF
  2622. arr[L++] = tmp & 0xFF
  2623. }
  2624. if (placeHolders === 2) {
  2625. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2626. arr[L++] = tmp & 0xFF
  2627. } else if (placeHolders === 1) {
  2628. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2629. arr[L++] = (tmp >> 8) & 0xFF
  2630. arr[L++] = tmp & 0xFF
  2631. }
  2632. return arr
  2633. }
  2634. function tripletToBase64 (num) {
  2635. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  2636. }
  2637. function encodeChunk (uint8, start, end) {
  2638. var tmp
  2639. var output = []
  2640. for (var i = start; i < end; i += 3) {
  2641. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  2642. output.push(tripletToBase64(tmp))
  2643. }
  2644. return output.join('')
  2645. }
  2646. function fromByteArray (uint8) {
  2647. var tmp
  2648. var len = uint8.length
  2649. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2650. var output = ''
  2651. var parts = []
  2652. var maxChunkLength = 16383 // must be multiple of 3
  2653. // go through the array every three bytes, we'll deal with trailing stuff later
  2654. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2655. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  2656. }
  2657. // pad the end with zeros, but make sure to not forget the extra bytes
  2658. if (extraBytes === 1) {
  2659. tmp = uint8[len - 1]
  2660. output += lookup[tmp >> 2]
  2661. output += lookup[(tmp << 4) & 0x3F]
  2662. output += '=='
  2663. } else if (extraBytes === 2) {
  2664. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  2665. output += lookup[tmp >> 10]
  2666. output += lookup[(tmp >> 4) & 0x3F]
  2667. output += lookup[(tmp << 2) & 0x3F]
  2668. output += '='
  2669. }
  2670. parts.push(output)
  2671. return parts.join('')
  2672. }
  2673. },{}],25:[function(require,module,exports){
  2674. },{}],26:[function(require,module,exports){
  2675. (function (process,Buffer){
  2676. 'use strict';
  2677. /* eslint camelcase: "off" */
  2678. var assert = require('assert');
  2679. var Zstream = require('pako/lib/zlib/zstream');
  2680. var zlib_deflate = require('pako/lib/zlib/deflate.js');
  2681. var zlib_inflate = require('pako/lib/zlib/inflate.js');
  2682. var constants = require('pako/lib/zlib/constants');
  2683. for (var key in constants) {
  2684. exports[key] = constants[key];
  2685. }
  2686. // zlib modes
  2687. exports.NONE = 0;
  2688. exports.DEFLATE = 1;
  2689. exports.INFLATE = 2;
  2690. exports.GZIP = 3;
  2691. exports.GUNZIP = 4;
  2692. exports.DEFLATERAW = 5;
  2693. exports.INFLATERAW = 6;
  2694. exports.UNZIP = 7;
  2695. var GZIP_HEADER_ID1 = 0x1f;
  2696. var GZIP_HEADER_ID2 = 0x8b;
  2697. /**
  2698. * Emulate Node's zlib C++ layer for use by the JS layer in index.js
  2699. */
  2700. function Zlib(mode) {
  2701. if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
  2702. throw new TypeError('Bad argument');
  2703. }
  2704. this.dictionary = null;
  2705. this.err = 0;
  2706. this.flush = 0;
  2707. this.init_done = false;
  2708. this.level = 0;
  2709. this.memLevel = 0;
  2710. this.mode = mode;
  2711. this.strategy = 0;
  2712. this.windowBits = 0;
  2713. this.write_in_progress = false;
  2714. this.pending_close = false;
  2715. this.gzip_id_bytes_read = 0;
  2716. }
  2717. Zlib.prototype.close = function () {
  2718. if (this.write_in_progress) {
  2719. this.pending_close = true;
  2720. return;
  2721. }
  2722. this.pending_close = false;
  2723. assert(this.init_done, 'close before init');
  2724. assert(this.mode <= exports.UNZIP);
  2725. if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
  2726. zlib_deflate.deflateEnd(this.strm);
  2727. } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
  2728. zlib_inflate.inflateEnd(this.strm);
  2729. }
  2730. this.mode = exports.NONE;
  2731. this.dictionary = null;
  2732. };
  2733. Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  2734. return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
  2735. };
  2736. Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  2737. return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
  2738. };
  2739. Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  2740. assert.equal(arguments.length, 8);
  2741. assert(this.init_done, 'write before init');
  2742. assert(this.mode !== exports.NONE, 'already finalized');
  2743. assert.equal(false, this.write_in_progress, 'write already in progress');
  2744. assert.equal(false, this.pending_close, 'close is pending');
  2745. this.write_in_progress = true;
  2746. assert.equal(false, flush === undefined, 'must provide flush value');
  2747. this.write_in_progress = true;
  2748. 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) {
  2749. throw new Error('Invalid flush value');
  2750. }
  2751. if (input == null) {
  2752. input = Buffer.alloc(0);
  2753. in_len = 0;
  2754. in_off = 0;
  2755. }
  2756. this.strm.avail_in = in_len;
  2757. this.strm.input = input;
  2758. this.strm.next_in = in_off;
  2759. this.strm.avail_out = out_len;
  2760. this.strm.output = out;
  2761. this.strm.next_out = out_off;
  2762. this.flush = flush;
  2763. if (!async) {
  2764. // sync version
  2765. this._process();
  2766. if (this._checkError()) {
  2767. return this._afterSync();
  2768. }
  2769. return;
  2770. }
  2771. // async version
  2772. var self = this;
  2773. process.nextTick(function () {
  2774. self._process();
  2775. self._after();
  2776. });
  2777. return this;
  2778. };
  2779. Zlib.prototype._afterSync = function () {
  2780. var avail_out = this.strm.avail_out;
  2781. var avail_in = this.strm.avail_in;
  2782. this.write_in_progress = false;
  2783. return [avail_in, avail_out];
  2784. };
  2785. Zlib.prototype._process = function () {
  2786. var next_expected_header_byte = null;
  2787. // If the avail_out is left at 0, then it means that it ran out
  2788. // of room. If there was avail_out left over, then it means
  2789. // that all of the input was consumed.
  2790. switch (this.mode) {
  2791. case exports.DEFLATE:
  2792. case exports.GZIP:
  2793. case exports.DEFLATERAW:
  2794. this.err = zlib_deflate.deflate(this.strm, this.flush);
  2795. break;
  2796. case exports.UNZIP:
  2797. if (this.strm.avail_in > 0) {
  2798. next_expected_header_byte = this.strm.next_in;
  2799. }
  2800. switch (this.gzip_id_bytes_read) {
  2801. case 0:
  2802. if (next_expected_header_byte === null) {
  2803. break;
  2804. }
  2805. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
  2806. this.gzip_id_bytes_read = 1;
  2807. next_expected_header_byte++;
  2808. if (this.strm.avail_in === 1) {
  2809. // The only available byte was already read.
  2810. break;
  2811. }
  2812. } else {
  2813. this.mode = exports.INFLATE;
  2814. break;
  2815. }
  2816. // fallthrough
  2817. case 1:
  2818. if (next_expected_header_byte === null) {
  2819. break;
  2820. }
  2821. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
  2822. this.gzip_id_bytes_read = 2;
  2823. this.mode = exports.GUNZIP;
  2824. } else {
  2825. // There is no actual difference between INFLATE and INFLATERAW
  2826. // (after initialization).
  2827. this.mode = exports.INFLATE;
  2828. }
  2829. break;
  2830. default:
  2831. throw new Error('invalid number of gzip magic number bytes read');
  2832. }
  2833. // fallthrough
  2834. case exports.INFLATE:
  2835. case exports.GUNZIP:
  2836. case exports.INFLATERAW:
  2837. this.err = zlib_inflate.inflate(this.strm, this.flush
  2838. // If data was encoded with dictionary
  2839. );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
  2840. // Load it
  2841. this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
  2842. if (this.err === exports.Z_OK) {
  2843. // And try to decode again
  2844. this.err = zlib_inflate.inflate(this.strm, this.flush);
  2845. } else if (this.err === exports.Z_DATA_ERROR) {
  2846. // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
  2847. // Make it possible for After() to tell a bad dictionary from bad
  2848. // input.
  2849. this.err = exports.Z_NEED_DICT;
  2850. }
  2851. }
  2852. while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
  2853. // Bytes remain in input buffer. Perhaps this is another compressed
  2854. // member in the same archive, or just trailing garbage.
  2855. // Trailing zero bytes are okay, though, since they are frequently
  2856. // used for padding.
  2857. this.reset();
  2858. this.err = zlib_inflate.inflate(this.strm, this.flush);
  2859. }
  2860. break;
  2861. default:
  2862. throw new Error('Unknown mode ' + this.mode);
  2863. }
  2864. };
  2865. Zlib.prototype._checkError = function () {
  2866. // Acceptable error states depend on the type of zlib stream.
  2867. switch (this.err) {
  2868. case exports.Z_OK:
  2869. case exports.Z_BUF_ERROR:
  2870. if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
  2871. this._error('unexpected end of file');
  2872. return false;
  2873. }
  2874. break;
  2875. case exports.Z_STREAM_END:
  2876. // normal statuses, not fatal
  2877. break;
  2878. case exports.Z_NEED_DICT:
  2879. if (this.dictionary == null) {
  2880. this._error('Missing dictionary');
  2881. } else {
  2882. this._error('Bad dictionary');
  2883. }
  2884. return false;
  2885. default:
  2886. // something else.
  2887. this._error('Zlib error');
  2888. return false;
  2889. }
  2890. return true;
  2891. };
  2892. Zlib.prototype._after = function () {
  2893. if (!this._checkError()) {
  2894. return;
  2895. }
  2896. var avail_out = this.strm.avail_out;
  2897. var avail_in = this.strm.avail_in;
  2898. this.write_in_progress = false;
  2899. // call the write() cb
  2900. this.callback(avail_in, avail_out);
  2901. if (this.pending_close) {
  2902. this.close();
  2903. }
  2904. };
  2905. Zlib.prototype._error = function (message) {
  2906. if (this.strm.msg) {
  2907. message = this.strm.msg;
  2908. }
  2909. this.onerror(message, this.err
  2910. // no hope of rescue.
  2911. );this.write_in_progress = false;
  2912. if (this.pending_close) {
  2913. this.close();
  2914. }
  2915. };
  2916. Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  2917. assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
  2918. assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  2919. assert(level >= -1 && level <= 9, 'invalid compression level');
  2920. assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
  2921. 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');
  2922. this._init(level, windowBits, memLevel, strategy, dictionary);
  2923. this._setDictionary();
  2924. };
  2925. Zlib.prototype.params = function () {
  2926. throw new Error('deflateParams Not supported');
  2927. };
  2928. Zlib.prototype.reset = function () {
  2929. this._reset();
  2930. this._setDictionary();
  2931. };
  2932. Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  2933. this.level = level;
  2934. this.windowBits = windowBits;
  2935. this.memLevel = memLevel;
  2936. this.strategy = strategy;
  2937. this.flush = exports.Z_NO_FLUSH;
  2938. this.err = exports.Z_OK;
  2939. if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
  2940. this.windowBits += 16;
  2941. }
  2942. if (this.mode === exports.UNZIP) {
  2943. this.windowBits += 32;
  2944. }
  2945. if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
  2946. this.windowBits = -1 * this.windowBits;
  2947. }
  2948. this.strm = new Zstream();
  2949. switch (this.mode) {
  2950. case exports.DEFLATE:
  2951. case exports.GZIP:
  2952. case exports.DEFLATERAW:
  2953. this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
  2954. break;
  2955. case exports.INFLATE:
  2956. case exports.GUNZIP:
  2957. case exports.INFLATERAW:
  2958. case exports.UNZIP:
  2959. this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
  2960. break;
  2961. default:
  2962. throw new Error('Unknown mode ' + this.mode);
  2963. }
  2964. if (this.err !== exports.Z_OK) {
  2965. this._error('Init error');
  2966. }
  2967. this.dictionary = dictionary;
  2968. this.write_in_progress = false;
  2969. this.init_done = true;
  2970. };
  2971. Zlib.prototype._setDictionary = function () {
  2972. if (this.dictionary == null) {
  2973. return;
  2974. }
  2975. this.err = exports.Z_OK;
  2976. switch (this.mode) {
  2977. case exports.DEFLATE:
  2978. case exports.DEFLATERAW:
  2979. this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
  2980. break;
  2981. default:
  2982. break;
  2983. }
  2984. if (this.err !== exports.Z_OK) {
  2985. this._error('Failed to set dictionary');
  2986. }
  2987. };
  2988. Zlib.prototype._reset = function () {
  2989. this.err = exports.Z_OK;
  2990. switch (this.mode) {
  2991. case exports.DEFLATE:
  2992. case exports.DEFLATERAW:
  2993. case exports.GZIP:
  2994. this.err = zlib_deflate.deflateReset(this.strm);
  2995. break;
  2996. case exports.INFLATE:
  2997. case exports.INFLATERAW:
  2998. case exports.GUNZIP:
  2999. this.err = zlib_inflate.inflateReset(this.strm);
  3000. break;
  3001. default:
  3002. break;
  3003. }
  3004. if (this.err !== exports.Z_OK) {
  3005. this._error('Failed to reset stream');
  3006. }
  3007. };
  3008. exports.Zlib = Zlib;
  3009. }).call(this,require('_process'),require("buffer").Buffer)
  3010. },{"_process":47,"assert":23,"buffer":28,"pako/lib/zlib/constants":37,"pako/lib/zlib/deflate.js":39,"pako/lib/zlib/inflate.js":41,"pako/lib/zlib/zstream":45}],27:[function(require,module,exports){
  3011. (function (process){
  3012. 'use strict';
  3013. var Buffer = require('buffer').Buffer;
  3014. var Transform = require('stream').Transform;
  3015. var binding = require('./binding');
  3016. var util = require('util');
  3017. var assert = require('assert').ok;
  3018. var kMaxLength = require('buffer').kMaxLength;
  3019. var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
  3020. // zlib doesn't provide these, so kludge them in following the same
  3021. // const naming scheme zlib uses.
  3022. binding.Z_MIN_WINDOWBITS = 8;
  3023. binding.Z_MAX_WINDOWBITS = 15;
  3024. binding.Z_DEFAULT_WINDOWBITS = 15;
  3025. // fewer than 64 bytes per chunk is stupid.
  3026. // technically it could work with as few as 8, but even 64 bytes
  3027. // is absurdly low. Usually a MB or more is best.
  3028. binding.Z_MIN_CHUNK = 64;
  3029. binding.Z_MAX_CHUNK = Infinity;
  3030. binding.Z_DEFAULT_CHUNK = 16 * 1024;
  3031. binding.Z_MIN_MEMLEVEL = 1;
  3032. binding.Z_MAX_MEMLEVEL = 9;
  3033. binding.Z_DEFAULT_MEMLEVEL = 8;
  3034. binding.Z_MIN_LEVEL = -1;
  3035. binding.Z_MAX_LEVEL = 9;
  3036. binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
  3037. // expose all the zlib constants
  3038. var bkeys = Object.keys(binding);
  3039. for (var bk = 0; bk < bkeys.length; bk++) {
  3040. var bkey = bkeys[bk];
  3041. if (bkey.match(/^Z/)) {
  3042. Object.defineProperty(exports, bkey, {
  3043. enumerable: true, value: binding[bkey], writable: false
  3044. });
  3045. }
  3046. }
  3047. // translation table for return codes.
  3048. var codes = {
  3049. Z_OK: binding.Z_OK,
  3050. Z_STREAM_END: binding.Z_STREAM_END,
  3051. Z_NEED_DICT: binding.Z_NEED_DICT,
  3052. Z_ERRNO: binding.Z_ERRNO,
  3053. Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  3054. Z_DATA_ERROR: binding.Z_DATA_ERROR,
  3055. Z_MEM_ERROR: binding.Z_MEM_ERROR,
  3056. Z_BUF_ERROR: binding.Z_BUF_ERROR,
  3057. Z_VERSION_ERROR: binding.Z_VERSION_ERROR
  3058. };
  3059. var ckeys = Object.keys(codes);
  3060. for (var ck = 0; ck < ckeys.length; ck++) {
  3061. var ckey = ckeys[ck];
  3062. codes[codes[ckey]] = ckey;
  3063. }
  3064. Object.defineProperty(exports, 'codes', {
  3065. enumerable: true, value: Object.freeze(codes), writable: false
  3066. });
  3067. exports.Deflate = Deflate;
  3068. exports.Inflate = Inflate;
  3069. exports.Gzip = Gzip;
  3070. exports.Gunzip = Gunzip;
  3071. exports.DeflateRaw = DeflateRaw;
  3072. exports.InflateRaw = InflateRaw;
  3073. exports.Unzip = Unzip;
  3074. exports.createDeflate = function (o) {
  3075. return new Deflate(o);
  3076. };
  3077. exports.createInflate = function (o) {
  3078. return new Inflate(o);
  3079. };
  3080. exports.createDeflateRaw = function (o) {
  3081. return new DeflateRaw(o);
  3082. };
  3083. exports.createInflateRaw = function (o) {
  3084. return new InflateRaw(o);
  3085. };
  3086. exports.createGzip = function (o) {
  3087. return new Gzip(o);
  3088. };
  3089. exports.createGunzip = function (o) {
  3090. return new Gunzip(o);
  3091. };
  3092. exports.createUnzip = function (o) {
  3093. return new Unzip(o);
  3094. };
  3095. // Convenience methods.
  3096. // compress/decompress a string or buffer in one step.
  3097. exports.deflate = function (buffer, opts, callback) {
  3098. if (typeof opts === 'function') {
  3099. callback = opts;
  3100. opts = {};
  3101. }
  3102. return zlibBuffer(new Deflate(opts), buffer, callback);
  3103. };
  3104. exports.deflateSync = function (buffer, opts) {
  3105. return zlibBufferSync(new Deflate(opts), buffer);
  3106. };
  3107. exports.gzip = function (buffer, opts, callback) {
  3108. if (typeof opts === 'function') {
  3109. callback = opts;
  3110. opts = {};
  3111. }
  3112. return zlibBuffer(new Gzip(opts), buffer, callback);
  3113. };
  3114. exports.gzipSync = function (buffer, opts) {
  3115. return zlibBufferSync(new Gzip(opts), buffer);
  3116. };
  3117. exports.deflateRaw = function (buffer, opts, callback) {
  3118. if (typeof opts === 'function') {
  3119. callback = opts;
  3120. opts = {};
  3121. }
  3122. return zlibBuffer(new DeflateRaw(opts), buffer, callback);
  3123. };
  3124. exports.deflateRawSync = function (buffer, opts) {
  3125. return zlibBufferSync(new DeflateRaw(opts), buffer);
  3126. };
  3127. exports.unzip = function (buffer, opts, callback) {
  3128. if (typeof opts === 'function') {
  3129. callback = opts;
  3130. opts = {};
  3131. }
  3132. return zlibBuffer(new Unzip(opts), buffer, callback);
  3133. };
  3134. exports.unzipSync = function (buffer, opts) {
  3135. return zlibBufferSync(new Unzip(opts), buffer);
  3136. };
  3137. exports.inflate = function (buffer, opts, callback) {
  3138. if (typeof opts === 'function') {
  3139. callback = opts;
  3140. opts = {};
  3141. }
  3142. return zlibBuffer(new Inflate(opts), buffer, callback);
  3143. };
  3144. exports.inflateSync = function (buffer, opts) {
  3145. return zlibBufferSync(new Inflate(opts), buffer);
  3146. };
  3147. exports.gunzip = function (buffer, opts, callback) {
  3148. if (typeof opts === 'function') {
  3149. callback = opts;
  3150. opts = {};
  3151. }
  3152. return zlibBuffer(new Gunzip(opts), buffer, callback);
  3153. };
  3154. exports.gunzipSync = function (buffer, opts) {
  3155. return zlibBufferSync(new Gunzip(opts), buffer);
  3156. };
  3157. exports.inflateRaw = function (buffer, opts, callback) {
  3158. if (typeof opts === 'function') {
  3159. callback = opts;
  3160. opts = {};
  3161. }
  3162. return zlibBuffer(new InflateRaw(opts), buffer, callback);
  3163. };
  3164. exports.inflateRawSync = function (buffer, opts) {
  3165. return zlibBufferSync(new InflateRaw(opts), buffer);
  3166. };
  3167. function zlibBuffer(engine, buffer, callback) {
  3168. var buffers = [];
  3169. var nread = 0;
  3170. engine.on('error', onError);
  3171. engine.on('end', onEnd);
  3172. engine.end(buffer);
  3173. flow();
  3174. function flow() {
  3175. var chunk;
  3176. while (null !== (chunk = engine.read())) {
  3177. buffers.push(chunk);
  3178. nread += chunk.length;
  3179. }
  3180. engine.once('readable', flow);
  3181. }
  3182. function onError(err) {
  3183. engine.removeListener('end', onEnd);
  3184. engine.removeListener('readable', flow);
  3185. callback(err);
  3186. }
  3187. function onEnd() {
  3188. var buf;
  3189. var err = null;
  3190. if (nread >= kMaxLength) {
  3191. err = new RangeError(kRangeErrorMessage);
  3192. } else {
  3193. buf = Buffer.concat(buffers, nread);
  3194. }
  3195. buffers = [];
  3196. engine.close();
  3197. callback(err, buf);
  3198. }
  3199. }
  3200. function zlibBufferSync(engine, buffer) {
  3201. if (typeof buffer === 'string') buffer = Buffer.from(buffer);
  3202. if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
  3203. var flushFlag = engine._finishFlushFlag;
  3204. return engine._processChunk(buffer, flushFlag);
  3205. }
  3206. // generic zlib
  3207. // minimal 2-byte header
  3208. function Deflate(opts) {
  3209. if (!(this instanceof Deflate)) return new Deflate(opts);
  3210. Zlib.call(this, opts, binding.DEFLATE);
  3211. }
  3212. function Inflate(opts) {
  3213. if (!(this instanceof Inflate)) return new Inflate(opts);
  3214. Zlib.call(this, opts, binding.INFLATE);
  3215. }
  3216. // gzip - bigger header, same deflate compression
  3217. function Gzip(opts) {
  3218. if (!(this instanceof Gzip)) return new Gzip(opts);
  3219. Zlib.call(this, opts, binding.GZIP);
  3220. }
  3221. function Gunzip(opts) {
  3222. if (!(this instanceof Gunzip)) return new Gunzip(opts);
  3223. Zlib.call(this, opts, binding.GUNZIP);
  3224. }
  3225. // raw - no header
  3226. function DeflateRaw(opts) {
  3227. if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  3228. Zlib.call(this, opts, binding.DEFLATERAW);
  3229. }
  3230. function InflateRaw(opts) {
  3231. if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  3232. Zlib.call(this, opts, binding.INFLATERAW);
  3233. }
  3234. // auto-detect header.
  3235. function Unzip(opts) {
  3236. if (!(this instanceof Unzip)) return new Unzip(opts);
  3237. Zlib.call(this, opts, binding.UNZIP);
  3238. }
  3239. function isValidFlushFlag(flag) {
  3240. 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;
  3241. }
  3242. // the Zlib class they all inherit from
  3243. // This thing manages the queue of requests, and returns
  3244. // true or false if there is anything in the queue when
  3245. // you call the .write() method.
  3246. function Zlib(opts, mode) {
  3247. var _this = this;
  3248. this._opts = opts = opts || {};
  3249. this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
  3250. Transform.call(this, opts);
  3251. if (opts.flush && !isValidFlushFlag(opts.flush)) {
  3252. throw new Error('Invalid flush flag: ' + opts.flush);
  3253. }
  3254. if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
  3255. throw new Error('Invalid flush flag: ' + opts.finishFlush);
  3256. }
  3257. this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  3258. this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
  3259. if (opts.chunkSize) {
  3260. if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
  3261. throw new Error('Invalid chunk size: ' + opts.chunkSize);
  3262. }
  3263. }
  3264. if (opts.windowBits) {
  3265. if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
  3266. throw new Error('Invalid windowBits: ' + opts.windowBits);
  3267. }
  3268. }
  3269. if (opts.level) {
  3270. if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
  3271. throw new Error('Invalid compression level: ' + opts.level);
  3272. }
  3273. }
  3274. if (opts.memLevel) {
  3275. if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
  3276. throw new Error('Invalid memLevel: ' + opts.memLevel);
  3277. }
  3278. }
  3279. if (opts.strategy) {
  3280. 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) {
  3281. throw new Error('Invalid strategy: ' + opts.strategy);
  3282. }
  3283. }
  3284. if (opts.dictionary) {
  3285. if (!Buffer.isBuffer(opts.dictionary)) {
  3286. throw new Error('Invalid dictionary: it should be a Buffer instance');
  3287. }
  3288. }
  3289. this._handle = new binding.Zlib(mode);
  3290. var self = this;
  3291. this._hadError = false;
  3292. this._handle.onerror = function (message, errno) {
  3293. // there is no way to cleanly recover.
  3294. // continuing only obscures problems.
  3295. _close(self);
  3296. self._hadError = true;
  3297. var error = new Error(message);
  3298. error.errno = errno;
  3299. error.code = exports.codes[errno];
  3300. self.emit('error', error);
  3301. };
  3302. var level = exports.Z_DEFAULT_COMPRESSION;
  3303. if (typeof opts.level === 'number') level = opts.level;
  3304. var strategy = exports.Z_DEFAULT_STRATEGY;
  3305. if (typeof opts.strategy === 'number') strategy = opts.strategy;
  3306. this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
  3307. this._buffer = Buffer.allocUnsafe(this._chunkSize);
  3308. this._offset = 0;
  3309. this._level = level;
  3310. this._strategy = strategy;
  3311. this.once('end', this.close);
  3312. Object.defineProperty(this, '_closed', {
  3313. get: function () {
  3314. return !_this._handle;
  3315. },
  3316. configurable: true,
  3317. enumerable: true
  3318. });
  3319. }
  3320. util.inherits(Zlib, Transform);
  3321. Zlib.prototype.params = function (level, strategy, callback) {
  3322. if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
  3323. throw new RangeError('Invalid compression level: ' + level);
  3324. }
  3325. if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
  3326. throw new TypeError('Invalid strategy: ' + strategy);
  3327. }
  3328. if (this._level !== level || this._strategy !== strategy) {
  3329. var self = this;
  3330. this.flush(binding.Z_SYNC_FLUSH, function () {
  3331. assert(self._handle, 'zlib binding closed');
  3332. self._handle.params(level, strategy);
  3333. if (!self._hadError) {
  3334. self._level = level;
  3335. self._strategy = strategy;
  3336. if (callback) callback();
  3337. }
  3338. });
  3339. } else {
  3340. process.nextTick(callback);
  3341. }
  3342. };
  3343. Zlib.prototype.reset = function () {
  3344. assert(this._handle, 'zlib binding closed');
  3345. return this._handle.reset();
  3346. };
  3347. // This is the _flush function called by the transform class,
  3348. // internally, when the last chunk has been written.
  3349. Zlib.prototype._flush = function (callback) {
  3350. this._transform(Buffer.alloc(0), '', callback);
  3351. };
  3352. Zlib.prototype.flush = function (kind, callback) {
  3353. var _this2 = this;
  3354. var ws = this._writableState;
  3355. if (typeof kind === 'function' || kind === undefined && !callback) {
  3356. callback = kind;
  3357. kind = binding.Z_FULL_FLUSH;
  3358. }
  3359. if (ws.ended) {
  3360. if (callback) process.nextTick(callback);
  3361. } else if (ws.ending) {
  3362. if (callback) this.once('end', callback);
  3363. } else if (ws.needDrain) {
  3364. if (callback) {
  3365. this.once('drain', function () {
  3366. return _this2.flush(kind, callback);
  3367. });
  3368. }
  3369. } else {
  3370. this._flushFlag = kind;
  3371. this.write(Buffer.alloc(0), '', callback);
  3372. }
  3373. };
  3374. Zlib.prototype.close = function (callback) {
  3375. _close(this, callback);
  3376. process.nextTick(emitCloseNT, this);
  3377. };
  3378. function _close(engine, callback) {
  3379. if (callback) process.nextTick(callback);
  3380. // Caller may invoke .close after a zlib error (which will null _handle).
  3381. if (!engine._handle) return;
  3382. engine._handle.close();
  3383. engine._handle = null;
  3384. }
  3385. function emitCloseNT(self) {
  3386. self.emit('close');
  3387. }
  3388. Zlib.prototype._transform = function (chunk, encoding, cb) {
  3389. var flushFlag;
  3390. var ws = this._writableState;
  3391. var ending = ws.ending || ws.ended;
  3392. var last = ending && (!chunk || ws.length === chunk.length);
  3393. if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
  3394. if (!this._handle) return cb(new Error('zlib binding closed'));
  3395. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  3396. // (or whatever flag was provided using opts.finishFlush).
  3397. // If it's explicitly flushing at some other time, then we use
  3398. // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  3399. // goodness.
  3400. if (last) flushFlag = this._finishFlushFlag;else {
  3401. flushFlag = this._flushFlag;
  3402. // once we've flushed the last of the queue, stop flushing and
  3403. // go back to the normal behavior.
  3404. if (chunk.length >= ws.length) {
  3405. this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
  3406. }
  3407. }
  3408. this._processChunk(chunk, flushFlag, cb);
  3409. };
  3410. Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  3411. var availInBefore = chunk && chunk.length;
  3412. var availOutBefore = this._chunkSize - this._offset;
  3413. var inOff = 0;
  3414. var self = this;
  3415. var async = typeof cb === 'function';
  3416. if (!async) {
  3417. var buffers = [];
  3418. var nread = 0;
  3419. var error;
  3420. this.on('error', function (er) {
  3421. error = er;
  3422. });
  3423. assert(this._handle, 'zlib binding closed');
  3424. do {
  3425. var res = this._handle.writeSync(flushFlag, chunk, // in
  3426. inOff, // in_off
  3427. availInBefore, // in_len
  3428. this._buffer, // out
  3429. this._offset, //out_off
  3430. availOutBefore); // out_len
  3431. } while (!this._hadError && callback(res[0], res[1]));
  3432. if (this._hadError) {
  3433. throw error;
  3434. }
  3435. if (nread >= kMaxLength) {
  3436. _close(this);
  3437. throw new RangeError(kRangeErrorMessage);
  3438. }
  3439. var buf = Buffer.concat(buffers, nread);
  3440. _close(this);
  3441. return buf;
  3442. }
  3443. assert(this._handle, 'zlib binding closed');
  3444. var req = this._handle.write(flushFlag, chunk, // in
  3445. inOff, // in_off
  3446. availInBefore, // in_len
  3447. this._buffer, // out
  3448. this._offset, //out_off
  3449. availOutBefore); // out_len
  3450. req.buffer = chunk;
  3451. req.callback = callback;
  3452. function callback(availInAfter, availOutAfter) {
  3453. // When the callback is used in an async write, the callback's
  3454. // context is the `req` object that was created. The req object
  3455. // is === this._handle, and that's why it's important to null
  3456. // out the values after they are done being used. `this._handle`
  3457. // can stay in memory longer than the callback and buffer are needed.
  3458. if (this) {
  3459. this.buffer = null;
  3460. this.callback = null;
  3461. }
  3462. if (self._hadError) return;
  3463. var have = availOutBefore - availOutAfter;
  3464. assert(have >= 0, 'have should not go down');
  3465. if (have > 0) {
  3466. var out = self._buffer.slice(self._offset, self._offset + have);
  3467. self._offset += have;
  3468. // serve some output to the consumer.
  3469. if (async) {
  3470. self.push(out);
  3471. } else {
  3472. buffers.push(out);
  3473. nread += out.length;
  3474. }
  3475. }
  3476. // exhausted the output buffer, or used all the input create a new one.
  3477. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  3478. availOutBefore = self._chunkSize;
  3479. self._offset = 0;
  3480. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  3481. }
  3482. if (availOutAfter === 0) {
  3483. // Not actually done. Need to reprocess.
  3484. // Also, update the availInBefore to the availInAfter value,
  3485. // so that if we have to hit it a third (fourth, etc.) time,
  3486. // it'll have the correct byte counts.
  3487. inOff += availInBefore - availInAfter;
  3488. availInBefore = availInAfter;
  3489. if (!async) return true;
  3490. var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
  3491. newReq.callback = callback; // this same function
  3492. newReq.buffer = chunk;
  3493. return;
  3494. }
  3495. if (!async) return false;
  3496. // finished with the chunk.
  3497. cb();
  3498. }
  3499. };
  3500. util.inherits(Deflate, Zlib);
  3501. util.inherits(Inflate, Zlib);
  3502. util.inherits(Gzip, Zlib);
  3503. util.inherits(Gunzip, Zlib);
  3504. util.inherits(DeflateRaw, Zlib);
  3505. util.inherits(InflateRaw, Zlib);
  3506. util.inherits(Unzip, Zlib);
  3507. }).call(this,require('_process'))
  3508. },{"./binding":26,"_process":47,"assert":23,"buffer":28,"stream":63,"util":67}],28:[function(require,module,exports){
  3509. /*!
  3510. * The buffer module from node.js, for the browser.
  3511. *
  3512. * @author Feross Aboukhadijeh <https://feross.org>
  3513. * @license MIT
  3514. */
  3515. /* eslint-disable no-proto */
  3516. 'use strict'
  3517. var base64 = require('base64-js')
  3518. var ieee754 = require('ieee754')
  3519. exports.Buffer = Buffer
  3520. exports.SlowBuffer = SlowBuffer
  3521. exports.INSPECT_MAX_BYTES = 50
  3522. var K_MAX_LENGTH = 0x7fffffff
  3523. exports.kMaxLength = K_MAX_LENGTH
  3524. /**
  3525. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  3526. * === true Use Uint8Array implementation (fastest)
  3527. * === false Print warning and recommend using `buffer` v4.x which has an Object
  3528. * implementation (most compatible, even IE6)
  3529. *
  3530. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  3531. * Opera 11.6+, iOS 4.2+.
  3532. *
  3533. * We report that the browser does not support typed arrays if the are not subclassable
  3534. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  3535. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  3536. * for __proto__ and has a buggy typed array implementation.
  3537. */
  3538. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  3539. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  3540. typeof console.error === 'function') {
  3541. console.error(
  3542. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  3543. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  3544. )
  3545. }
  3546. function typedArraySupport () {
  3547. // Can typed array instances can be augmented?
  3548. try {
  3549. var arr = new Uint8Array(1)
  3550. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  3551. return arr.foo() === 42
  3552. } catch (e) {
  3553. return false
  3554. }
  3555. }
  3556. Object.defineProperty(Buffer.prototype, 'parent', {
  3557. enumerable: true,
  3558. get: function () {
  3559. if (!Buffer.isBuffer(this)) return undefined
  3560. return this.buffer
  3561. }
  3562. })
  3563. Object.defineProperty(Buffer.prototype, 'offset', {
  3564. enumerable: true,
  3565. get: function () {
  3566. if (!Buffer.isBuffer(this)) return undefined
  3567. return this.byteOffset
  3568. }
  3569. })
  3570. function createBuffer (length) {
  3571. if (length > K_MAX_LENGTH) {
  3572. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  3573. }
  3574. // Return an augmented `Uint8Array` instance
  3575. var buf = new Uint8Array(length)
  3576. buf.__proto__ = Buffer.prototype
  3577. return buf
  3578. }
  3579. /**
  3580. * The Buffer constructor returns instances of `Uint8Array` that have their
  3581. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  3582. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  3583. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  3584. * returns a single octet.
  3585. *
  3586. * The `Uint8Array` prototype remains unmodified.
  3587. */
  3588. function Buffer (arg, encodingOrOffset, length) {
  3589. // Common case.
  3590. if (typeof arg === 'number') {
  3591. if (typeof encodingOrOffset === 'string') {
  3592. throw new TypeError(
  3593. 'The "string" argument must be of type string. Received type number'
  3594. )
  3595. }
  3596. return allocUnsafe(arg)
  3597. }
  3598. return from(arg, encodingOrOffset, length)
  3599. }
  3600. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  3601. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  3602. Buffer[Symbol.species] === Buffer) {
  3603. Object.defineProperty(Buffer, Symbol.species, {
  3604. value: null,
  3605. configurable: true,
  3606. enumerable: false,
  3607. writable: false
  3608. })
  3609. }
  3610. Buffer.poolSize = 8192 // not used by this implementation
  3611. function from (value, encodingOrOffset, length) {
  3612. if (typeof value === 'string') {
  3613. return fromString(value, encodingOrOffset)
  3614. }
  3615. if (ArrayBuffer.isView(value)) {
  3616. return fromArrayLike(value)
  3617. }
  3618. if (value == null) {
  3619. throw TypeError(
  3620. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3621. 'or Array-like Object. Received type ' + (typeof value)
  3622. )
  3623. }
  3624. if (isInstance(value, ArrayBuffer) ||
  3625. (value && isInstance(value.buffer, ArrayBuffer))) {
  3626. return fromArrayBuffer(value, encodingOrOffset, length)
  3627. }
  3628. if (typeof value === 'number') {
  3629. throw new TypeError(
  3630. 'The "value" argument must not be of type number. Received type number'
  3631. )
  3632. }
  3633. var valueOf = value.valueOf && value.valueOf()
  3634. if (valueOf != null && valueOf !== value) {
  3635. return Buffer.from(valueOf, encodingOrOffset, length)
  3636. }
  3637. var b = fromObject(value)
  3638. if (b) return b
  3639. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  3640. typeof value[Symbol.toPrimitive] === 'function') {
  3641. return Buffer.from(
  3642. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  3643. )
  3644. }
  3645. throw new TypeError(
  3646. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3647. 'or Array-like Object. Received type ' + (typeof value)
  3648. )
  3649. }
  3650. /**
  3651. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  3652. * if value is a number.
  3653. * Buffer.from(str[, encoding])
  3654. * Buffer.from(array)
  3655. * Buffer.from(buffer)
  3656. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  3657. **/
  3658. Buffer.from = function (value, encodingOrOffset, length) {
  3659. return from(value, encodingOrOffset, length)
  3660. }
  3661. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  3662. // https://github.com/feross/buffer/pull/148
  3663. Buffer.prototype.__proto__ = Uint8Array.prototype
  3664. Buffer.__proto__ = Uint8Array
  3665. function assertSize (size) {
  3666. if (typeof size !== 'number') {
  3667. throw new TypeError('"size" argument must be of type number')
  3668. } else if (size < 0) {
  3669. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  3670. }
  3671. }
  3672. function alloc (size, fill, encoding) {
  3673. assertSize(size)
  3674. if (size <= 0) {
  3675. return createBuffer(size)
  3676. }
  3677. if (fill !== undefined) {
  3678. // Only pay attention to encoding if it's a string. This
  3679. // prevents accidentally sending in a number that would
  3680. // be interpretted as a start offset.
  3681. return typeof encoding === 'string'
  3682. ? createBuffer(size).fill(fill, encoding)
  3683. : createBuffer(size).fill(fill)
  3684. }
  3685. return createBuffer(size)
  3686. }
  3687. /**
  3688. * Creates a new filled Buffer instance.
  3689. * alloc(size[, fill[, encoding]])
  3690. **/
  3691. Buffer.alloc = function (size, fill, encoding) {
  3692. return alloc(size, fill, encoding)
  3693. }
  3694. function allocUnsafe (size) {
  3695. assertSize(size)
  3696. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  3697. }
  3698. /**
  3699. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  3700. * */
  3701. Buffer.allocUnsafe = function (size) {
  3702. return allocUnsafe(size)
  3703. }
  3704. /**
  3705. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  3706. */
  3707. Buffer.allocUnsafeSlow = function (size) {
  3708. return allocUnsafe(size)
  3709. }
  3710. function fromString (string, encoding) {
  3711. if (typeof encoding !== 'string' || encoding === '') {
  3712. encoding = 'utf8'
  3713. }
  3714. if (!Buffer.isEncoding(encoding)) {
  3715. throw new TypeError('Unknown encoding: ' + encoding)
  3716. }
  3717. var length = byteLength(string, encoding) | 0
  3718. var buf = createBuffer(length)
  3719. var actual = buf.write(string, encoding)
  3720. if (actual !== length) {
  3721. // Writing a hex string, for example, that contains invalid characters will
  3722. // cause everything after the first invalid character to be ignored. (e.g.
  3723. // 'abxxcd' will be treated as 'ab')
  3724. buf = buf.slice(0, actual)
  3725. }
  3726. return buf
  3727. }
  3728. function fromArrayLike (array) {
  3729. var length = array.length < 0 ? 0 : checked(array.length) | 0
  3730. var buf = createBuffer(length)
  3731. for (var i = 0; i < length; i += 1) {
  3732. buf[i] = array[i] & 255
  3733. }
  3734. return buf
  3735. }
  3736. function fromArrayBuffer (array, byteOffset, length) {
  3737. if (byteOffset < 0 || array.byteLength < byteOffset) {
  3738. throw new RangeError('"offset" is outside of buffer bounds')
  3739. }
  3740. if (array.byteLength < byteOffset + (length || 0)) {
  3741. throw new RangeError('"length" is outside of buffer bounds')
  3742. }
  3743. var buf
  3744. if (byteOffset === undefined && length === undefined) {
  3745. buf = new Uint8Array(array)
  3746. } else if (length === undefined) {
  3747. buf = new Uint8Array(array, byteOffset)
  3748. } else {
  3749. buf = new Uint8Array(array, byteOffset, length)
  3750. }
  3751. // Return an augmented `Uint8Array` instance
  3752. buf.__proto__ = Buffer.prototype
  3753. return buf
  3754. }
  3755. function fromObject (obj) {
  3756. if (Buffer.isBuffer(obj)) {
  3757. var len = checked(obj.length) | 0
  3758. var buf = createBuffer(len)
  3759. if (buf.length === 0) {
  3760. return buf
  3761. }
  3762. obj.copy(buf, 0, 0, len)
  3763. return buf
  3764. }
  3765. if (obj.length !== undefined) {
  3766. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  3767. return createBuffer(0)
  3768. }
  3769. return fromArrayLike(obj)
  3770. }
  3771. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  3772. return fromArrayLike(obj.data)
  3773. }
  3774. }
  3775. function checked (length) {
  3776. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  3777. // length is NaN (which is otherwise coerced to zero.)
  3778. if (length >= K_MAX_LENGTH) {
  3779. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  3780. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  3781. }
  3782. return length | 0
  3783. }
  3784. function SlowBuffer (length) {
  3785. if (+length != length) { // eslint-disable-line eqeqeq
  3786. length = 0
  3787. }
  3788. return Buffer.alloc(+length)
  3789. }
  3790. Buffer.isBuffer = function isBuffer (b) {
  3791. return b != null && b._isBuffer === true &&
  3792. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  3793. }
  3794. Buffer.compare = function compare (a, b) {
  3795. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  3796. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  3797. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  3798. throw new TypeError(
  3799. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  3800. )
  3801. }
  3802. if (a === b) return 0
  3803. var x = a.length
  3804. var y = b.length
  3805. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  3806. if (a[i] !== b[i]) {
  3807. x = a[i]
  3808. y = b[i]
  3809. break
  3810. }
  3811. }
  3812. if (x < y) return -1
  3813. if (y < x) return 1
  3814. return 0
  3815. }
  3816. Buffer.isEncoding = function isEncoding (encoding) {
  3817. switch (String(encoding).toLowerCase()) {
  3818. case 'hex':
  3819. case 'utf8':
  3820. case 'utf-8':
  3821. case 'ascii':
  3822. case 'latin1':
  3823. case 'binary':
  3824. case 'base64':
  3825. case 'ucs2':
  3826. case 'ucs-2':
  3827. case 'utf16le':
  3828. case 'utf-16le':
  3829. return true
  3830. default:
  3831. return false
  3832. }
  3833. }
  3834. Buffer.concat = function concat (list, length) {
  3835. if (!Array.isArray(list)) {
  3836. throw new TypeError('"list" argument must be an Array of Buffers')
  3837. }
  3838. if (list.length === 0) {
  3839. return Buffer.alloc(0)
  3840. }
  3841. var i
  3842. if (length === undefined) {
  3843. length = 0
  3844. for (i = 0; i < list.length; ++i) {
  3845. length += list[i].length
  3846. }
  3847. }
  3848. var buffer = Buffer.allocUnsafe(length)
  3849. var pos = 0
  3850. for (i = 0; i < list.length; ++i) {
  3851. var buf = list[i]
  3852. if (isInstance(buf, Uint8Array)) {
  3853. buf = Buffer.from(buf)
  3854. }
  3855. if (!Buffer.isBuffer(buf)) {
  3856. throw new TypeError('"list" argument must be an Array of Buffers')
  3857. }
  3858. buf.copy(buffer, pos)
  3859. pos += buf.length
  3860. }
  3861. return buffer
  3862. }
  3863. function byteLength (string, encoding) {
  3864. if (Buffer.isBuffer(string)) {
  3865. return string.length
  3866. }
  3867. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  3868. return string.byteLength
  3869. }
  3870. if (typeof string !== 'string') {
  3871. throw new TypeError(
  3872. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  3873. 'Received type ' + typeof string
  3874. )
  3875. }
  3876. var len = string.length
  3877. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  3878. if (!mustMatch && len === 0) return 0
  3879. // Use a for loop to avoid recursion
  3880. var loweredCase = false
  3881. for (;;) {
  3882. switch (encoding) {
  3883. case 'ascii':
  3884. case 'latin1':
  3885. case 'binary':
  3886. return len
  3887. case 'utf8':
  3888. case 'utf-8':
  3889. return utf8ToBytes(string).length
  3890. case 'ucs2':
  3891. case 'ucs-2':
  3892. case 'utf16le':
  3893. case 'utf-16le':
  3894. return len * 2
  3895. case 'hex':
  3896. return len >>> 1
  3897. case 'base64':
  3898. return base64ToBytes(string).length
  3899. default:
  3900. if (loweredCase) {
  3901. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  3902. }
  3903. encoding = ('' + encoding).toLowerCase()
  3904. loweredCase = true
  3905. }
  3906. }
  3907. }
  3908. Buffer.byteLength = byteLength
  3909. function slowToString (encoding, start, end) {
  3910. var loweredCase = false
  3911. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  3912. // property of a typed array.
  3913. // This behaves neither like String nor Uint8Array in that we set start/end
  3914. // to their upper/lower bounds if the value passed is out of range.
  3915. // undefined is handled specially as per ECMA-262 6th Edition,
  3916. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  3917. if (start === undefined || start < 0) {
  3918. start = 0
  3919. }
  3920. // Return early if start > this.length. Done here to prevent potential uint32
  3921. // coercion fail below.
  3922. if (start > this.length) {
  3923. return ''
  3924. }
  3925. if (end === undefined || end > this.length) {
  3926. end = this.length
  3927. }
  3928. if (end <= 0) {
  3929. return ''
  3930. }
  3931. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  3932. end >>>= 0
  3933. start >>>= 0
  3934. if (end <= start) {
  3935. return ''
  3936. }
  3937. if (!encoding) encoding = 'utf8'
  3938. while (true) {
  3939. switch (encoding) {
  3940. case 'hex':
  3941. return hexSlice(this, start, end)
  3942. case 'utf8':
  3943. case 'utf-8':
  3944. return utf8Slice(this, start, end)
  3945. case 'ascii':
  3946. return asciiSlice(this, start, end)
  3947. case 'latin1':
  3948. case 'binary':
  3949. return latin1Slice(this, start, end)
  3950. case 'base64':
  3951. return base64Slice(this, start, end)
  3952. case 'ucs2':
  3953. case 'ucs-2':
  3954. case 'utf16le':
  3955. case 'utf-16le':
  3956. return utf16leSlice(this, start, end)
  3957. default:
  3958. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3959. encoding = (encoding + '').toLowerCase()
  3960. loweredCase = true
  3961. }
  3962. }
  3963. }
  3964. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  3965. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  3966. // reliably in a browserify context because there could be multiple different
  3967. // copies of the 'buffer' package in use. This method works even for Buffer
  3968. // instances that were created from another copy of the `buffer` package.
  3969. // See: https://github.com/feross/buffer/issues/154
  3970. Buffer.prototype._isBuffer = true
  3971. function swap (b, n, m) {
  3972. var i = b[n]
  3973. b[n] = b[m]
  3974. b[m] = i
  3975. }
  3976. Buffer.prototype.swap16 = function swap16 () {
  3977. var len = this.length
  3978. if (len % 2 !== 0) {
  3979. throw new RangeError('Buffer size must be a multiple of 16-bits')
  3980. }
  3981. for (var i = 0; i < len; i += 2) {
  3982. swap(this, i, i + 1)
  3983. }
  3984. return this
  3985. }
  3986. Buffer.prototype.swap32 = function swap32 () {
  3987. var len = this.length
  3988. if (len % 4 !== 0) {
  3989. throw new RangeError('Buffer size must be a multiple of 32-bits')
  3990. }
  3991. for (var i = 0; i < len; i += 4) {
  3992. swap(this, i, i + 3)
  3993. swap(this, i + 1, i + 2)
  3994. }
  3995. return this
  3996. }
  3997. Buffer.prototype.swap64 = function swap64 () {
  3998. var len = this.length
  3999. if (len % 8 !== 0) {
  4000. throw new RangeError('Buffer size must be a multiple of 64-bits')
  4001. }
  4002. for (var i = 0; i < len; i += 8) {
  4003. swap(this, i, i + 7)
  4004. swap(this, i + 1, i + 6)
  4005. swap(this, i + 2, i + 5)
  4006. swap(this, i + 3, i + 4)
  4007. }
  4008. return this
  4009. }
  4010. Buffer.prototype.toString = function toString () {
  4011. var length = this.length
  4012. if (length === 0) return ''
  4013. if (arguments.length === 0) return utf8Slice(this, 0, length)
  4014. return slowToString.apply(this, arguments)
  4015. }
  4016. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  4017. Buffer.prototype.equals = function equals (b) {
  4018. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  4019. if (this === b) return true
  4020. return Buffer.compare(this, b) === 0
  4021. }
  4022. Buffer.prototype.inspect = function inspect () {
  4023. var str = ''
  4024. var max = exports.INSPECT_MAX_BYTES
  4025. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  4026. if (this.length > max) str += ' ... '
  4027. return '<Buffer ' + str + '>'
  4028. }
  4029. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  4030. if (isInstance(target, Uint8Array)) {
  4031. target = Buffer.from(target, target.offset, target.byteLength)
  4032. }
  4033. if (!Buffer.isBuffer(target)) {
  4034. throw new TypeError(
  4035. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  4036. 'Received type ' + (typeof target)
  4037. )
  4038. }
  4039. if (start === undefined) {
  4040. start = 0
  4041. }
  4042. if (end === undefined) {
  4043. end = target ? target.length : 0
  4044. }
  4045. if (thisStart === undefined) {
  4046. thisStart = 0
  4047. }
  4048. if (thisEnd === undefined) {
  4049. thisEnd = this.length
  4050. }
  4051. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  4052. throw new RangeError('out of range index')
  4053. }
  4054. if (thisStart >= thisEnd && start >= end) {
  4055. return 0
  4056. }
  4057. if (thisStart >= thisEnd) {
  4058. return -1
  4059. }
  4060. if (start >= end) {
  4061. return 1
  4062. }
  4063. start >>>= 0
  4064. end >>>= 0
  4065. thisStart >>>= 0
  4066. thisEnd >>>= 0
  4067. if (this === target) return 0
  4068. var x = thisEnd - thisStart
  4069. var y = end - start
  4070. var len = Math.min(x, y)
  4071. var thisCopy = this.slice(thisStart, thisEnd)
  4072. var targetCopy = target.slice(start, end)
  4073. for (var i = 0; i < len; ++i) {
  4074. if (thisCopy[i] !== targetCopy[i]) {
  4075. x = thisCopy[i]
  4076. y = targetCopy[i]
  4077. break
  4078. }
  4079. }
  4080. if (x < y) return -1
  4081. if (y < x) return 1
  4082. return 0
  4083. }
  4084. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  4085. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  4086. //
  4087. // Arguments:
  4088. // - buffer - a Buffer to search
  4089. // - val - a string, Buffer, or number
  4090. // - byteOffset - an index into `buffer`; will be clamped to an int32
  4091. // - encoding - an optional encoding, relevant is val is a string
  4092. // - dir - true for indexOf, false for lastIndexOf
  4093. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  4094. // Empty buffer means no match
  4095. if (buffer.length === 0) return -1
  4096. // Normalize byteOffset
  4097. if (typeof byteOffset === 'string') {
  4098. encoding = byteOffset
  4099. byteOffset = 0
  4100. } else if (byteOffset > 0x7fffffff) {
  4101. byteOffset = 0x7fffffff
  4102. } else if (byteOffset < -0x80000000) {
  4103. byteOffset = -0x80000000
  4104. }
  4105. byteOffset = +byteOffset // Coerce to Number.
  4106. if (numberIsNaN(byteOffset)) {
  4107. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  4108. byteOffset = dir ? 0 : (buffer.length - 1)
  4109. }
  4110. // Normalize byteOffset: negative offsets start from the end of the buffer
  4111. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  4112. if (byteOffset >= buffer.length) {
  4113. if (dir) return -1
  4114. else byteOffset = buffer.length - 1
  4115. } else if (byteOffset < 0) {
  4116. if (dir) byteOffset = 0
  4117. else return -1
  4118. }
  4119. // Normalize val
  4120. if (typeof val === 'string') {
  4121. val = Buffer.from(val, encoding)
  4122. }
  4123. // Finally, search either indexOf (if dir is true) or lastIndexOf
  4124. if (Buffer.isBuffer(val)) {
  4125. // Special case: looking for empty string/buffer always fails
  4126. if (val.length === 0) {
  4127. return -1
  4128. }
  4129. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  4130. } else if (typeof val === 'number') {
  4131. val = val & 0xFF // Search for a byte value [0-255]
  4132. if (typeof Uint8Array.prototype.indexOf === 'function') {
  4133. if (dir) {
  4134. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  4135. } else {
  4136. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  4137. }
  4138. }
  4139. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  4140. }
  4141. throw new TypeError('val must be string, number or Buffer')
  4142. }
  4143. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  4144. var indexSize = 1
  4145. var arrLength = arr.length
  4146. var valLength = val.length
  4147. if (encoding !== undefined) {
  4148. encoding = String(encoding).toLowerCase()
  4149. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  4150. encoding === 'utf16le' || encoding === 'utf-16le') {
  4151. if (arr.length < 2 || val.length < 2) {
  4152. return -1
  4153. }
  4154. indexSize = 2
  4155. arrLength /= 2
  4156. valLength /= 2
  4157. byteOffset /= 2
  4158. }
  4159. }
  4160. function read (buf, i) {
  4161. if (indexSize === 1) {
  4162. return buf[i]
  4163. } else {
  4164. return buf.readUInt16BE(i * indexSize)
  4165. }
  4166. }
  4167. var i
  4168. if (dir) {
  4169. var foundIndex = -1
  4170. for (i = byteOffset; i < arrLength; i++) {
  4171. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  4172. if (foundIndex === -1) foundIndex = i
  4173. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  4174. } else {
  4175. if (foundIndex !== -1) i -= i - foundIndex
  4176. foundIndex = -1
  4177. }
  4178. }
  4179. } else {
  4180. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  4181. for (i = byteOffset; i >= 0; i--) {
  4182. var found = true
  4183. for (var j = 0; j < valLength; j++) {
  4184. if (read(arr, i + j) !== read(val, j)) {
  4185. found = false
  4186. break
  4187. }
  4188. }
  4189. if (found) return i
  4190. }
  4191. }
  4192. return -1
  4193. }
  4194. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  4195. return this.indexOf(val, byteOffset, encoding) !== -1
  4196. }
  4197. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  4198. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  4199. }
  4200. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  4201. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  4202. }
  4203. function hexWrite (buf, string, offset, length) {
  4204. offset = Number(offset) || 0
  4205. var remaining = buf.length - offset
  4206. if (!length) {
  4207. length = remaining
  4208. } else {
  4209. length = Number(length)
  4210. if (length > remaining) {
  4211. length = remaining
  4212. }
  4213. }
  4214. var strLen = string.length
  4215. if (length > strLen / 2) {
  4216. length = strLen / 2
  4217. }
  4218. for (var i = 0; i < length; ++i) {
  4219. var parsed = parseInt(string.substr(i * 2, 2), 16)
  4220. if (numberIsNaN(parsed)) return i
  4221. buf[offset + i] = parsed
  4222. }
  4223. return i
  4224. }
  4225. function utf8Write (buf, string, offset, length) {
  4226. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  4227. }
  4228. function asciiWrite (buf, string, offset, length) {
  4229. return blitBuffer(asciiToBytes(string), buf, offset, length)
  4230. }
  4231. function latin1Write (buf, string, offset, length) {
  4232. return asciiWrite(buf, string, offset, length)
  4233. }
  4234. function base64Write (buf, string, offset, length) {
  4235. return blitBuffer(base64ToBytes(string), buf, offset, length)
  4236. }
  4237. function ucs2Write (buf, string, offset, length) {
  4238. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  4239. }
  4240. Buffer.prototype.write = function write (string, offset, length, encoding) {
  4241. // Buffer#write(string)
  4242. if (offset === undefined) {
  4243. encoding = 'utf8'
  4244. length = this.length
  4245. offset = 0
  4246. // Buffer#write(string, encoding)
  4247. } else if (length === undefined && typeof offset === 'string') {
  4248. encoding = offset
  4249. length = this.length
  4250. offset = 0
  4251. // Buffer#write(string, offset[, length][, encoding])
  4252. } else if (isFinite(offset)) {
  4253. offset = offset >>> 0
  4254. if (isFinite(length)) {
  4255. length = length >>> 0
  4256. if (encoding === undefined) encoding = 'utf8'
  4257. } else {
  4258. encoding = length
  4259. length = undefined
  4260. }
  4261. } else {
  4262. throw new Error(
  4263. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  4264. )
  4265. }
  4266. var remaining = this.length - offset
  4267. if (length === undefined || length > remaining) length = remaining
  4268. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  4269. throw new RangeError('Attempt to write outside buffer bounds')
  4270. }
  4271. if (!encoding) encoding = 'utf8'
  4272. var loweredCase = false
  4273. for (;;) {
  4274. switch (encoding) {
  4275. case 'hex':
  4276. return hexWrite(this, string, offset, length)
  4277. case 'utf8':
  4278. case 'utf-8':
  4279. return utf8Write(this, string, offset, length)
  4280. case 'ascii':
  4281. return asciiWrite(this, string, offset, length)
  4282. case 'latin1':
  4283. case 'binary':
  4284. return latin1Write(this, string, offset, length)
  4285. case 'base64':
  4286. // Warning: maxLength not taken into account in base64Write
  4287. return base64Write(this, string, offset, length)
  4288. case 'ucs2':
  4289. case 'ucs-2':
  4290. case 'utf16le':
  4291. case 'utf-16le':
  4292. return ucs2Write(this, string, offset, length)
  4293. default:
  4294. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  4295. encoding = ('' + encoding).toLowerCase()
  4296. loweredCase = true
  4297. }
  4298. }
  4299. }
  4300. Buffer.prototype.toJSON = function toJSON () {
  4301. return {
  4302. type: 'Buffer',
  4303. data: Array.prototype.slice.call(this._arr || this, 0)
  4304. }
  4305. }
  4306. function base64Slice (buf, start, end) {
  4307. if (start === 0 && end === buf.length) {
  4308. return base64.fromByteArray(buf)
  4309. } else {
  4310. return base64.fromByteArray(buf.slice(start, end))
  4311. }
  4312. }
  4313. function utf8Slice (buf, start, end) {
  4314. end = Math.min(buf.length, end)
  4315. var res = []
  4316. var i = start
  4317. while (i < end) {
  4318. var firstByte = buf[i]
  4319. var codePoint = null
  4320. var bytesPerSequence = (firstByte > 0xEF) ? 4
  4321. : (firstByte > 0xDF) ? 3
  4322. : (firstByte > 0xBF) ? 2
  4323. : 1
  4324. if (i + bytesPerSequence <= end) {
  4325. var secondByte, thirdByte, fourthByte, tempCodePoint
  4326. switch (bytesPerSequence) {
  4327. case 1:
  4328. if (firstByte < 0x80) {
  4329. codePoint = firstByte
  4330. }
  4331. break
  4332. case 2:
  4333. secondByte = buf[i + 1]
  4334. if ((secondByte & 0xC0) === 0x80) {
  4335. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  4336. if (tempCodePoint > 0x7F) {
  4337. codePoint = tempCodePoint
  4338. }
  4339. }
  4340. break
  4341. case 3:
  4342. secondByte = buf[i + 1]
  4343. thirdByte = buf[i + 2]
  4344. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  4345. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  4346. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  4347. codePoint = tempCodePoint
  4348. }
  4349. }
  4350. break
  4351. case 4:
  4352. secondByte = buf[i + 1]
  4353. thirdByte = buf[i + 2]
  4354. fourthByte = buf[i + 3]
  4355. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  4356. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  4357. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  4358. codePoint = tempCodePoint
  4359. }
  4360. }
  4361. }
  4362. }
  4363. if (codePoint === null) {
  4364. // we did not generate a valid codePoint so insert a
  4365. // replacement char (U+FFFD) and advance only 1 byte
  4366. codePoint = 0xFFFD
  4367. bytesPerSequence = 1
  4368. } else if (codePoint > 0xFFFF) {
  4369. // encode to utf16 (surrogate pair dance)
  4370. codePoint -= 0x10000
  4371. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  4372. codePoint = 0xDC00 | codePoint & 0x3FF
  4373. }
  4374. res.push(codePoint)
  4375. i += bytesPerSequence
  4376. }
  4377. return decodeCodePointsArray(res)
  4378. }
  4379. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  4380. // the lowest limit is Chrome, with 0x10000 args.
  4381. // We go 1 magnitude less, for safety
  4382. var MAX_ARGUMENTS_LENGTH = 0x1000
  4383. function decodeCodePointsArray (codePoints) {
  4384. var len = codePoints.length
  4385. if (len <= MAX_ARGUMENTS_LENGTH) {
  4386. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  4387. }
  4388. // Decode in chunks to avoid "call stack size exceeded".
  4389. var res = ''
  4390. var i = 0
  4391. while (i < len) {
  4392. res += String.fromCharCode.apply(
  4393. String,
  4394. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  4395. )
  4396. }
  4397. return res
  4398. }
  4399. function asciiSlice (buf, start, end) {
  4400. var ret = ''
  4401. end = Math.min(buf.length, end)
  4402. for (var i = start; i < end; ++i) {
  4403. ret += String.fromCharCode(buf[i] & 0x7F)
  4404. }
  4405. return ret
  4406. }
  4407. function latin1Slice (buf, start, end) {
  4408. var ret = ''
  4409. end = Math.min(buf.length, end)
  4410. for (var i = start; i < end; ++i) {
  4411. ret += String.fromCharCode(buf[i])
  4412. }
  4413. return ret
  4414. }
  4415. function hexSlice (buf, start, end) {
  4416. var len = buf.length
  4417. if (!start || start < 0) start = 0
  4418. if (!end || end < 0 || end > len) end = len
  4419. var out = ''
  4420. for (var i = start; i < end; ++i) {
  4421. out += toHex(buf[i])
  4422. }
  4423. return out
  4424. }
  4425. function utf16leSlice (buf, start, end) {
  4426. var bytes = buf.slice(start, end)
  4427. var res = ''
  4428. for (var i = 0; i < bytes.length; i += 2) {
  4429. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  4430. }
  4431. return res
  4432. }
  4433. Buffer.prototype.slice = function slice (start, end) {
  4434. var len = this.length
  4435. start = ~~start
  4436. end = end === undefined ? len : ~~end
  4437. if (start < 0) {
  4438. start += len
  4439. if (start < 0) start = 0
  4440. } else if (start > len) {
  4441. start = len
  4442. }
  4443. if (end < 0) {
  4444. end += len
  4445. if (end < 0) end = 0
  4446. } else if (end > len) {
  4447. end = len
  4448. }
  4449. if (end < start) end = start
  4450. var newBuf = this.subarray(start, end)
  4451. // Return an augmented `Uint8Array` instance
  4452. newBuf.__proto__ = Buffer.prototype
  4453. return newBuf
  4454. }
  4455. /*
  4456. * Need to make sure that buffer isn't trying to write out of bounds.
  4457. */
  4458. function checkOffset (offset, ext, length) {
  4459. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  4460. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  4461. }
  4462. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  4463. offset = offset >>> 0
  4464. byteLength = byteLength >>> 0
  4465. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4466. var val = this[offset]
  4467. var mul = 1
  4468. var i = 0
  4469. while (++i < byteLength && (mul *= 0x100)) {
  4470. val += this[offset + i] * mul
  4471. }
  4472. return val
  4473. }
  4474. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  4475. offset = offset >>> 0
  4476. byteLength = byteLength >>> 0
  4477. if (!noAssert) {
  4478. checkOffset(offset, byteLength, this.length)
  4479. }
  4480. var val = this[offset + --byteLength]
  4481. var mul = 1
  4482. while (byteLength > 0 && (mul *= 0x100)) {
  4483. val += this[offset + --byteLength] * mul
  4484. }
  4485. return val
  4486. }
  4487. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  4488. offset = offset >>> 0
  4489. if (!noAssert) checkOffset(offset, 1, this.length)
  4490. return this[offset]
  4491. }
  4492. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  4493. offset = offset >>> 0
  4494. if (!noAssert) checkOffset(offset, 2, this.length)
  4495. return this[offset] | (this[offset + 1] << 8)
  4496. }
  4497. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  4498. offset = offset >>> 0
  4499. if (!noAssert) checkOffset(offset, 2, this.length)
  4500. return (this[offset] << 8) | this[offset + 1]
  4501. }
  4502. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  4503. offset = offset >>> 0
  4504. if (!noAssert) checkOffset(offset, 4, this.length)
  4505. return ((this[offset]) |
  4506. (this[offset + 1] << 8) |
  4507. (this[offset + 2] << 16)) +
  4508. (this[offset + 3] * 0x1000000)
  4509. }
  4510. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  4511. offset = offset >>> 0
  4512. if (!noAssert) checkOffset(offset, 4, this.length)
  4513. return (this[offset] * 0x1000000) +
  4514. ((this[offset + 1] << 16) |
  4515. (this[offset + 2] << 8) |
  4516. this[offset + 3])
  4517. }
  4518. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  4519. offset = offset >>> 0
  4520. byteLength = byteLength >>> 0
  4521. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4522. var val = this[offset]
  4523. var mul = 1
  4524. var i = 0
  4525. while (++i < byteLength && (mul *= 0x100)) {
  4526. val += this[offset + i] * mul
  4527. }
  4528. mul *= 0x80
  4529. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4530. return val
  4531. }
  4532. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  4533. offset = offset >>> 0
  4534. byteLength = byteLength >>> 0
  4535. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4536. var i = byteLength
  4537. var mul = 1
  4538. var val = this[offset + --i]
  4539. while (i > 0 && (mul *= 0x100)) {
  4540. val += this[offset + --i] * mul
  4541. }
  4542. mul *= 0x80
  4543. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4544. return val
  4545. }
  4546. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  4547. offset = offset >>> 0
  4548. if (!noAssert) checkOffset(offset, 1, this.length)
  4549. if (!(this[offset] & 0x80)) return (this[offset])
  4550. return ((0xff - this[offset] + 1) * -1)
  4551. }
  4552. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  4553. offset = offset >>> 0
  4554. if (!noAssert) checkOffset(offset, 2, this.length)
  4555. var val = this[offset] | (this[offset + 1] << 8)
  4556. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4557. }
  4558. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  4559. offset = offset >>> 0
  4560. if (!noAssert) checkOffset(offset, 2, this.length)
  4561. var val = this[offset + 1] | (this[offset] << 8)
  4562. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4563. }
  4564. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  4565. offset = offset >>> 0
  4566. if (!noAssert) checkOffset(offset, 4, this.length)
  4567. return (this[offset]) |
  4568. (this[offset + 1] << 8) |
  4569. (this[offset + 2] << 16) |
  4570. (this[offset + 3] << 24)
  4571. }
  4572. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  4573. offset = offset >>> 0
  4574. if (!noAssert) checkOffset(offset, 4, this.length)
  4575. return (this[offset] << 24) |
  4576. (this[offset + 1] << 16) |
  4577. (this[offset + 2] << 8) |
  4578. (this[offset + 3])
  4579. }
  4580. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  4581. offset = offset >>> 0
  4582. if (!noAssert) checkOffset(offset, 4, this.length)
  4583. return ieee754.read(this, offset, true, 23, 4)
  4584. }
  4585. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  4586. offset = offset >>> 0
  4587. if (!noAssert) checkOffset(offset, 4, this.length)
  4588. return ieee754.read(this, offset, false, 23, 4)
  4589. }
  4590. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  4591. offset = offset >>> 0
  4592. if (!noAssert) checkOffset(offset, 8, this.length)
  4593. return ieee754.read(this, offset, true, 52, 8)
  4594. }
  4595. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  4596. offset = offset >>> 0
  4597. if (!noAssert) checkOffset(offset, 8, this.length)
  4598. return ieee754.read(this, offset, false, 52, 8)
  4599. }
  4600. function checkInt (buf, value, offset, ext, max, min) {
  4601. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  4602. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  4603. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4604. }
  4605. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  4606. value = +value
  4607. offset = offset >>> 0
  4608. byteLength = byteLength >>> 0
  4609. if (!noAssert) {
  4610. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4611. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4612. }
  4613. var mul = 1
  4614. var i = 0
  4615. this[offset] = value & 0xFF
  4616. while (++i < byteLength && (mul *= 0x100)) {
  4617. this[offset + i] = (value / mul) & 0xFF
  4618. }
  4619. return offset + byteLength
  4620. }
  4621. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  4622. value = +value
  4623. offset = offset >>> 0
  4624. byteLength = byteLength >>> 0
  4625. if (!noAssert) {
  4626. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4627. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4628. }
  4629. var i = byteLength - 1
  4630. var mul = 1
  4631. this[offset + i] = value & 0xFF
  4632. while (--i >= 0 && (mul *= 0x100)) {
  4633. this[offset + i] = (value / mul) & 0xFF
  4634. }
  4635. return offset + byteLength
  4636. }
  4637. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  4638. value = +value
  4639. offset = offset >>> 0
  4640. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  4641. this[offset] = (value & 0xff)
  4642. return offset + 1
  4643. }
  4644. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  4645. value = +value
  4646. offset = offset >>> 0
  4647. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4648. this[offset] = (value & 0xff)
  4649. this[offset + 1] = (value >>> 8)
  4650. return offset + 2
  4651. }
  4652. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  4653. value = +value
  4654. offset = offset >>> 0
  4655. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4656. this[offset] = (value >>> 8)
  4657. this[offset + 1] = (value & 0xff)
  4658. return offset + 2
  4659. }
  4660. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  4661. value = +value
  4662. offset = offset >>> 0
  4663. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4664. this[offset + 3] = (value >>> 24)
  4665. this[offset + 2] = (value >>> 16)
  4666. this[offset + 1] = (value >>> 8)
  4667. this[offset] = (value & 0xff)
  4668. return offset + 4
  4669. }
  4670. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  4671. value = +value
  4672. offset = offset >>> 0
  4673. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4674. this[offset] = (value >>> 24)
  4675. this[offset + 1] = (value >>> 16)
  4676. this[offset + 2] = (value >>> 8)
  4677. this[offset + 3] = (value & 0xff)
  4678. return offset + 4
  4679. }
  4680. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  4681. value = +value
  4682. offset = offset >>> 0
  4683. if (!noAssert) {
  4684. var limit = Math.pow(2, (8 * byteLength) - 1)
  4685. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4686. }
  4687. var i = 0
  4688. var mul = 1
  4689. var sub = 0
  4690. this[offset] = value & 0xFF
  4691. while (++i < byteLength && (mul *= 0x100)) {
  4692. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  4693. sub = 1
  4694. }
  4695. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4696. }
  4697. return offset + byteLength
  4698. }
  4699. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  4700. value = +value
  4701. offset = offset >>> 0
  4702. if (!noAssert) {
  4703. var limit = Math.pow(2, (8 * byteLength) - 1)
  4704. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4705. }
  4706. var i = byteLength - 1
  4707. var mul = 1
  4708. var sub = 0
  4709. this[offset + i] = value & 0xFF
  4710. while (--i >= 0 && (mul *= 0x100)) {
  4711. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  4712. sub = 1
  4713. }
  4714. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4715. }
  4716. return offset + byteLength
  4717. }
  4718. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  4719. value = +value
  4720. offset = offset >>> 0
  4721. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  4722. if (value < 0) value = 0xff + value + 1
  4723. this[offset] = (value & 0xff)
  4724. return offset + 1
  4725. }
  4726. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  4727. value = +value
  4728. offset = offset >>> 0
  4729. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4730. this[offset] = (value & 0xff)
  4731. this[offset + 1] = (value >>> 8)
  4732. return offset + 2
  4733. }
  4734. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  4735. value = +value
  4736. offset = offset >>> 0
  4737. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4738. this[offset] = (value >>> 8)
  4739. this[offset + 1] = (value & 0xff)
  4740. return offset + 2
  4741. }
  4742. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  4743. value = +value
  4744. offset = offset >>> 0
  4745. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4746. this[offset] = (value & 0xff)
  4747. this[offset + 1] = (value >>> 8)
  4748. this[offset + 2] = (value >>> 16)
  4749. this[offset + 3] = (value >>> 24)
  4750. return offset + 4
  4751. }
  4752. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  4753. value = +value
  4754. offset = offset >>> 0
  4755. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4756. if (value < 0) value = 0xffffffff + value + 1
  4757. this[offset] = (value >>> 24)
  4758. this[offset + 1] = (value >>> 16)
  4759. this[offset + 2] = (value >>> 8)
  4760. this[offset + 3] = (value & 0xff)
  4761. return offset + 4
  4762. }
  4763. function checkIEEE754 (buf, value, offset, ext, max, min) {
  4764. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4765. if (offset < 0) throw new RangeError('Index out of range')
  4766. }
  4767. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  4768. value = +value
  4769. offset = offset >>> 0
  4770. if (!noAssert) {
  4771. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  4772. }
  4773. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  4774. return offset + 4
  4775. }
  4776. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  4777. return writeFloat(this, value, offset, true, noAssert)
  4778. }
  4779. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  4780. return writeFloat(this, value, offset, false, noAssert)
  4781. }
  4782. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  4783. value = +value
  4784. offset = offset >>> 0
  4785. if (!noAssert) {
  4786. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  4787. }
  4788. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  4789. return offset + 8
  4790. }
  4791. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  4792. return writeDouble(this, value, offset, true, noAssert)
  4793. }
  4794. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  4795. return writeDouble(this, value, offset, false, noAssert)
  4796. }
  4797. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  4798. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  4799. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  4800. if (!start) start = 0
  4801. if (!end && end !== 0) end = this.length
  4802. if (targetStart >= target.length) targetStart = target.length
  4803. if (!targetStart) targetStart = 0
  4804. if (end > 0 && end < start) end = start
  4805. // Copy 0 bytes; we're done
  4806. if (end === start) return 0
  4807. if (target.length === 0 || this.length === 0) return 0
  4808. // Fatal error conditions
  4809. if (targetStart < 0) {
  4810. throw new RangeError('targetStart out of bounds')
  4811. }
  4812. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  4813. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  4814. // Are we oob?
  4815. if (end > this.length) end = this.length
  4816. if (target.length - targetStart < end - start) {
  4817. end = target.length - targetStart + start
  4818. }
  4819. var len = end - start
  4820. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  4821. // Use built-in when available, missing from IE11
  4822. this.copyWithin(targetStart, start, end)
  4823. } else if (this === target && start < targetStart && targetStart < end) {
  4824. // descending copy from end
  4825. for (var i = len - 1; i >= 0; --i) {
  4826. target[i + targetStart] = this[i + start]
  4827. }
  4828. } else {
  4829. Uint8Array.prototype.set.call(
  4830. target,
  4831. this.subarray(start, end),
  4832. targetStart
  4833. )
  4834. }
  4835. return len
  4836. }
  4837. // Usage:
  4838. // buffer.fill(number[, offset[, end]])
  4839. // buffer.fill(buffer[, offset[, end]])
  4840. // buffer.fill(string[, offset[, end]][, encoding])
  4841. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  4842. // Handle string cases:
  4843. if (typeof val === 'string') {
  4844. if (typeof start === 'string') {
  4845. encoding = start
  4846. start = 0
  4847. end = this.length
  4848. } else if (typeof end === 'string') {
  4849. encoding = end
  4850. end = this.length
  4851. }
  4852. if (encoding !== undefined && typeof encoding !== 'string') {
  4853. throw new TypeError('encoding must be a string')
  4854. }
  4855. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  4856. throw new TypeError('Unknown encoding: ' + encoding)
  4857. }
  4858. if (val.length === 1) {
  4859. var code = val.charCodeAt(0)
  4860. if ((encoding === 'utf8' && code < 128) ||
  4861. encoding === 'latin1') {
  4862. // Fast path: If `val` fits into a single byte, use that numeric value.
  4863. val = code
  4864. }
  4865. }
  4866. } else if (typeof val === 'number') {
  4867. val = val & 255
  4868. }
  4869. // Invalid ranges are not set to a default, so can range check early.
  4870. if (start < 0 || this.length < start || this.length < end) {
  4871. throw new RangeError('Out of range index')
  4872. }
  4873. if (end <= start) {
  4874. return this
  4875. }
  4876. start = start >>> 0
  4877. end = end === undefined ? this.length : end >>> 0
  4878. if (!val) val = 0
  4879. var i
  4880. if (typeof val === 'number') {
  4881. for (i = start; i < end; ++i) {
  4882. this[i] = val
  4883. }
  4884. } else {
  4885. var bytes = Buffer.isBuffer(val)
  4886. ? val
  4887. : Buffer.from(val, encoding)
  4888. var len = bytes.length
  4889. if (len === 0) {
  4890. throw new TypeError('The value "' + val +
  4891. '" is invalid for argument "value"')
  4892. }
  4893. for (i = 0; i < end - start; ++i) {
  4894. this[i + start] = bytes[i % len]
  4895. }
  4896. }
  4897. return this
  4898. }
  4899. // HELPER FUNCTIONS
  4900. // ================
  4901. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  4902. function base64clean (str) {
  4903. // Node takes equal signs as end of the Base64 encoding
  4904. str = str.split('=')[0]
  4905. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  4906. str = str.trim().replace(INVALID_BASE64_RE, '')
  4907. // Node converts strings with length < 2 to ''
  4908. if (str.length < 2) return ''
  4909. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  4910. while (str.length % 4 !== 0) {
  4911. str = str + '='
  4912. }
  4913. return str
  4914. }
  4915. function toHex (n) {
  4916. if (n < 16) return '0' + n.toString(16)
  4917. return n.toString(16)
  4918. }
  4919. function utf8ToBytes (string, units) {
  4920. units = units || Infinity
  4921. var codePoint
  4922. var length = string.length
  4923. var leadSurrogate = null
  4924. var bytes = []
  4925. for (var i = 0; i < length; ++i) {
  4926. codePoint = string.charCodeAt(i)
  4927. // is surrogate component
  4928. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  4929. // last char was a lead
  4930. if (!leadSurrogate) {
  4931. // no lead yet
  4932. if (codePoint > 0xDBFF) {
  4933. // unexpected trail
  4934. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4935. continue
  4936. } else if (i + 1 === length) {
  4937. // unpaired lead
  4938. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4939. continue
  4940. }
  4941. // valid lead
  4942. leadSurrogate = codePoint
  4943. continue
  4944. }
  4945. // 2 leads in a row
  4946. if (codePoint < 0xDC00) {
  4947. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4948. leadSurrogate = codePoint
  4949. continue
  4950. }
  4951. // valid surrogate pair
  4952. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  4953. } else if (leadSurrogate) {
  4954. // valid bmp char, but last char was a lead
  4955. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4956. }
  4957. leadSurrogate = null
  4958. // encode utf8
  4959. if (codePoint < 0x80) {
  4960. if ((units -= 1) < 0) break
  4961. bytes.push(codePoint)
  4962. } else if (codePoint < 0x800) {
  4963. if ((units -= 2) < 0) break
  4964. bytes.push(
  4965. codePoint >> 0x6 | 0xC0,
  4966. codePoint & 0x3F | 0x80
  4967. )
  4968. } else if (codePoint < 0x10000) {
  4969. if ((units -= 3) < 0) break
  4970. bytes.push(
  4971. codePoint >> 0xC | 0xE0,
  4972. codePoint >> 0x6 & 0x3F | 0x80,
  4973. codePoint & 0x3F | 0x80
  4974. )
  4975. } else if (codePoint < 0x110000) {
  4976. if ((units -= 4) < 0) break
  4977. bytes.push(
  4978. codePoint >> 0x12 | 0xF0,
  4979. codePoint >> 0xC & 0x3F | 0x80,
  4980. codePoint >> 0x6 & 0x3F | 0x80,
  4981. codePoint & 0x3F | 0x80
  4982. )
  4983. } else {
  4984. throw new Error('Invalid code point')
  4985. }
  4986. }
  4987. return bytes
  4988. }
  4989. function asciiToBytes (str) {
  4990. var byteArray = []
  4991. for (var i = 0; i < str.length; ++i) {
  4992. // Node's code seems to be doing this and not & 0x7F..
  4993. byteArray.push(str.charCodeAt(i) & 0xFF)
  4994. }
  4995. return byteArray
  4996. }
  4997. function utf16leToBytes (str, units) {
  4998. var c, hi, lo
  4999. var byteArray = []
  5000. for (var i = 0; i < str.length; ++i) {
  5001. if ((units -= 2) < 0) break
  5002. c = str.charCodeAt(i)
  5003. hi = c >> 8
  5004. lo = c % 256
  5005. byteArray.push(lo)
  5006. byteArray.push(hi)
  5007. }
  5008. return byteArray
  5009. }
  5010. function base64ToBytes (str) {
  5011. return base64.toByteArray(base64clean(str))
  5012. }
  5013. function blitBuffer (src, dst, offset, length) {
  5014. for (var i = 0; i < length; ++i) {
  5015. if ((i + offset >= dst.length) || (i >= src.length)) break
  5016. dst[i + offset] = src[i]
  5017. }
  5018. return i
  5019. }
  5020. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  5021. // the `instanceof` check but they should be treated as of that type.
  5022. // See: https://github.com/feross/buffer/issues/166
  5023. function isInstance (obj, type) {
  5024. return obj instanceof type ||
  5025. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  5026. obj.constructor.name === type.name)
  5027. }
  5028. function numberIsNaN (obj) {
  5029. // For IE11 support
  5030. return obj !== obj // eslint-disable-line no-self-compare
  5031. }
  5032. },{"base64-js":24,"ieee754":31}],29:[function(require,module,exports){
  5033. (function (Buffer){
  5034. // Copyright Joyent, Inc. and other Node contributors.
  5035. //
  5036. // Permission is hereby granted, free of charge, to any person obtaining a
  5037. // copy of this software and associated documentation files (the
  5038. // "Software"), to deal in the Software without restriction, including
  5039. // without limitation the rights to use, copy, modify, merge, publish,
  5040. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5041. // persons to whom the Software is furnished to do so, subject to the
  5042. // following conditions:
  5043. //
  5044. // The above copyright notice and this permission notice shall be included
  5045. // in all copies or substantial portions of the Software.
  5046. //
  5047. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5048. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5049. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5050. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5051. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5052. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5053. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5054. // NOTE: These type checking functions intentionally don't use `instanceof`
  5055. // because it is fragile and can be easily faked with `Object.create()`.
  5056. function isArray(arg) {
  5057. if (Array.isArray) {
  5058. return Array.isArray(arg);
  5059. }
  5060. return objectToString(arg) === '[object Array]';
  5061. }
  5062. exports.isArray = isArray;
  5063. function isBoolean(arg) {
  5064. return typeof arg === 'boolean';
  5065. }
  5066. exports.isBoolean = isBoolean;
  5067. function isNull(arg) {
  5068. return arg === null;
  5069. }
  5070. exports.isNull = isNull;
  5071. function isNullOrUndefined(arg) {
  5072. return arg == null;
  5073. }
  5074. exports.isNullOrUndefined = isNullOrUndefined;
  5075. function isNumber(arg) {
  5076. return typeof arg === 'number';
  5077. }
  5078. exports.isNumber = isNumber;
  5079. function isString(arg) {
  5080. return typeof arg === 'string';
  5081. }
  5082. exports.isString = isString;
  5083. function isSymbol(arg) {
  5084. return typeof arg === 'symbol';
  5085. }
  5086. exports.isSymbol = isSymbol;
  5087. function isUndefined(arg) {
  5088. return arg === void 0;
  5089. }
  5090. exports.isUndefined = isUndefined;
  5091. function isRegExp(re) {
  5092. return objectToString(re) === '[object RegExp]';
  5093. }
  5094. exports.isRegExp = isRegExp;
  5095. function isObject(arg) {
  5096. return typeof arg === 'object' && arg !== null;
  5097. }
  5098. exports.isObject = isObject;
  5099. function isDate(d) {
  5100. return objectToString(d) === '[object Date]';
  5101. }
  5102. exports.isDate = isDate;
  5103. function isError(e) {
  5104. return (objectToString(e) === '[object Error]' || e instanceof Error);
  5105. }
  5106. exports.isError = isError;
  5107. function isFunction(arg) {
  5108. return typeof arg === 'function';
  5109. }
  5110. exports.isFunction = isFunction;
  5111. function isPrimitive(arg) {
  5112. return arg === null ||
  5113. typeof arg === 'boolean' ||
  5114. typeof arg === 'number' ||
  5115. typeof arg === 'string' ||
  5116. typeof arg === 'symbol' || // ES6 symbol
  5117. typeof arg === 'undefined';
  5118. }
  5119. exports.isPrimitive = isPrimitive;
  5120. exports.isBuffer = Buffer.isBuffer;
  5121. function objectToString(o) {
  5122. return Object.prototype.toString.call(o);
  5123. }
  5124. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  5125. },{"../../is-buffer/index.js":33}],30:[function(require,module,exports){
  5126. // Copyright Joyent, Inc. and other Node contributors.
  5127. //
  5128. // Permission is hereby granted, free of charge, to any person obtaining a
  5129. // copy of this software and associated documentation files (the
  5130. // "Software"), to deal in the Software without restriction, including
  5131. // without limitation the rights to use, copy, modify, merge, publish,
  5132. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5133. // persons to whom the Software is furnished to do so, subject to the
  5134. // following conditions:
  5135. //
  5136. // The above copyright notice and this permission notice shall be included
  5137. // in all copies or substantial portions of the Software.
  5138. //
  5139. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5140. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5141. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5142. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5143. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5144. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5145. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5146. var objectCreate = Object.create || objectCreatePolyfill
  5147. var objectKeys = Object.keys || objectKeysPolyfill
  5148. var bind = Function.prototype.bind || functionBindPolyfill
  5149. function EventEmitter() {
  5150. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  5151. this._events = objectCreate(null);
  5152. this._eventsCount = 0;
  5153. }
  5154. this._maxListeners = this._maxListeners || undefined;
  5155. }
  5156. module.exports = EventEmitter;
  5157. // Backwards-compat with node 0.10.x
  5158. EventEmitter.EventEmitter = EventEmitter;
  5159. EventEmitter.prototype._events = undefined;
  5160. EventEmitter.prototype._maxListeners = undefined;
  5161. // By default EventEmitters will print a warning if more than 10 listeners are
  5162. // added to it. This is a useful default which helps finding memory leaks.
  5163. var defaultMaxListeners = 10;
  5164. var hasDefineProperty;
  5165. try {
  5166. var o = {};
  5167. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  5168. hasDefineProperty = o.x === 0;
  5169. } catch (err) { hasDefineProperty = false }
  5170. if (hasDefineProperty) {
  5171. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  5172. enumerable: true,
  5173. get: function() {
  5174. return defaultMaxListeners;
  5175. },
  5176. set: function(arg) {
  5177. // check whether the input is a positive number (whose value is zero or
  5178. // greater and not a NaN).
  5179. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  5180. throw new TypeError('"defaultMaxListeners" must be a positive number');
  5181. defaultMaxListeners = arg;
  5182. }
  5183. });
  5184. } else {
  5185. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  5186. }
  5187. // Obviously not all Emitters should be limited to 10. This function allows
  5188. // that to be increased. Set to zero for unlimited.
  5189. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  5190. if (typeof n !== 'number' || n < 0 || isNaN(n))
  5191. throw new TypeError('"n" argument must be a positive number');
  5192. this._maxListeners = n;
  5193. return this;
  5194. };
  5195. function $getMaxListeners(that) {
  5196. if (that._maxListeners === undefined)
  5197. return EventEmitter.defaultMaxListeners;
  5198. return that._maxListeners;
  5199. }
  5200. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  5201. return $getMaxListeners(this);
  5202. };
  5203. // These standalone emit* functions are used to optimize calling of event
  5204. // handlers for fast cases because emit() itself often has a variable number of
  5205. // arguments and can be deoptimized because of that. These functions always have
  5206. // the same number of arguments and thus do not get deoptimized, so the code
  5207. // inside them can execute faster.
  5208. function emitNone(handler, isFn, self) {
  5209. if (isFn)
  5210. handler.call(self);
  5211. else {
  5212. var len = handler.length;
  5213. var listeners = arrayClone(handler, len);
  5214. for (var i = 0; i < len; ++i)
  5215. listeners[i].call(self);
  5216. }
  5217. }
  5218. function emitOne(handler, isFn, self, arg1) {
  5219. if (isFn)
  5220. handler.call(self, arg1);
  5221. else {
  5222. var len = handler.length;
  5223. var listeners = arrayClone(handler, len);
  5224. for (var i = 0; i < len; ++i)
  5225. listeners[i].call(self, arg1);
  5226. }
  5227. }
  5228. function emitTwo(handler, isFn, self, arg1, arg2) {
  5229. if (isFn)
  5230. handler.call(self, arg1, arg2);
  5231. else {
  5232. var len = handler.length;
  5233. var listeners = arrayClone(handler, len);
  5234. for (var i = 0; i < len; ++i)
  5235. listeners[i].call(self, arg1, arg2);
  5236. }
  5237. }
  5238. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  5239. if (isFn)
  5240. handler.call(self, arg1, arg2, arg3);
  5241. else {
  5242. var len = handler.length;
  5243. var listeners = arrayClone(handler, len);
  5244. for (var i = 0; i < len; ++i)
  5245. listeners[i].call(self, arg1, arg2, arg3);
  5246. }
  5247. }
  5248. function emitMany(handler, isFn, self, args) {
  5249. if (isFn)
  5250. handler.apply(self, args);
  5251. else {
  5252. var len = handler.length;
  5253. var listeners = arrayClone(handler, len);
  5254. for (var i = 0; i < len; ++i)
  5255. listeners[i].apply(self, args);
  5256. }
  5257. }
  5258. EventEmitter.prototype.emit = function emit(type) {
  5259. var er, handler, len, args, i, events;
  5260. var doError = (type === 'error');
  5261. events = this._events;
  5262. if (events)
  5263. doError = (doError && events.error == null);
  5264. else if (!doError)
  5265. return false;
  5266. // If there is no 'error' event listener then throw.
  5267. if (doError) {
  5268. if (arguments.length > 1)
  5269. er = arguments[1];
  5270. if (er instanceof Error) {
  5271. throw er; // Unhandled 'error' event
  5272. } else {
  5273. // At least give some kind of context to the user
  5274. var err = new Error('Unhandled "error" event. (' + er + ')');
  5275. err.context = er;
  5276. throw err;
  5277. }
  5278. return false;
  5279. }
  5280. handler = events[type];
  5281. if (!handler)
  5282. return false;
  5283. var isFn = typeof handler === 'function';
  5284. len = arguments.length;
  5285. switch (len) {
  5286. // fast cases
  5287. case 1:
  5288. emitNone(handler, isFn, this);
  5289. break;
  5290. case 2:
  5291. emitOne(handler, isFn, this, arguments[1]);
  5292. break;
  5293. case 3:
  5294. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  5295. break;
  5296. case 4:
  5297. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  5298. break;
  5299. // slower
  5300. default:
  5301. args = new Array(len - 1);
  5302. for (i = 1; i < len; i++)
  5303. args[i - 1] = arguments[i];
  5304. emitMany(handler, isFn, this, args);
  5305. }
  5306. return true;
  5307. };
  5308. function _addListener(target, type, listener, prepend) {
  5309. var m;
  5310. var events;
  5311. var existing;
  5312. if (typeof listener !== 'function')
  5313. throw new TypeError('"listener" argument must be a function');
  5314. events = target._events;
  5315. if (!events) {
  5316. events = target._events = objectCreate(null);
  5317. target._eventsCount = 0;
  5318. } else {
  5319. // To avoid recursion in the case that type === "newListener"! Before
  5320. // adding it to the listeners, first emit "newListener".
  5321. if (events.newListener) {
  5322. target.emit('newListener', type,
  5323. listener.listener ? listener.listener : listener);
  5324. // Re-assign `events` because a newListener handler could have caused the
  5325. // this._events to be assigned to a new object
  5326. events = target._events;
  5327. }
  5328. existing = events[type];
  5329. }
  5330. if (!existing) {
  5331. // Optimize the case of one listener. Don't need the extra array object.
  5332. existing = events[type] = listener;
  5333. ++target._eventsCount;
  5334. } else {
  5335. if (typeof existing === 'function') {
  5336. // Adding the second element, need to change to array.
  5337. existing = events[type] =
  5338. prepend ? [listener, existing] : [existing, listener];
  5339. } else {
  5340. // If we've already got an array, just append.
  5341. if (prepend) {
  5342. existing.unshift(listener);
  5343. } else {
  5344. existing.push(listener);
  5345. }
  5346. }
  5347. // Check for listener leak
  5348. if (!existing.warned) {
  5349. m = $getMaxListeners(target);
  5350. if (m && m > 0 && existing.length > m) {
  5351. existing.warned = true;
  5352. var w = new Error('Possible EventEmitter memory leak detected. ' +
  5353. existing.length + ' "' + String(type) + '" listeners ' +
  5354. 'added. Use emitter.setMaxListeners() to ' +
  5355. 'increase limit.');
  5356. w.name = 'MaxListenersExceededWarning';
  5357. w.emitter = target;
  5358. w.type = type;
  5359. w.count = existing.length;
  5360. if (typeof console === 'object' && console.warn) {
  5361. console.warn('%s: %s', w.name, w.message);
  5362. }
  5363. }
  5364. }
  5365. }
  5366. return target;
  5367. }
  5368. EventEmitter.prototype.addListener = function addListener(type, listener) {
  5369. return _addListener(this, type, listener, false);
  5370. };
  5371. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  5372. EventEmitter.prototype.prependListener =
  5373. function prependListener(type, listener) {
  5374. return _addListener(this, type, listener, true);
  5375. };
  5376. function onceWrapper() {
  5377. if (!this.fired) {
  5378. this.target.removeListener(this.type, this.wrapFn);
  5379. this.fired = true;
  5380. switch (arguments.length) {
  5381. case 0:
  5382. return this.listener.call(this.target);
  5383. case 1:
  5384. return this.listener.call(this.target, arguments[0]);
  5385. case 2:
  5386. return this.listener.call(this.target, arguments[0], arguments[1]);
  5387. case 3:
  5388. return this.listener.call(this.target, arguments[0], arguments[1],
  5389. arguments[2]);
  5390. default:
  5391. var args = new Array(arguments.length);
  5392. for (var i = 0; i < args.length; ++i)
  5393. args[i] = arguments[i];
  5394. this.listener.apply(this.target, args);
  5395. }
  5396. }
  5397. }
  5398. function _onceWrap(target, type, listener) {
  5399. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  5400. var wrapped = bind.call(onceWrapper, state);
  5401. wrapped.listener = listener;
  5402. state.wrapFn = wrapped;
  5403. return wrapped;
  5404. }
  5405. EventEmitter.prototype.once = function once(type, listener) {
  5406. if (typeof listener !== 'function')
  5407. throw new TypeError('"listener" argument must be a function');
  5408. this.on(type, _onceWrap(this, type, listener));
  5409. return this;
  5410. };
  5411. EventEmitter.prototype.prependOnceListener =
  5412. function prependOnceListener(type, listener) {
  5413. if (typeof listener !== 'function')
  5414. throw new TypeError('"listener" argument must be a function');
  5415. this.prependListener(type, _onceWrap(this, type, listener));
  5416. return this;
  5417. };
  5418. // Emits a 'removeListener' event if and only if the listener was removed.
  5419. EventEmitter.prototype.removeListener =
  5420. function removeListener(type, listener) {
  5421. var list, events, position, i, originalListener;
  5422. if (typeof listener !== 'function')
  5423. throw new TypeError('"listener" argument must be a function');
  5424. events = this._events;
  5425. if (!events)
  5426. return this;
  5427. list = events[type];
  5428. if (!list)
  5429. return this;
  5430. if (list === listener || list.listener === listener) {
  5431. if (--this._eventsCount === 0)
  5432. this._events = objectCreate(null);
  5433. else {
  5434. delete events[type];
  5435. if (events.removeListener)
  5436. this.emit('removeListener', type, list.listener || listener);
  5437. }
  5438. } else if (typeof list !== 'function') {
  5439. position = -1;
  5440. for (i = list.length - 1; i >= 0; i--) {
  5441. if (list[i] === listener || list[i].listener === listener) {
  5442. originalListener = list[i].listener;
  5443. position = i;
  5444. break;
  5445. }
  5446. }
  5447. if (position < 0)
  5448. return this;
  5449. if (position === 0)
  5450. list.shift();
  5451. else
  5452. spliceOne(list, position);
  5453. if (list.length === 1)
  5454. events[type] = list[0];
  5455. if (events.removeListener)
  5456. this.emit('removeListener', type, originalListener || listener);
  5457. }
  5458. return this;
  5459. };
  5460. EventEmitter.prototype.removeAllListeners =
  5461. function removeAllListeners(type) {
  5462. var listeners, events, i;
  5463. events = this._events;
  5464. if (!events)
  5465. return this;
  5466. // not listening for removeListener, no need to emit
  5467. if (!events.removeListener) {
  5468. if (arguments.length === 0) {
  5469. this._events = objectCreate(null);
  5470. this._eventsCount = 0;
  5471. } else if (events[type]) {
  5472. if (--this._eventsCount === 0)
  5473. this._events = objectCreate(null);
  5474. else
  5475. delete events[type];
  5476. }
  5477. return this;
  5478. }
  5479. // emit removeListener for all listeners on all events
  5480. if (arguments.length === 0) {
  5481. var keys = objectKeys(events);
  5482. var key;
  5483. for (i = 0; i < keys.length; ++i) {
  5484. key = keys[i];
  5485. if (key === 'removeListener') continue;
  5486. this.removeAllListeners(key);
  5487. }
  5488. this.removeAllListeners('removeListener');
  5489. this._events = objectCreate(null);
  5490. this._eventsCount = 0;
  5491. return this;
  5492. }
  5493. listeners = events[type];
  5494. if (typeof listeners === 'function') {
  5495. this.removeListener(type, listeners);
  5496. } else if (listeners) {
  5497. // LIFO order
  5498. for (i = listeners.length - 1; i >= 0; i--) {
  5499. this.removeListener(type, listeners[i]);
  5500. }
  5501. }
  5502. return this;
  5503. };
  5504. function _listeners(target, type, unwrap) {
  5505. var events = target._events;
  5506. if (!events)
  5507. return [];
  5508. var evlistener = events[type];
  5509. if (!evlistener)
  5510. return [];
  5511. if (typeof evlistener === 'function')
  5512. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  5513. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  5514. }
  5515. EventEmitter.prototype.listeners = function listeners(type) {
  5516. return _listeners(this, type, true);
  5517. };
  5518. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  5519. return _listeners(this, type, false);
  5520. };
  5521. EventEmitter.listenerCount = function(emitter, type) {
  5522. if (typeof emitter.listenerCount === 'function') {
  5523. return emitter.listenerCount(type);
  5524. } else {
  5525. return listenerCount.call(emitter, type);
  5526. }
  5527. };
  5528. EventEmitter.prototype.listenerCount = listenerCount;
  5529. function listenerCount(type) {
  5530. var events = this._events;
  5531. if (events) {
  5532. var evlistener = events[type];
  5533. if (typeof evlistener === 'function') {
  5534. return 1;
  5535. } else if (evlistener) {
  5536. return evlistener.length;
  5537. }
  5538. }
  5539. return 0;
  5540. }
  5541. EventEmitter.prototype.eventNames = function eventNames() {
  5542. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  5543. };
  5544. // About 1.5x faster than the two-arg version of Array#splice().
  5545. function spliceOne(list, index) {
  5546. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  5547. list[i] = list[k];
  5548. list.pop();
  5549. }
  5550. function arrayClone(arr, n) {
  5551. var copy = new Array(n);
  5552. for (var i = 0; i < n; ++i)
  5553. copy[i] = arr[i];
  5554. return copy;
  5555. }
  5556. function unwrapListeners(arr) {
  5557. var ret = new Array(arr.length);
  5558. for (var i = 0; i < ret.length; ++i) {
  5559. ret[i] = arr[i].listener || arr[i];
  5560. }
  5561. return ret;
  5562. }
  5563. function objectCreatePolyfill(proto) {
  5564. var F = function() {};
  5565. F.prototype = proto;
  5566. return new F;
  5567. }
  5568. function objectKeysPolyfill(obj) {
  5569. var keys = [];
  5570. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  5571. keys.push(k);
  5572. }
  5573. return k;
  5574. }
  5575. function functionBindPolyfill(context) {
  5576. var fn = this;
  5577. return function () {
  5578. return fn.apply(context, arguments);
  5579. };
  5580. }
  5581. },{}],31:[function(require,module,exports){
  5582. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5583. var e, m
  5584. var eLen = nBytes * 8 - mLen - 1
  5585. var eMax = (1 << eLen) - 1
  5586. var eBias = eMax >> 1
  5587. var nBits = -7
  5588. var i = isLE ? (nBytes - 1) : 0
  5589. var d = isLE ? -1 : 1
  5590. var s = buffer[offset + i]
  5591. i += d
  5592. e = s & ((1 << (-nBits)) - 1)
  5593. s >>= (-nBits)
  5594. nBits += eLen
  5595. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  5596. m = e & ((1 << (-nBits)) - 1)
  5597. e >>= (-nBits)
  5598. nBits += mLen
  5599. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  5600. if (e === 0) {
  5601. e = 1 - eBias
  5602. } else if (e === eMax) {
  5603. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5604. } else {
  5605. m = m + Math.pow(2, mLen)
  5606. e = e - eBias
  5607. }
  5608. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5609. }
  5610. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5611. var e, m, c
  5612. var eLen = nBytes * 8 - mLen - 1
  5613. var eMax = (1 << eLen) - 1
  5614. var eBias = eMax >> 1
  5615. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5616. var i = isLE ? 0 : (nBytes - 1)
  5617. var d = isLE ? 1 : -1
  5618. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5619. value = Math.abs(value)
  5620. if (isNaN(value) || value === Infinity) {
  5621. m = isNaN(value) ? 1 : 0
  5622. e = eMax
  5623. } else {
  5624. e = Math.floor(Math.log(value) / Math.LN2)
  5625. if (value * (c = Math.pow(2, -e)) < 1) {
  5626. e--
  5627. c *= 2
  5628. }
  5629. if (e + eBias >= 1) {
  5630. value += rt / c
  5631. } else {
  5632. value += rt * Math.pow(2, 1 - eBias)
  5633. }
  5634. if (value * c >= 2) {
  5635. e++
  5636. c /= 2
  5637. }
  5638. if (e + eBias >= eMax) {
  5639. m = 0
  5640. e = eMax
  5641. } else if (e + eBias >= 1) {
  5642. m = (value * c - 1) * Math.pow(2, mLen)
  5643. e = e + eBias
  5644. } else {
  5645. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5646. e = 0
  5647. }
  5648. }
  5649. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5650. e = (e << mLen) | m
  5651. eLen += mLen
  5652. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  5653. buffer[offset + i - d] |= s * 128
  5654. }
  5655. },{}],32:[function(require,module,exports){
  5656. if (typeof Object.create === 'function') {
  5657. // implementation from standard node.js 'util' module
  5658. module.exports = function inherits(ctor, superCtor) {
  5659. ctor.super_ = superCtor
  5660. ctor.prototype = Object.create(superCtor.prototype, {
  5661. constructor: {
  5662. value: ctor,
  5663. enumerable: false,
  5664. writable: true,
  5665. configurable: true
  5666. }
  5667. });
  5668. };
  5669. } else {
  5670. // old school shim for old browsers
  5671. module.exports = function inherits(ctor, superCtor) {
  5672. ctor.super_ = superCtor
  5673. var TempCtor = function () {}
  5674. TempCtor.prototype = superCtor.prototype
  5675. ctor.prototype = new TempCtor()
  5676. ctor.prototype.constructor = ctor
  5677. }
  5678. }
  5679. },{}],33:[function(require,module,exports){
  5680. /*!
  5681. * Determine if an object is a Buffer
  5682. *
  5683. * @author Feross Aboukhadijeh <https://feross.org>
  5684. * @license MIT
  5685. */
  5686. // The _isBuffer check is for Safari 5-7 support, because it's missing
  5687. // Object.prototype.constructor. Remove this eventually
  5688. module.exports = function (obj) {
  5689. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  5690. }
  5691. function isBuffer (obj) {
  5692. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  5693. }
  5694. // For Node v0.10 support. Remove this eventually.
  5695. function isSlowBuffer (obj) {
  5696. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  5697. }
  5698. },{}],34:[function(require,module,exports){
  5699. var toString = {}.toString;
  5700. module.exports = Array.isArray || function (arr) {
  5701. return toString.call(arr) == '[object Array]';
  5702. };
  5703. },{}],35:[function(require,module,exports){
  5704. 'use strict';
  5705. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5706. (typeof Uint16Array !== 'undefined') &&
  5707. (typeof Int32Array !== 'undefined');
  5708. function _has(obj, key) {
  5709. return Object.prototype.hasOwnProperty.call(obj, key);
  5710. }
  5711. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5712. var sources = Array.prototype.slice.call(arguments, 1);
  5713. while (sources.length) {
  5714. var source = sources.shift();
  5715. if (!source) { continue; }
  5716. if (typeof source !== 'object') {
  5717. throw new TypeError(source + 'must be non-object');
  5718. }
  5719. for (var p in source) {
  5720. if (_has(source, p)) {
  5721. obj[p] = source[p];
  5722. }
  5723. }
  5724. }
  5725. return obj;
  5726. };
  5727. // reduce buffer size, avoiding mem copy
  5728. exports.shrinkBuf = function (buf, size) {
  5729. if (buf.length === size) { return buf; }
  5730. if (buf.subarray) { return buf.subarray(0, size); }
  5731. buf.length = size;
  5732. return buf;
  5733. };
  5734. var fnTyped = {
  5735. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5736. if (src.subarray && dest.subarray) {
  5737. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5738. return;
  5739. }
  5740. // Fallback to ordinary array
  5741. for (var i = 0; i < len; i++) {
  5742. dest[dest_offs + i] = src[src_offs + i];
  5743. }
  5744. },
  5745. // Join array of chunks to single array.
  5746. flattenChunks: function (chunks) {
  5747. var i, l, len, pos, chunk, result;
  5748. // calculate data length
  5749. len = 0;
  5750. for (i = 0, l = chunks.length; i < l; i++) {
  5751. len += chunks[i].length;
  5752. }
  5753. // join chunks
  5754. result = new Uint8Array(len);
  5755. pos = 0;
  5756. for (i = 0, l = chunks.length; i < l; i++) {
  5757. chunk = chunks[i];
  5758. result.set(chunk, pos);
  5759. pos += chunk.length;
  5760. }
  5761. return result;
  5762. }
  5763. };
  5764. var fnUntyped = {
  5765. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5766. for (var i = 0; i < len; i++) {
  5767. dest[dest_offs + i] = src[src_offs + i];
  5768. }
  5769. },
  5770. // Join array of chunks to single array.
  5771. flattenChunks: function (chunks) {
  5772. return [].concat.apply([], chunks);
  5773. }
  5774. };
  5775. // Enable/Disable typed arrays use, for testing
  5776. //
  5777. exports.setTyped = function (on) {
  5778. if (on) {
  5779. exports.Buf8 = Uint8Array;
  5780. exports.Buf16 = Uint16Array;
  5781. exports.Buf32 = Int32Array;
  5782. exports.assign(exports, fnTyped);
  5783. } else {
  5784. exports.Buf8 = Array;
  5785. exports.Buf16 = Array;
  5786. exports.Buf32 = Array;
  5787. exports.assign(exports, fnUntyped);
  5788. }
  5789. };
  5790. exports.setTyped(TYPED_OK);
  5791. },{}],36:[function(require,module,exports){
  5792. 'use strict';
  5793. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5794. // It isn't worth it to make additional optimizations as in original.
  5795. // Small size is preferable.
  5796. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5797. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5798. //
  5799. // This software is provided 'as-is', without any express or implied
  5800. // warranty. In no event will the authors be held liable for any damages
  5801. // arising from the use of this software.
  5802. //
  5803. // Permission is granted to anyone to use this software for any purpose,
  5804. // including commercial applications, and to alter it and redistribute it
  5805. // freely, subject to the following restrictions:
  5806. //
  5807. // 1. The origin of this software must not be misrepresented; you must not
  5808. // claim that you wrote the original software. If you use this software
  5809. // in a product, an acknowledgment in the product documentation would be
  5810. // appreciated but is not required.
  5811. // 2. Altered source versions must be plainly marked as such, and must not be
  5812. // misrepresented as being the original software.
  5813. // 3. This notice may not be removed or altered from any source distribution.
  5814. function adler32(adler, buf, len, pos) {
  5815. var s1 = (adler & 0xffff) |0,
  5816. s2 = ((adler >>> 16) & 0xffff) |0,
  5817. n = 0;
  5818. while (len !== 0) {
  5819. // Set limit ~ twice less than 5552, to keep
  5820. // s2 in 31-bits, because we force signed ints.
  5821. // in other case %= will fail.
  5822. n = len > 2000 ? 2000 : len;
  5823. len -= n;
  5824. do {
  5825. s1 = (s1 + buf[pos++]) |0;
  5826. s2 = (s2 + s1) |0;
  5827. } while (--n);
  5828. s1 %= 65521;
  5829. s2 %= 65521;
  5830. }
  5831. return (s1 | (s2 << 16)) |0;
  5832. }
  5833. module.exports = adler32;
  5834. },{}],37:[function(require,module,exports){
  5835. 'use strict';
  5836. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5837. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5838. //
  5839. // This software is provided 'as-is', without any express or implied
  5840. // warranty. In no event will the authors be held liable for any damages
  5841. // arising from the use of this software.
  5842. //
  5843. // Permission is granted to anyone to use this software for any purpose,
  5844. // including commercial applications, and to alter it and redistribute it
  5845. // freely, subject to the following restrictions:
  5846. //
  5847. // 1. The origin of this software must not be misrepresented; you must not
  5848. // claim that you wrote the original software. If you use this software
  5849. // in a product, an acknowledgment in the product documentation would be
  5850. // appreciated but is not required.
  5851. // 2. Altered source versions must be plainly marked as such, and must not be
  5852. // misrepresented as being the original software.
  5853. // 3. This notice may not be removed or altered from any source distribution.
  5854. module.exports = {
  5855. /* Allowed flush values; see deflate() and inflate() below for details */
  5856. Z_NO_FLUSH: 0,
  5857. Z_PARTIAL_FLUSH: 1,
  5858. Z_SYNC_FLUSH: 2,
  5859. Z_FULL_FLUSH: 3,
  5860. Z_FINISH: 4,
  5861. Z_BLOCK: 5,
  5862. Z_TREES: 6,
  5863. /* Return codes for the compression/decompression functions. Negative values
  5864. * are errors, positive values are used for special but normal events.
  5865. */
  5866. Z_OK: 0,
  5867. Z_STREAM_END: 1,
  5868. Z_NEED_DICT: 2,
  5869. Z_ERRNO: -1,
  5870. Z_STREAM_ERROR: -2,
  5871. Z_DATA_ERROR: -3,
  5872. //Z_MEM_ERROR: -4,
  5873. Z_BUF_ERROR: -5,
  5874. //Z_VERSION_ERROR: -6,
  5875. /* compression levels */
  5876. Z_NO_COMPRESSION: 0,
  5877. Z_BEST_SPEED: 1,
  5878. Z_BEST_COMPRESSION: 9,
  5879. Z_DEFAULT_COMPRESSION: -1,
  5880. Z_FILTERED: 1,
  5881. Z_HUFFMAN_ONLY: 2,
  5882. Z_RLE: 3,
  5883. Z_FIXED: 4,
  5884. Z_DEFAULT_STRATEGY: 0,
  5885. /* Possible values of the data_type field (though see inflate()) */
  5886. Z_BINARY: 0,
  5887. Z_TEXT: 1,
  5888. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5889. Z_UNKNOWN: 2,
  5890. /* The deflate compression method */
  5891. Z_DEFLATED: 8
  5892. //Z_NULL: null // Use -1 or null inline, depending on var type
  5893. };
  5894. },{}],38:[function(require,module,exports){
  5895. 'use strict';
  5896. // Note: we can't get significant speed boost here.
  5897. // So write code to minimize size - no pregenerated tables
  5898. // and array tools dependencies.
  5899. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5900. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5901. //
  5902. // This software is provided 'as-is', without any express or implied
  5903. // warranty. In no event will the authors be held liable for any damages
  5904. // arising from the use of this software.
  5905. //
  5906. // Permission is granted to anyone to use this software for any purpose,
  5907. // including commercial applications, and to alter it and redistribute it
  5908. // freely, subject to the following restrictions:
  5909. //
  5910. // 1. The origin of this software must not be misrepresented; you must not
  5911. // claim that you wrote the original software. If you use this software
  5912. // in a product, an acknowledgment in the product documentation would be
  5913. // appreciated but is not required.
  5914. // 2. Altered source versions must be plainly marked as such, and must not be
  5915. // misrepresented as being the original software.
  5916. // 3. This notice may not be removed or altered from any source distribution.
  5917. // Use ordinary array, since untyped makes no boost here
  5918. function makeTable() {
  5919. var c, table = [];
  5920. for (var n = 0; n < 256; n++) {
  5921. c = n;
  5922. for (var k = 0; k < 8; k++) {
  5923. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5924. }
  5925. table[n] = c;
  5926. }
  5927. return table;
  5928. }
  5929. // Create table on load. Just 255 signed longs. Not a problem.
  5930. var crcTable = makeTable();
  5931. function crc32(crc, buf, len, pos) {
  5932. var t = crcTable,
  5933. end = pos + len;
  5934. crc ^= -1;
  5935. for (var i = pos; i < end; i++) {
  5936. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5937. }
  5938. return (crc ^ (-1)); // >>> 0;
  5939. }
  5940. module.exports = crc32;
  5941. },{}],39:[function(require,module,exports){
  5942. 'use strict';
  5943. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5944. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5945. //
  5946. // This software is provided 'as-is', without any express or implied
  5947. // warranty. In no event will the authors be held liable for any damages
  5948. // arising from the use of this software.
  5949. //
  5950. // Permission is granted to anyone to use this software for any purpose,
  5951. // including commercial applications, and to alter it and redistribute it
  5952. // freely, subject to the following restrictions:
  5953. //
  5954. // 1. The origin of this software must not be misrepresented; you must not
  5955. // claim that you wrote the original software. If you use this software
  5956. // in a product, an acknowledgment in the product documentation would be
  5957. // appreciated but is not required.
  5958. // 2. Altered source versions must be plainly marked as such, and must not be
  5959. // misrepresented as being the original software.
  5960. // 3. This notice may not be removed or altered from any source distribution.
  5961. var utils = require('../utils/common');
  5962. var trees = require('./trees');
  5963. var adler32 = require('./adler32');
  5964. var crc32 = require('./crc32');
  5965. var msg = require('./messages');
  5966. /* Public constants ==========================================================*/
  5967. /* ===========================================================================*/
  5968. /* Allowed flush values; see deflate() and inflate() below for details */
  5969. var Z_NO_FLUSH = 0;
  5970. var Z_PARTIAL_FLUSH = 1;
  5971. //var Z_SYNC_FLUSH = 2;
  5972. var Z_FULL_FLUSH = 3;
  5973. var Z_FINISH = 4;
  5974. var Z_BLOCK = 5;
  5975. //var Z_TREES = 6;
  5976. /* Return codes for the compression/decompression functions. Negative values
  5977. * are errors, positive values are used for special but normal events.
  5978. */
  5979. var Z_OK = 0;
  5980. var Z_STREAM_END = 1;
  5981. //var Z_NEED_DICT = 2;
  5982. //var Z_ERRNO = -1;
  5983. var Z_STREAM_ERROR = -2;
  5984. var Z_DATA_ERROR = -3;
  5985. //var Z_MEM_ERROR = -4;
  5986. var Z_BUF_ERROR = -5;
  5987. //var Z_VERSION_ERROR = -6;
  5988. /* compression levels */
  5989. //var Z_NO_COMPRESSION = 0;
  5990. //var Z_BEST_SPEED = 1;
  5991. //var Z_BEST_COMPRESSION = 9;
  5992. var Z_DEFAULT_COMPRESSION = -1;
  5993. var Z_FILTERED = 1;
  5994. var Z_HUFFMAN_ONLY = 2;
  5995. var Z_RLE = 3;
  5996. var Z_FIXED = 4;
  5997. var Z_DEFAULT_STRATEGY = 0;
  5998. /* Possible values of the data_type field (though see inflate()) */
  5999. //var Z_BINARY = 0;
  6000. //var Z_TEXT = 1;
  6001. //var Z_ASCII = 1; // = Z_TEXT
  6002. var Z_UNKNOWN = 2;
  6003. /* The deflate compression method */
  6004. var Z_DEFLATED = 8;
  6005. /*============================================================================*/
  6006. var MAX_MEM_LEVEL = 9;
  6007. /* Maximum value for memLevel in deflateInit2 */
  6008. var MAX_WBITS = 15;
  6009. /* 32K LZ77 window */
  6010. var DEF_MEM_LEVEL = 8;
  6011. var LENGTH_CODES = 29;
  6012. /* number of length codes, not counting the special END_BLOCK code */
  6013. var LITERALS = 256;
  6014. /* number of literal bytes 0..255 */
  6015. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6016. /* number of Literal or Length codes, including the END_BLOCK code */
  6017. var D_CODES = 30;
  6018. /* number of distance codes */
  6019. var BL_CODES = 19;
  6020. /* number of codes used to transfer the bit lengths */
  6021. var HEAP_SIZE = 2 * L_CODES + 1;
  6022. /* maximum heap size */
  6023. var MAX_BITS = 15;
  6024. /* All codes must not exceed MAX_BITS bits */
  6025. var MIN_MATCH = 3;
  6026. var MAX_MATCH = 258;
  6027. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6028. var PRESET_DICT = 0x20;
  6029. var INIT_STATE = 42;
  6030. var EXTRA_STATE = 69;
  6031. var NAME_STATE = 73;
  6032. var COMMENT_STATE = 91;
  6033. var HCRC_STATE = 103;
  6034. var BUSY_STATE = 113;
  6035. var FINISH_STATE = 666;
  6036. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6037. var BS_BLOCK_DONE = 2; /* block flush performed */
  6038. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6039. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6040. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6041. function err(strm, errorCode) {
  6042. strm.msg = msg[errorCode];
  6043. return errorCode;
  6044. }
  6045. function rank(f) {
  6046. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6047. }
  6048. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6049. /* =========================================================================
  6050. * Flush as much pending output as possible. All deflate() output goes
  6051. * through this function so some applications may wish to modify it
  6052. * to avoid allocating a large strm->output buffer and copying into it.
  6053. * (See also read_buf()).
  6054. */
  6055. function flush_pending(strm) {
  6056. var s = strm.state;
  6057. //_tr_flush_bits(s);
  6058. var len = s.pending;
  6059. if (len > strm.avail_out) {
  6060. len = strm.avail_out;
  6061. }
  6062. if (len === 0) { return; }
  6063. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6064. strm.next_out += len;
  6065. s.pending_out += len;
  6066. strm.total_out += len;
  6067. strm.avail_out -= len;
  6068. s.pending -= len;
  6069. if (s.pending === 0) {
  6070. s.pending_out = 0;
  6071. }
  6072. }
  6073. function flush_block_only(s, last) {
  6074. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6075. s.block_start = s.strstart;
  6076. flush_pending(s.strm);
  6077. }
  6078. function put_byte(s, b) {
  6079. s.pending_buf[s.pending++] = b;
  6080. }
  6081. /* =========================================================================
  6082. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6083. * IN assertion: the stream state is correct and there is enough room in
  6084. * pending_buf.
  6085. */
  6086. function putShortMSB(s, b) {
  6087. // put_byte(s, (Byte)(b >> 8));
  6088. // put_byte(s, (Byte)(b & 0xff));
  6089. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6090. s.pending_buf[s.pending++] = b & 0xff;
  6091. }
  6092. /* ===========================================================================
  6093. * Read a new buffer from the current input stream, update the adler32
  6094. * and total number of bytes read. All deflate() input goes through
  6095. * this function so some applications may wish to modify it to avoid
  6096. * allocating a large strm->input buffer and copying from it.
  6097. * (See also flush_pending()).
  6098. */
  6099. function read_buf(strm, buf, start, size) {
  6100. var len = strm.avail_in;
  6101. if (len > size) { len = size; }
  6102. if (len === 0) { return 0; }
  6103. strm.avail_in -= len;
  6104. // zmemcpy(buf, strm->next_in, len);
  6105. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6106. if (strm.state.wrap === 1) {
  6107. strm.adler = adler32(strm.adler, buf, len, start);
  6108. }
  6109. else if (strm.state.wrap === 2) {
  6110. strm.adler = crc32(strm.adler, buf, len, start);
  6111. }
  6112. strm.next_in += len;
  6113. strm.total_in += len;
  6114. return len;
  6115. }
  6116. /* ===========================================================================
  6117. * Set match_start to the longest match starting at the given string and
  6118. * return its length. Matches shorter or equal to prev_length are discarded,
  6119. * in which case the result is equal to prev_length and match_start is
  6120. * garbage.
  6121. * IN assertions: cur_match is the head of the hash chain for the current
  6122. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6123. * OUT assertion: the match length is not greater than s->lookahead.
  6124. */
  6125. function longest_match(s, cur_match) {
  6126. var chain_length = s.max_chain_length; /* max hash chain length */
  6127. var scan = s.strstart; /* current string */
  6128. var match; /* matched string */
  6129. var len; /* length of current match */
  6130. var best_len = s.prev_length; /* best match length so far */
  6131. var nice_match = s.nice_match; /* stop if match long enough */
  6132. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6133. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6134. var _win = s.window; // shortcut
  6135. var wmask = s.w_mask;
  6136. var prev = s.prev;
  6137. /* Stop when cur_match becomes <= limit. To simplify the code,
  6138. * we prevent matches with the string of window index 0.
  6139. */
  6140. var strend = s.strstart + MAX_MATCH;
  6141. var scan_end1 = _win[scan + best_len - 1];
  6142. var scan_end = _win[scan + best_len];
  6143. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6144. * It is easy to get rid of this optimization if necessary.
  6145. */
  6146. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6147. /* Do not waste too much time if we already have a good match: */
  6148. if (s.prev_length >= s.good_match) {
  6149. chain_length >>= 2;
  6150. }
  6151. /* Do not look for matches beyond the end of the input. This is necessary
  6152. * to make deflate deterministic.
  6153. */
  6154. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6155. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6156. do {
  6157. // Assert(cur_match < s->strstart, "no future");
  6158. match = cur_match;
  6159. /* Skip to next match if the match length cannot increase
  6160. * or if the match length is less than 2. Note that the checks below
  6161. * for insufficient lookahead only occur occasionally for performance
  6162. * reasons. Therefore uninitialized memory will be accessed, and
  6163. * conditional jumps will be made that depend on those values.
  6164. * However the length of the match is limited to the lookahead, so
  6165. * the output of deflate is not affected by the uninitialized values.
  6166. */
  6167. if (_win[match + best_len] !== scan_end ||
  6168. _win[match + best_len - 1] !== scan_end1 ||
  6169. _win[match] !== _win[scan] ||
  6170. _win[++match] !== _win[scan + 1]) {
  6171. continue;
  6172. }
  6173. /* The check at best_len-1 can be removed because it will be made
  6174. * again later. (This heuristic is not always a win.)
  6175. * It is not necessary to compare scan[2] and match[2] since they
  6176. * are always equal when the other bytes match, given that
  6177. * the hash keys are equal and that HASH_BITS >= 8.
  6178. */
  6179. scan += 2;
  6180. match++;
  6181. // Assert(*scan == *match, "match[2]?");
  6182. /* We check for insufficient lookahead only every 8th comparison;
  6183. * the 256th check will be made at strstart+258.
  6184. */
  6185. do {
  6186. /*jshint noempty:false*/
  6187. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6188. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6189. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6190. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6191. scan < strend);
  6192. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6193. len = MAX_MATCH - (strend - scan);
  6194. scan = strend - MAX_MATCH;
  6195. if (len > best_len) {
  6196. s.match_start = cur_match;
  6197. best_len = len;
  6198. if (len >= nice_match) {
  6199. break;
  6200. }
  6201. scan_end1 = _win[scan + best_len - 1];
  6202. scan_end = _win[scan + best_len];
  6203. }
  6204. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6205. if (best_len <= s.lookahead) {
  6206. return best_len;
  6207. }
  6208. return s.lookahead;
  6209. }
  6210. /* ===========================================================================
  6211. * Fill the window when the lookahead becomes insufficient.
  6212. * Updates strstart and lookahead.
  6213. *
  6214. * IN assertion: lookahead < MIN_LOOKAHEAD
  6215. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6216. * At least one byte has been read, or avail_in == 0; reads are
  6217. * performed for at least two bytes (required for the zip translate_eol
  6218. * option -- not supported here).
  6219. */
  6220. function fill_window(s) {
  6221. var _w_size = s.w_size;
  6222. var p, n, m, more, str;
  6223. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6224. do {
  6225. more = s.window_size - s.lookahead - s.strstart;
  6226. // JS ints have 32 bit, block below not needed
  6227. /* Deal with !@#$% 64K limit: */
  6228. //if (sizeof(int) <= 2) {
  6229. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6230. // more = wsize;
  6231. //
  6232. // } else if (more == (unsigned)(-1)) {
  6233. // /* Very unlikely, but possible on 16 bit machine if
  6234. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6235. // */
  6236. // more--;
  6237. // }
  6238. //}
  6239. /* If the window is almost full and there is insufficient lookahead,
  6240. * move the upper half to the lower one to make room in the upper half.
  6241. */
  6242. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6243. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6244. s.match_start -= _w_size;
  6245. s.strstart -= _w_size;
  6246. /* we now have strstart >= MAX_DIST */
  6247. s.block_start -= _w_size;
  6248. /* Slide the hash table (could be avoided with 32 bit values
  6249. at the expense of memory usage). We slide even when level == 0
  6250. to keep the hash table consistent if we switch back to level > 0
  6251. later. (Using level 0 permanently is not an optimal usage of
  6252. zlib, so we don't care about this pathological case.)
  6253. */
  6254. n = s.hash_size;
  6255. p = n;
  6256. do {
  6257. m = s.head[--p];
  6258. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6259. } while (--n);
  6260. n = _w_size;
  6261. p = n;
  6262. do {
  6263. m = s.prev[--p];
  6264. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6265. /* If n is not on any hash chain, prev[n] is garbage but
  6266. * its value will never be used.
  6267. */
  6268. } while (--n);
  6269. more += _w_size;
  6270. }
  6271. if (s.strm.avail_in === 0) {
  6272. break;
  6273. }
  6274. /* If there was no sliding:
  6275. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6276. * more == window_size - lookahead - strstart
  6277. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6278. * => more >= window_size - 2*WSIZE + 2
  6279. * In the BIG_MEM or MMAP case (not yet supported),
  6280. * window_size == input_size + MIN_LOOKAHEAD &&
  6281. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6282. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6283. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6284. */
  6285. //Assert(more >= 2, "more < 2");
  6286. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6287. s.lookahead += n;
  6288. /* Initialize the hash value now that we have some input: */
  6289. if (s.lookahead + s.insert >= MIN_MATCH) {
  6290. str = s.strstart - s.insert;
  6291. s.ins_h = s.window[str];
  6292. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6293. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6294. //#if MIN_MATCH != 3
  6295. // Call update_hash() MIN_MATCH-3 more times
  6296. //#endif
  6297. while (s.insert) {
  6298. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6299. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6300. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6301. s.head[s.ins_h] = str;
  6302. str++;
  6303. s.insert--;
  6304. if (s.lookahead + s.insert < MIN_MATCH) {
  6305. break;
  6306. }
  6307. }
  6308. }
  6309. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6310. * but this is not important since only literal bytes will be emitted.
  6311. */
  6312. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6313. /* If the WIN_INIT bytes after the end of the current data have never been
  6314. * written, then zero those bytes in order to avoid memory check reports of
  6315. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6316. * the longest match routines. Update the high water mark for the next
  6317. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6318. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6319. */
  6320. // if (s.high_water < s.window_size) {
  6321. // var curr = s.strstart + s.lookahead;
  6322. // var init = 0;
  6323. //
  6324. // if (s.high_water < curr) {
  6325. // /* Previous high water mark below current data -- zero WIN_INIT
  6326. // * bytes or up to end of window, whichever is less.
  6327. // */
  6328. // init = s.window_size - curr;
  6329. // if (init > WIN_INIT)
  6330. // init = WIN_INIT;
  6331. // zmemzero(s->window + curr, (unsigned)init);
  6332. // s->high_water = curr + init;
  6333. // }
  6334. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6335. // /* High water mark at or above current data, but below current data
  6336. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6337. // * to end of window, whichever is less.
  6338. // */
  6339. // init = (ulg)curr + WIN_INIT - s->high_water;
  6340. // if (init > s->window_size - s->high_water)
  6341. // init = s->window_size - s->high_water;
  6342. // zmemzero(s->window + s->high_water, (unsigned)init);
  6343. // s->high_water += init;
  6344. // }
  6345. // }
  6346. //
  6347. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6348. // "not enough room for search");
  6349. }
  6350. /* ===========================================================================
  6351. * Copy without compression as much as possible from the input stream, return
  6352. * the current block state.
  6353. * This function does not insert new strings in the dictionary since
  6354. * uncompressible data is probably not useful. This function is used
  6355. * only for the level=0 compression option.
  6356. * NOTE: this function should be optimized to avoid extra copying from
  6357. * window to pending_buf.
  6358. */
  6359. function deflate_stored(s, flush) {
  6360. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6361. * to pending_buf_size, and each stored block has a 5 byte header:
  6362. */
  6363. var max_block_size = 0xffff;
  6364. if (max_block_size > s.pending_buf_size - 5) {
  6365. max_block_size = s.pending_buf_size - 5;
  6366. }
  6367. /* Copy as much as possible from input to output: */
  6368. for (;;) {
  6369. /* Fill the window as much as possible: */
  6370. if (s.lookahead <= 1) {
  6371. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6372. // s->block_start >= (long)s->w_size, "slide too late");
  6373. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6374. // s.block_start >= s.w_size)) {
  6375. // throw new Error("slide too late");
  6376. // }
  6377. fill_window(s);
  6378. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6379. return BS_NEED_MORE;
  6380. }
  6381. if (s.lookahead === 0) {
  6382. break;
  6383. }
  6384. /* flush the current block */
  6385. }
  6386. //Assert(s->block_start >= 0L, "block gone");
  6387. // if (s.block_start < 0) throw new Error("block gone");
  6388. s.strstart += s.lookahead;
  6389. s.lookahead = 0;
  6390. /* Emit a stored block if pending_buf will be full: */
  6391. var max_start = s.block_start + max_block_size;
  6392. if (s.strstart === 0 || s.strstart >= max_start) {
  6393. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6394. s.lookahead = s.strstart - max_start;
  6395. s.strstart = max_start;
  6396. /*** FLUSH_BLOCK(s, 0); ***/
  6397. flush_block_only(s, false);
  6398. if (s.strm.avail_out === 0) {
  6399. return BS_NEED_MORE;
  6400. }
  6401. /***/
  6402. }
  6403. /* Flush if we may have to slide, otherwise block_start may become
  6404. * negative and the data will be gone:
  6405. */
  6406. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6407. /*** FLUSH_BLOCK(s, 0); ***/
  6408. flush_block_only(s, false);
  6409. if (s.strm.avail_out === 0) {
  6410. return BS_NEED_MORE;
  6411. }
  6412. /***/
  6413. }
  6414. }
  6415. s.insert = 0;
  6416. if (flush === Z_FINISH) {
  6417. /*** FLUSH_BLOCK(s, 1); ***/
  6418. flush_block_only(s, true);
  6419. if (s.strm.avail_out === 0) {
  6420. return BS_FINISH_STARTED;
  6421. }
  6422. /***/
  6423. return BS_FINISH_DONE;
  6424. }
  6425. if (s.strstart > s.block_start) {
  6426. /*** FLUSH_BLOCK(s, 0); ***/
  6427. flush_block_only(s, false);
  6428. if (s.strm.avail_out === 0) {
  6429. return BS_NEED_MORE;
  6430. }
  6431. /***/
  6432. }
  6433. return BS_NEED_MORE;
  6434. }
  6435. /* ===========================================================================
  6436. * Compress as much as possible from the input stream, return the current
  6437. * block state.
  6438. * This function does not perform lazy evaluation of matches and inserts
  6439. * new strings in the dictionary only for unmatched strings or for short
  6440. * matches. It is used only for the fast compression options.
  6441. */
  6442. function deflate_fast(s, flush) {
  6443. var hash_head; /* head of the hash chain */
  6444. var bflush; /* set if current block must be flushed */
  6445. for (;;) {
  6446. /* Make sure that we always have enough lookahead, except
  6447. * at the end of the input file. We need MAX_MATCH bytes
  6448. * for the next match, plus MIN_MATCH bytes to insert the
  6449. * string following the next match.
  6450. */
  6451. if (s.lookahead < MIN_LOOKAHEAD) {
  6452. fill_window(s);
  6453. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6454. return BS_NEED_MORE;
  6455. }
  6456. if (s.lookahead === 0) {
  6457. break; /* flush the current block */
  6458. }
  6459. }
  6460. /* Insert the string window[strstart .. strstart+2] in the
  6461. * dictionary, and set hash_head to the head of the hash chain:
  6462. */
  6463. hash_head = 0/*NIL*/;
  6464. if (s.lookahead >= MIN_MATCH) {
  6465. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6466. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6467. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6468. s.head[s.ins_h] = s.strstart;
  6469. /***/
  6470. }
  6471. /* Find the longest match, discarding those <= prev_length.
  6472. * At this point we have always match_length < MIN_MATCH
  6473. */
  6474. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6475. /* To simplify the code, we prevent matches with the string
  6476. * of window index 0 (in particular we have to avoid a match
  6477. * of the string with itself at the start of the input file).
  6478. */
  6479. s.match_length = longest_match(s, hash_head);
  6480. /* longest_match() sets match_start */
  6481. }
  6482. if (s.match_length >= MIN_MATCH) {
  6483. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6484. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6485. s.match_length - MIN_MATCH, bflush); ***/
  6486. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6487. s.lookahead -= s.match_length;
  6488. /* Insert new strings in the hash table only if the match length
  6489. * is not too large. This saves time but degrades compression.
  6490. */
  6491. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6492. s.match_length--; /* string at strstart already in table */
  6493. do {
  6494. s.strstart++;
  6495. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6496. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6497. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6498. s.head[s.ins_h] = s.strstart;
  6499. /***/
  6500. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6501. * always MIN_MATCH bytes ahead.
  6502. */
  6503. } while (--s.match_length !== 0);
  6504. s.strstart++;
  6505. } else
  6506. {
  6507. s.strstart += s.match_length;
  6508. s.match_length = 0;
  6509. s.ins_h = s.window[s.strstart];
  6510. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6511. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6512. //#if MIN_MATCH != 3
  6513. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6514. //#endif
  6515. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6516. * matter since it will be recomputed at next deflate call.
  6517. */
  6518. }
  6519. } else {
  6520. /* No match, output a literal byte */
  6521. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6522. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6523. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6524. s.lookahead--;
  6525. s.strstart++;
  6526. }
  6527. if (bflush) {
  6528. /*** FLUSH_BLOCK(s, 0); ***/
  6529. flush_block_only(s, false);
  6530. if (s.strm.avail_out === 0) {
  6531. return BS_NEED_MORE;
  6532. }
  6533. /***/
  6534. }
  6535. }
  6536. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6537. if (flush === Z_FINISH) {
  6538. /*** FLUSH_BLOCK(s, 1); ***/
  6539. flush_block_only(s, true);
  6540. if (s.strm.avail_out === 0) {
  6541. return BS_FINISH_STARTED;
  6542. }
  6543. /***/
  6544. return BS_FINISH_DONE;
  6545. }
  6546. if (s.last_lit) {
  6547. /*** FLUSH_BLOCK(s, 0); ***/
  6548. flush_block_only(s, false);
  6549. if (s.strm.avail_out === 0) {
  6550. return BS_NEED_MORE;
  6551. }
  6552. /***/
  6553. }
  6554. return BS_BLOCK_DONE;
  6555. }
  6556. /* ===========================================================================
  6557. * Same as above, but achieves better compression. We use a lazy
  6558. * evaluation for matches: a match is finally adopted only if there is
  6559. * no better match at the next window position.
  6560. */
  6561. function deflate_slow(s, flush) {
  6562. var hash_head; /* head of hash chain */
  6563. var bflush; /* set if current block must be flushed */
  6564. var max_insert;
  6565. /* Process the input block. */
  6566. for (;;) {
  6567. /* Make sure that we always have enough lookahead, except
  6568. * at the end of the input file. We need MAX_MATCH bytes
  6569. * for the next match, plus MIN_MATCH bytes to insert the
  6570. * string following the next match.
  6571. */
  6572. if (s.lookahead < MIN_LOOKAHEAD) {
  6573. fill_window(s);
  6574. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6575. return BS_NEED_MORE;
  6576. }
  6577. if (s.lookahead === 0) { break; } /* flush the current block */
  6578. }
  6579. /* Insert the string window[strstart .. strstart+2] in the
  6580. * dictionary, and set hash_head to the head of the hash chain:
  6581. */
  6582. hash_head = 0/*NIL*/;
  6583. if (s.lookahead >= MIN_MATCH) {
  6584. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6585. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6586. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6587. s.head[s.ins_h] = s.strstart;
  6588. /***/
  6589. }
  6590. /* Find the longest match, discarding those <= prev_length.
  6591. */
  6592. s.prev_length = s.match_length;
  6593. s.prev_match = s.match_start;
  6594. s.match_length = MIN_MATCH - 1;
  6595. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6596. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6597. /* To simplify the code, we prevent matches with the string
  6598. * of window index 0 (in particular we have to avoid a match
  6599. * of the string with itself at the start of the input file).
  6600. */
  6601. s.match_length = longest_match(s, hash_head);
  6602. /* longest_match() sets match_start */
  6603. if (s.match_length <= 5 &&
  6604. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6605. /* If prev_match is also MIN_MATCH, match_start is garbage
  6606. * but we will ignore the current match anyway.
  6607. */
  6608. s.match_length = MIN_MATCH - 1;
  6609. }
  6610. }
  6611. /* If there was a match at the previous step and the current
  6612. * match is not better, output the previous match:
  6613. */
  6614. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6615. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6616. /* Do not insert strings in hash table beyond this. */
  6617. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6618. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6619. s.prev_length - MIN_MATCH, bflush);***/
  6620. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6621. /* Insert in hash table all strings up to the end of the match.
  6622. * strstart-1 and strstart are already inserted. If there is not
  6623. * enough lookahead, the last two strings are not inserted in
  6624. * the hash table.
  6625. */
  6626. s.lookahead -= s.prev_length - 1;
  6627. s.prev_length -= 2;
  6628. do {
  6629. if (++s.strstart <= max_insert) {
  6630. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6631. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6632. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6633. s.head[s.ins_h] = s.strstart;
  6634. /***/
  6635. }
  6636. } while (--s.prev_length !== 0);
  6637. s.match_available = 0;
  6638. s.match_length = MIN_MATCH - 1;
  6639. s.strstart++;
  6640. if (bflush) {
  6641. /*** FLUSH_BLOCK(s, 0); ***/
  6642. flush_block_only(s, false);
  6643. if (s.strm.avail_out === 0) {
  6644. return BS_NEED_MORE;
  6645. }
  6646. /***/
  6647. }
  6648. } else if (s.match_available) {
  6649. /* If there was no match at the previous position, output a
  6650. * single literal. If there was a match but the current match
  6651. * is longer, truncate the previous match to a single literal.
  6652. */
  6653. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6654. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6655. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6656. if (bflush) {
  6657. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6658. flush_block_only(s, false);
  6659. /***/
  6660. }
  6661. s.strstart++;
  6662. s.lookahead--;
  6663. if (s.strm.avail_out === 0) {
  6664. return BS_NEED_MORE;
  6665. }
  6666. } else {
  6667. /* There is no previous match to compare with, wait for
  6668. * the next step to decide.
  6669. */
  6670. s.match_available = 1;
  6671. s.strstart++;
  6672. s.lookahead--;
  6673. }
  6674. }
  6675. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6676. if (s.match_available) {
  6677. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6678. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6679. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6680. s.match_available = 0;
  6681. }
  6682. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  6683. if (flush === Z_FINISH) {
  6684. /*** FLUSH_BLOCK(s, 1); ***/
  6685. flush_block_only(s, true);
  6686. if (s.strm.avail_out === 0) {
  6687. return BS_FINISH_STARTED;
  6688. }
  6689. /***/
  6690. return BS_FINISH_DONE;
  6691. }
  6692. if (s.last_lit) {
  6693. /*** FLUSH_BLOCK(s, 0); ***/
  6694. flush_block_only(s, false);
  6695. if (s.strm.avail_out === 0) {
  6696. return BS_NEED_MORE;
  6697. }
  6698. /***/
  6699. }
  6700. return BS_BLOCK_DONE;
  6701. }
  6702. /* ===========================================================================
  6703. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6704. * one. Do not maintain a hash table. (It will be regenerated if this run of
  6705. * deflate switches away from Z_RLE.)
  6706. */
  6707. function deflate_rle(s, flush) {
  6708. var bflush; /* set if current block must be flushed */
  6709. var prev; /* byte at distance one to match */
  6710. var scan, strend; /* scan goes up to strend for length of run */
  6711. var _win = s.window;
  6712. for (;;) {
  6713. /* Make sure that we always have enough lookahead, except
  6714. * at the end of the input file. We need MAX_MATCH bytes
  6715. * for the longest run, plus one for the unrolled loop.
  6716. */
  6717. if (s.lookahead <= MAX_MATCH) {
  6718. fill_window(s);
  6719. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  6720. return BS_NEED_MORE;
  6721. }
  6722. if (s.lookahead === 0) { break; } /* flush the current block */
  6723. }
  6724. /* See how many times the previous byte repeats */
  6725. s.match_length = 0;
  6726. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  6727. scan = s.strstart - 1;
  6728. prev = _win[scan];
  6729. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  6730. strend = s.strstart + MAX_MATCH;
  6731. do {
  6732. /*jshint noempty:false*/
  6733. } while (prev === _win[++scan] && prev === _win[++scan] &&
  6734. prev === _win[++scan] && prev === _win[++scan] &&
  6735. prev === _win[++scan] && prev === _win[++scan] &&
  6736. prev === _win[++scan] && prev === _win[++scan] &&
  6737. scan < strend);
  6738. s.match_length = MAX_MATCH - (strend - scan);
  6739. if (s.match_length > s.lookahead) {
  6740. s.match_length = s.lookahead;
  6741. }
  6742. }
  6743. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  6744. }
  6745. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  6746. if (s.match_length >= MIN_MATCH) {
  6747. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  6748. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  6749. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  6750. s.lookahead -= s.match_length;
  6751. s.strstart += s.match_length;
  6752. s.match_length = 0;
  6753. } else {
  6754. /* No match, output a literal byte */
  6755. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6756. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6757. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6758. s.lookahead--;
  6759. s.strstart++;
  6760. }
  6761. if (bflush) {
  6762. /*** FLUSH_BLOCK(s, 0); ***/
  6763. flush_block_only(s, false);
  6764. if (s.strm.avail_out === 0) {
  6765. return BS_NEED_MORE;
  6766. }
  6767. /***/
  6768. }
  6769. }
  6770. s.insert = 0;
  6771. if (flush === Z_FINISH) {
  6772. /*** FLUSH_BLOCK(s, 1); ***/
  6773. flush_block_only(s, true);
  6774. if (s.strm.avail_out === 0) {
  6775. return BS_FINISH_STARTED;
  6776. }
  6777. /***/
  6778. return BS_FINISH_DONE;
  6779. }
  6780. if (s.last_lit) {
  6781. /*** FLUSH_BLOCK(s, 0); ***/
  6782. flush_block_only(s, false);
  6783. if (s.strm.avail_out === 0) {
  6784. return BS_NEED_MORE;
  6785. }
  6786. /***/
  6787. }
  6788. return BS_BLOCK_DONE;
  6789. }
  6790. /* ===========================================================================
  6791. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6792. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6793. */
  6794. function deflate_huff(s, flush) {
  6795. var bflush; /* set if current block must be flushed */
  6796. for (;;) {
  6797. /* Make sure that we have a literal to write. */
  6798. if (s.lookahead === 0) {
  6799. fill_window(s);
  6800. if (s.lookahead === 0) {
  6801. if (flush === Z_NO_FLUSH) {
  6802. return BS_NEED_MORE;
  6803. }
  6804. break; /* flush the current block */
  6805. }
  6806. }
  6807. /* Output a literal byte */
  6808. s.match_length = 0;
  6809. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6810. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6811. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6812. s.lookahead--;
  6813. s.strstart++;
  6814. if (bflush) {
  6815. /*** FLUSH_BLOCK(s, 0); ***/
  6816. flush_block_only(s, false);
  6817. if (s.strm.avail_out === 0) {
  6818. return BS_NEED_MORE;
  6819. }
  6820. /***/
  6821. }
  6822. }
  6823. s.insert = 0;
  6824. if (flush === Z_FINISH) {
  6825. /*** FLUSH_BLOCK(s, 1); ***/
  6826. flush_block_only(s, true);
  6827. if (s.strm.avail_out === 0) {
  6828. return BS_FINISH_STARTED;
  6829. }
  6830. /***/
  6831. return BS_FINISH_DONE;
  6832. }
  6833. if (s.last_lit) {
  6834. /*** FLUSH_BLOCK(s, 0); ***/
  6835. flush_block_only(s, false);
  6836. if (s.strm.avail_out === 0) {
  6837. return BS_NEED_MORE;
  6838. }
  6839. /***/
  6840. }
  6841. return BS_BLOCK_DONE;
  6842. }
  6843. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6844. * the desired pack level (0..9). The values given below have been tuned to
  6845. * exclude worst case performance for pathological files. Better values may be
  6846. * found for specific files.
  6847. */
  6848. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  6849. this.good_length = good_length;
  6850. this.max_lazy = max_lazy;
  6851. this.nice_length = nice_length;
  6852. this.max_chain = max_chain;
  6853. this.func = func;
  6854. }
  6855. var configuration_table;
  6856. configuration_table = [
  6857. /* good lazy nice chain */
  6858. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6859. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6860. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6861. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6862. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6863. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6864. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6865. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6866. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6867. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6868. ];
  6869. /* ===========================================================================
  6870. * Initialize the "longest match" routines for a new zlib stream
  6871. */
  6872. function lm_init(s) {
  6873. s.window_size = 2 * s.w_size;
  6874. /*** CLEAR_HASH(s); ***/
  6875. zero(s.head); // Fill with NIL (= 0);
  6876. /* Set the default configuration parameters:
  6877. */
  6878. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6879. s.good_match = configuration_table[s.level].good_length;
  6880. s.nice_match = configuration_table[s.level].nice_length;
  6881. s.max_chain_length = configuration_table[s.level].max_chain;
  6882. s.strstart = 0;
  6883. s.block_start = 0;
  6884. s.lookahead = 0;
  6885. s.insert = 0;
  6886. s.match_length = s.prev_length = MIN_MATCH - 1;
  6887. s.match_available = 0;
  6888. s.ins_h = 0;
  6889. }
  6890. function DeflateState() {
  6891. this.strm = null; /* pointer back to this zlib stream */
  6892. this.status = 0; /* as the name implies */
  6893. this.pending_buf = null; /* output still pending */
  6894. this.pending_buf_size = 0; /* size of pending_buf */
  6895. this.pending_out = 0; /* next pending byte to output to the stream */
  6896. this.pending = 0; /* nb of bytes in the pending buffer */
  6897. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6898. this.gzhead = null; /* gzip header information to write */
  6899. this.gzindex = 0; /* where in extra, name, or comment */
  6900. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6901. this.last_flush = -1; /* value of flush param for previous deflate call */
  6902. this.w_size = 0; /* LZ77 window size (32K by default) */
  6903. this.w_bits = 0; /* log2(w_size) (8..16) */
  6904. this.w_mask = 0; /* w_size - 1 */
  6905. this.window = null;
  6906. /* Sliding window. Input bytes are read into the second half of the window,
  6907. * and move to the first half later to keep a dictionary of at least wSize
  6908. * bytes. With this organization, matches are limited to a distance of
  6909. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6910. * performed with a length multiple of the block size.
  6911. */
  6912. this.window_size = 0;
  6913. /* Actual size of window: 2*wSize, except when the user input buffer
  6914. * is directly used as sliding window.
  6915. */
  6916. this.prev = null;
  6917. /* Link to older string with same hash index. To limit the size of this
  6918. * array to 64K, this link is maintained only for the last 32K strings.
  6919. * An index in this array is thus a window index modulo 32K.
  6920. */
  6921. this.head = null; /* Heads of the hash chains or NIL. */
  6922. this.ins_h = 0; /* hash index of string to be inserted */
  6923. this.hash_size = 0; /* number of elements in hash table */
  6924. this.hash_bits = 0; /* log2(hash_size) */
  6925. this.hash_mask = 0; /* hash_size-1 */
  6926. this.hash_shift = 0;
  6927. /* Number of bits by which ins_h must be shifted at each input
  6928. * step. It must be such that after MIN_MATCH steps, the oldest
  6929. * byte no longer takes part in the hash key, that is:
  6930. * hash_shift * MIN_MATCH >= hash_bits
  6931. */
  6932. this.block_start = 0;
  6933. /* Window position at the beginning of the current output block. Gets
  6934. * negative when the window is moved backwards.
  6935. */
  6936. this.match_length = 0; /* length of best match */
  6937. this.prev_match = 0; /* previous match */
  6938. this.match_available = 0; /* set if previous match exists */
  6939. this.strstart = 0; /* start of string to insert */
  6940. this.match_start = 0; /* start of matching string */
  6941. this.lookahead = 0; /* number of valid bytes ahead in window */
  6942. this.prev_length = 0;
  6943. /* Length of the best match at previous step. Matches not greater than this
  6944. * are discarded. This is used in the lazy match evaluation.
  6945. */
  6946. this.max_chain_length = 0;
  6947. /* To speed up deflation, hash chains are never searched beyond this
  6948. * length. A higher limit improves compression ratio but degrades the
  6949. * speed.
  6950. */
  6951. this.max_lazy_match = 0;
  6952. /* Attempt to find a better match only when the current match is strictly
  6953. * smaller than this value. This mechanism is used only for compression
  6954. * levels >= 4.
  6955. */
  6956. // That's alias to max_lazy_match, don't use directly
  6957. //this.max_insert_length = 0;
  6958. /* Insert new strings in the hash table only if the match length is not
  6959. * greater than this length. This saves time but degrades compression.
  6960. * max_insert_length is used only for compression levels <= 3.
  6961. */
  6962. this.level = 0; /* compression level (1..9) */
  6963. this.strategy = 0; /* favor or force Huffman coding*/
  6964. this.good_match = 0;
  6965. /* Use a faster search when the previous match is longer than this */
  6966. this.nice_match = 0; /* Stop searching when current match exceeds this */
  6967. /* used by trees.c: */
  6968. /* Didn't use ct_data typedef below to suppress compiler warning */
  6969. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  6970. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  6971. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  6972. // Use flat array of DOUBLE size, with interleaved fata,
  6973. // because JS does not support effective
  6974. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  6975. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  6976. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  6977. zero(this.dyn_ltree);
  6978. zero(this.dyn_dtree);
  6979. zero(this.bl_tree);
  6980. this.l_desc = null; /* desc. for literal tree */
  6981. this.d_desc = null; /* desc. for distance tree */
  6982. this.bl_desc = null; /* desc. for bit length tree */
  6983. //ush bl_count[MAX_BITS+1];
  6984. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  6985. /* number of codes at each bit length for an optimal tree */
  6986. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  6987. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  6988. zero(this.heap);
  6989. this.heap_len = 0; /* number of elements in the heap */
  6990. this.heap_max = 0; /* element of largest frequency */
  6991. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  6992. * The same heap array is used to build all trees.
  6993. */
  6994. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  6995. zero(this.depth);
  6996. /* Depth of each subtree used as tie breaker for trees of equal frequency
  6997. */
  6998. this.l_buf = 0; /* buffer index for literals or lengths */
  6999. this.lit_bufsize = 0;
  7000. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7001. * limiting lit_bufsize to 64K:
  7002. * - frequencies can be kept in 16 bit counters
  7003. * - if compression is not successful for the first block, all input
  7004. * data is still in the window so we can still emit a stored block even
  7005. * when input comes from standard input. (This can also be done for
  7006. * all blocks if lit_bufsize is not greater than 32K.)
  7007. * - if compression is not successful for a file smaller than 64K, we can
  7008. * even emit a stored file instead of a stored block (saving 5 bytes).
  7009. * This is applicable only for zip (not gzip or zlib).
  7010. * - creating new Huffman trees less frequently may not provide fast
  7011. * adaptation to changes in the input data statistics. (Take for
  7012. * example a binary file with poorly compressible code followed by
  7013. * a highly compressible string table.) Smaller buffer sizes give
  7014. * fast adaptation but have of course the overhead of transmitting
  7015. * trees more frequently.
  7016. * - I can't count above 4
  7017. */
  7018. this.last_lit = 0; /* running index in l_buf */
  7019. this.d_buf = 0;
  7020. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7021. * the same number of elements. To use different lengths, an extra flag
  7022. * array would be necessary.
  7023. */
  7024. this.opt_len = 0; /* bit length of current block with optimal trees */
  7025. this.static_len = 0; /* bit length of current block with static trees */
  7026. this.matches = 0; /* number of string matches in current block */
  7027. this.insert = 0; /* bytes at end of window left to insert */
  7028. this.bi_buf = 0;
  7029. /* Output buffer. bits are inserted starting at the bottom (least
  7030. * significant bits).
  7031. */
  7032. this.bi_valid = 0;
  7033. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7034. * are always zero.
  7035. */
  7036. // Used for window memory init. We safely ignore it for JS. That makes
  7037. // sense only for pointers and memory check tools.
  7038. //this.high_water = 0;
  7039. /* High water mark offset in window for initialized bytes -- bytes above
  7040. * this are set to zero in order to avoid memory check warnings when
  7041. * longest match routines access bytes past the input. This is then
  7042. * updated to the new high water mark.
  7043. */
  7044. }
  7045. function deflateResetKeep(strm) {
  7046. var s;
  7047. if (!strm || !strm.state) {
  7048. return err(strm, Z_STREAM_ERROR);
  7049. }
  7050. strm.total_in = strm.total_out = 0;
  7051. strm.data_type = Z_UNKNOWN;
  7052. s = strm.state;
  7053. s.pending = 0;
  7054. s.pending_out = 0;
  7055. if (s.wrap < 0) {
  7056. s.wrap = -s.wrap;
  7057. /* was made negative by deflate(..., Z_FINISH); */
  7058. }
  7059. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7060. strm.adler = (s.wrap === 2) ?
  7061. 0 // crc32(0, Z_NULL, 0)
  7062. :
  7063. 1; // adler32(0, Z_NULL, 0)
  7064. s.last_flush = Z_NO_FLUSH;
  7065. trees._tr_init(s);
  7066. return Z_OK;
  7067. }
  7068. function deflateReset(strm) {
  7069. var ret = deflateResetKeep(strm);
  7070. if (ret === Z_OK) {
  7071. lm_init(strm.state);
  7072. }
  7073. return ret;
  7074. }
  7075. function deflateSetHeader(strm, head) {
  7076. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7077. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7078. strm.state.gzhead = head;
  7079. return Z_OK;
  7080. }
  7081. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7082. if (!strm) { // === Z_NULL
  7083. return Z_STREAM_ERROR;
  7084. }
  7085. var wrap = 1;
  7086. if (level === Z_DEFAULT_COMPRESSION) {
  7087. level = 6;
  7088. }
  7089. if (windowBits < 0) { /* suppress zlib wrapper */
  7090. wrap = 0;
  7091. windowBits = -windowBits;
  7092. }
  7093. else if (windowBits > 15) {
  7094. wrap = 2; /* write gzip wrapper instead */
  7095. windowBits -= 16;
  7096. }
  7097. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7098. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7099. strategy < 0 || strategy > Z_FIXED) {
  7100. return err(strm, Z_STREAM_ERROR);
  7101. }
  7102. if (windowBits === 8) {
  7103. windowBits = 9;
  7104. }
  7105. /* until 256-byte window bug fixed */
  7106. var s = new DeflateState();
  7107. strm.state = s;
  7108. s.strm = strm;
  7109. s.wrap = wrap;
  7110. s.gzhead = null;
  7111. s.w_bits = windowBits;
  7112. s.w_size = 1 << s.w_bits;
  7113. s.w_mask = s.w_size - 1;
  7114. s.hash_bits = memLevel + 7;
  7115. s.hash_size = 1 << s.hash_bits;
  7116. s.hash_mask = s.hash_size - 1;
  7117. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7118. s.window = new utils.Buf8(s.w_size * 2);
  7119. s.head = new utils.Buf16(s.hash_size);
  7120. s.prev = new utils.Buf16(s.w_size);
  7121. // Don't need mem init magic for JS.
  7122. //s.high_water = 0; /* nothing written to s->window yet */
  7123. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7124. s.pending_buf_size = s.lit_bufsize * 4;
  7125. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7126. //s->pending_buf = (uchf *) overlay;
  7127. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7128. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7129. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7130. s.d_buf = 1 * s.lit_bufsize;
  7131. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7132. s.l_buf = (1 + 2) * s.lit_bufsize;
  7133. s.level = level;
  7134. s.strategy = strategy;
  7135. s.method = method;
  7136. return deflateReset(strm);
  7137. }
  7138. function deflateInit(strm, level) {
  7139. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7140. }
  7141. function deflate(strm, flush) {
  7142. var old_flush, s;
  7143. var beg, val; // for gzip header write only
  7144. if (!strm || !strm.state ||
  7145. flush > Z_BLOCK || flush < 0) {
  7146. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7147. }
  7148. s = strm.state;
  7149. if (!strm.output ||
  7150. (!strm.input && strm.avail_in !== 0) ||
  7151. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7152. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7153. }
  7154. s.strm = strm; /* just in case */
  7155. old_flush = s.last_flush;
  7156. s.last_flush = flush;
  7157. /* Write the header */
  7158. if (s.status === INIT_STATE) {
  7159. if (s.wrap === 2) { // GZIP header
  7160. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7161. put_byte(s, 31);
  7162. put_byte(s, 139);
  7163. put_byte(s, 8);
  7164. if (!s.gzhead) { // s->gzhead == Z_NULL
  7165. put_byte(s, 0);
  7166. put_byte(s, 0);
  7167. put_byte(s, 0);
  7168. put_byte(s, 0);
  7169. put_byte(s, 0);
  7170. put_byte(s, s.level === 9 ? 2 :
  7171. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7172. 4 : 0));
  7173. put_byte(s, OS_CODE);
  7174. s.status = BUSY_STATE;
  7175. }
  7176. else {
  7177. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7178. (s.gzhead.hcrc ? 2 : 0) +
  7179. (!s.gzhead.extra ? 0 : 4) +
  7180. (!s.gzhead.name ? 0 : 8) +
  7181. (!s.gzhead.comment ? 0 : 16)
  7182. );
  7183. put_byte(s, s.gzhead.time & 0xff);
  7184. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7185. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7186. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7187. put_byte(s, s.level === 9 ? 2 :
  7188. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7189. 4 : 0));
  7190. put_byte(s, s.gzhead.os & 0xff);
  7191. if (s.gzhead.extra && s.gzhead.extra.length) {
  7192. put_byte(s, s.gzhead.extra.length & 0xff);
  7193. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7194. }
  7195. if (s.gzhead.hcrc) {
  7196. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7197. }
  7198. s.gzindex = 0;
  7199. s.status = EXTRA_STATE;
  7200. }
  7201. }
  7202. else // DEFLATE header
  7203. {
  7204. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7205. var level_flags = -1;
  7206. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7207. level_flags = 0;
  7208. } else if (s.level < 6) {
  7209. level_flags = 1;
  7210. } else if (s.level === 6) {
  7211. level_flags = 2;
  7212. } else {
  7213. level_flags = 3;
  7214. }
  7215. header |= (level_flags << 6);
  7216. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7217. header += 31 - (header % 31);
  7218. s.status = BUSY_STATE;
  7219. putShortMSB(s, header);
  7220. /* Save the adler32 of the preset dictionary: */
  7221. if (s.strstart !== 0) {
  7222. putShortMSB(s, strm.adler >>> 16);
  7223. putShortMSB(s, strm.adler & 0xffff);
  7224. }
  7225. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7226. }
  7227. }
  7228. //#ifdef GZIP
  7229. if (s.status === EXTRA_STATE) {
  7230. if (s.gzhead.extra/* != Z_NULL*/) {
  7231. beg = s.pending; /* start of bytes to update crc */
  7232. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7233. if (s.pending === s.pending_buf_size) {
  7234. if (s.gzhead.hcrc && s.pending > beg) {
  7235. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7236. }
  7237. flush_pending(strm);
  7238. beg = s.pending;
  7239. if (s.pending === s.pending_buf_size) {
  7240. break;
  7241. }
  7242. }
  7243. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7244. s.gzindex++;
  7245. }
  7246. if (s.gzhead.hcrc && s.pending > beg) {
  7247. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7248. }
  7249. if (s.gzindex === s.gzhead.extra.length) {
  7250. s.gzindex = 0;
  7251. s.status = NAME_STATE;
  7252. }
  7253. }
  7254. else {
  7255. s.status = NAME_STATE;
  7256. }
  7257. }
  7258. if (s.status === NAME_STATE) {
  7259. if (s.gzhead.name/* != Z_NULL*/) {
  7260. beg = s.pending; /* start of bytes to update crc */
  7261. //int val;
  7262. do {
  7263. if (s.pending === s.pending_buf_size) {
  7264. if (s.gzhead.hcrc && s.pending > beg) {
  7265. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7266. }
  7267. flush_pending(strm);
  7268. beg = s.pending;
  7269. if (s.pending === s.pending_buf_size) {
  7270. val = 1;
  7271. break;
  7272. }
  7273. }
  7274. // JS specific: little magic to add zero terminator to end of string
  7275. if (s.gzindex < s.gzhead.name.length) {
  7276. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7277. } else {
  7278. val = 0;
  7279. }
  7280. put_byte(s, val);
  7281. } while (val !== 0);
  7282. if (s.gzhead.hcrc && s.pending > beg) {
  7283. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7284. }
  7285. if (val === 0) {
  7286. s.gzindex = 0;
  7287. s.status = COMMENT_STATE;
  7288. }
  7289. }
  7290. else {
  7291. s.status = COMMENT_STATE;
  7292. }
  7293. }
  7294. if (s.status === COMMENT_STATE) {
  7295. if (s.gzhead.comment/* != Z_NULL*/) {
  7296. beg = s.pending; /* start of bytes to update crc */
  7297. //int val;
  7298. do {
  7299. if (s.pending === s.pending_buf_size) {
  7300. if (s.gzhead.hcrc && s.pending > beg) {
  7301. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7302. }
  7303. flush_pending(strm);
  7304. beg = s.pending;
  7305. if (s.pending === s.pending_buf_size) {
  7306. val = 1;
  7307. break;
  7308. }
  7309. }
  7310. // JS specific: little magic to add zero terminator to end of string
  7311. if (s.gzindex < s.gzhead.comment.length) {
  7312. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7313. } else {
  7314. val = 0;
  7315. }
  7316. put_byte(s, val);
  7317. } while (val !== 0);
  7318. if (s.gzhead.hcrc && s.pending > beg) {
  7319. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7320. }
  7321. if (val === 0) {
  7322. s.status = HCRC_STATE;
  7323. }
  7324. }
  7325. else {
  7326. s.status = HCRC_STATE;
  7327. }
  7328. }
  7329. if (s.status === HCRC_STATE) {
  7330. if (s.gzhead.hcrc) {
  7331. if (s.pending + 2 > s.pending_buf_size) {
  7332. flush_pending(strm);
  7333. }
  7334. if (s.pending + 2 <= s.pending_buf_size) {
  7335. put_byte(s, strm.adler & 0xff);
  7336. put_byte(s, (strm.adler >> 8) & 0xff);
  7337. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7338. s.status = BUSY_STATE;
  7339. }
  7340. }
  7341. else {
  7342. s.status = BUSY_STATE;
  7343. }
  7344. }
  7345. //#endif
  7346. /* Flush as much pending output as possible */
  7347. if (s.pending !== 0) {
  7348. flush_pending(strm);
  7349. if (strm.avail_out === 0) {
  7350. /* Since avail_out is 0, deflate will be called again with
  7351. * more output space, but possibly with both pending and
  7352. * avail_in equal to zero. There won't be anything to do,
  7353. * but this is not an error situation so make sure we
  7354. * return OK instead of BUF_ERROR at next call of deflate:
  7355. */
  7356. s.last_flush = -1;
  7357. return Z_OK;
  7358. }
  7359. /* Make sure there is something to do and avoid duplicate consecutive
  7360. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7361. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7362. */
  7363. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7364. flush !== Z_FINISH) {
  7365. return err(strm, Z_BUF_ERROR);
  7366. }
  7367. /* User must not provide more input after the first FINISH: */
  7368. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7369. return err(strm, Z_BUF_ERROR);
  7370. }
  7371. /* Start a new block or continue the current one.
  7372. */
  7373. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7374. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7375. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7376. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7377. configuration_table[s.level].func(s, flush));
  7378. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7379. s.status = FINISH_STATE;
  7380. }
  7381. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7382. if (strm.avail_out === 0) {
  7383. s.last_flush = -1;
  7384. /* avoid BUF_ERROR next call, see above */
  7385. }
  7386. return Z_OK;
  7387. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7388. * of deflate should use the same flush parameter to make sure
  7389. * that the flush is complete. So we don't have to output an
  7390. * empty block here, this will be done at next call. This also
  7391. * ensures that for a very small output buffer, we emit at most
  7392. * one empty block.
  7393. */
  7394. }
  7395. if (bstate === BS_BLOCK_DONE) {
  7396. if (flush === Z_PARTIAL_FLUSH) {
  7397. trees._tr_align(s);
  7398. }
  7399. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7400. trees._tr_stored_block(s, 0, 0, false);
  7401. /* For a full flush, this empty block will be recognized
  7402. * as a special marker by inflate_sync().
  7403. */
  7404. if (flush === Z_FULL_FLUSH) {
  7405. /*** CLEAR_HASH(s); ***/ /* forget history */
  7406. zero(s.head); // Fill with NIL (= 0);
  7407. if (s.lookahead === 0) {
  7408. s.strstart = 0;
  7409. s.block_start = 0;
  7410. s.insert = 0;
  7411. }
  7412. }
  7413. }
  7414. flush_pending(strm);
  7415. if (strm.avail_out === 0) {
  7416. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7417. return Z_OK;
  7418. }
  7419. }
  7420. }
  7421. //Assert(strm->avail_out > 0, "bug2");
  7422. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7423. if (flush !== Z_FINISH) { return Z_OK; }
  7424. if (s.wrap <= 0) { return Z_STREAM_END; }
  7425. /* Write the trailer */
  7426. if (s.wrap === 2) {
  7427. put_byte(s, strm.adler & 0xff);
  7428. put_byte(s, (strm.adler >> 8) & 0xff);
  7429. put_byte(s, (strm.adler >> 16) & 0xff);
  7430. put_byte(s, (strm.adler >> 24) & 0xff);
  7431. put_byte(s, strm.total_in & 0xff);
  7432. put_byte(s, (strm.total_in >> 8) & 0xff);
  7433. put_byte(s, (strm.total_in >> 16) & 0xff);
  7434. put_byte(s, (strm.total_in >> 24) & 0xff);
  7435. }
  7436. else
  7437. {
  7438. putShortMSB(s, strm.adler >>> 16);
  7439. putShortMSB(s, strm.adler & 0xffff);
  7440. }
  7441. flush_pending(strm);
  7442. /* If avail_out is zero, the application will call deflate again
  7443. * to flush the rest.
  7444. */
  7445. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7446. /* write the trailer only once! */
  7447. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7448. }
  7449. function deflateEnd(strm) {
  7450. var status;
  7451. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7452. return Z_STREAM_ERROR;
  7453. }
  7454. status = strm.state.status;
  7455. if (status !== INIT_STATE &&
  7456. status !== EXTRA_STATE &&
  7457. status !== NAME_STATE &&
  7458. status !== COMMENT_STATE &&
  7459. status !== HCRC_STATE &&
  7460. status !== BUSY_STATE &&
  7461. status !== FINISH_STATE
  7462. ) {
  7463. return err(strm, Z_STREAM_ERROR);
  7464. }
  7465. strm.state = null;
  7466. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7467. }
  7468. /* =========================================================================
  7469. * Initializes the compression dictionary from the given byte
  7470. * sequence without producing any compressed output.
  7471. */
  7472. function deflateSetDictionary(strm, dictionary) {
  7473. var dictLength = dictionary.length;
  7474. var s;
  7475. var str, n;
  7476. var wrap;
  7477. var avail;
  7478. var next;
  7479. var input;
  7480. var tmpDict;
  7481. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7482. return Z_STREAM_ERROR;
  7483. }
  7484. s = strm.state;
  7485. wrap = s.wrap;
  7486. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7487. return Z_STREAM_ERROR;
  7488. }
  7489. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7490. if (wrap === 1) {
  7491. /* adler32(strm->adler, dictionary, dictLength); */
  7492. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7493. }
  7494. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  7495. /* if dictionary would fill window, just replace the history */
  7496. if (dictLength >= s.w_size) {
  7497. if (wrap === 0) { /* already empty otherwise */
  7498. /*** CLEAR_HASH(s); ***/
  7499. zero(s.head); // Fill with NIL (= 0);
  7500. s.strstart = 0;
  7501. s.block_start = 0;
  7502. s.insert = 0;
  7503. }
  7504. /* use the tail */
  7505. // dictionary = dictionary.slice(dictLength - s.w_size);
  7506. tmpDict = new utils.Buf8(s.w_size);
  7507. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7508. dictionary = tmpDict;
  7509. dictLength = s.w_size;
  7510. }
  7511. /* insert dictionary into window and hash */
  7512. avail = strm.avail_in;
  7513. next = strm.next_in;
  7514. input = strm.input;
  7515. strm.avail_in = dictLength;
  7516. strm.next_in = 0;
  7517. strm.input = dictionary;
  7518. fill_window(s);
  7519. while (s.lookahead >= MIN_MATCH) {
  7520. str = s.strstart;
  7521. n = s.lookahead - (MIN_MATCH - 1);
  7522. do {
  7523. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7524. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7525. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7526. s.head[s.ins_h] = str;
  7527. str++;
  7528. } while (--n);
  7529. s.strstart = str;
  7530. s.lookahead = MIN_MATCH - 1;
  7531. fill_window(s);
  7532. }
  7533. s.strstart += s.lookahead;
  7534. s.block_start = s.strstart;
  7535. s.insert = s.lookahead;
  7536. s.lookahead = 0;
  7537. s.match_length = s.prev_length = MIN_MATCH - 1;
  7538. s.match_available = 0;
  7539. strm.next_in = next;
  7540. strm.input = input;
  7541. strm.avail_in = avail;
  7542. s.wrap = wrap;
  7543. return Z_OK;
  7544. }
  7545. exports.deflateInit = deflateInit;
  7546. exports.deflateInit2 = deflateInit2;
  7547. exports.deflateReset = deflateReset;
  7548. exports.deflateResetKeep = deflateResetKeep;
  7549. exports.deflateSetHeader = deflateSetHeader;
  7550. exports.deflate = deflate;
  7551. exports.deflateEnd = deflateEnd;
  7552. exports.deflateSetDictionary = deflateSetDictionary;
  7553. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7554. /* Not implemented
  7555. exports.deflateBound = deflateBound;
  7556. exports.deflateCopy = deflateCopy;
  7557. exports.deflateParams = deflateParams;
  7558. exports.deflatePending = deflatePending;
  7559. exports.deflatePrime = deflatePrime;
  7560. exports.deflateTune = deflateTune;
  7561. */
  7562. },{"../utils/common":35,"./adler32":36,"./crc32":38,"./messages":43,"./trees":44}],40:[function(require,module,exports){
  7563. 'use strict';
  7564. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7565. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7566. //
  7567. // This software is provided 'as-is', without any express or implied
  7568. // warranty. In no event will the authors be held liable for any damages
  7569. // arising from the use of this software.
  7570. //
  7571. // Permission is granted to anyone to use this software for any purpose,
  7572. // including commercial applications, and to alter it and redistribute it
  7573. // freely, subject to the following restrictions:
  7574. //
  7575. // 1. The origin of this software must not be misrepresented; you must not
  7576. // claim that you wrote the original software. If you use this software
  7577. // in a product, an acknowledgment in the product documentation would be
  7578. // appreciated but is not required.
  7579. // 2. Altered source versions must be plainly marked as such, and must not be
  7580. // misrepresented as being the original software.
  7581. // 3. This notice may not be removed or altered from any source distribution.
  7582. // See state defs from inflate.js
  7583. var BAD = 30; /* got a data error -- remain here until reset */
  7584. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7585. /*
  7586. Decode literal, length, and distance codes and write out the resulting
  7587. literal and match bytes until either not enough input or output is
  7588. available, an end-of-block is encountered, or a data error is encountered.
  7589. When large enough input and output buffers are supplied to inflate(), for
  7590. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7591. inflate execution time is spent in this routine.
  7592. Entry assumptions:
  7593. state.mode === LEN
  7594. strm.avail_in >= 6
  7595. strm.avail_out >= 258
  7596. start >= strm.avail_out
  7597. state.bits < 8
  7598. On return, state.mode is one of:
  7599. LEN -- ran out of enough output space or enough available input
  7600. TYPE -- reached end of block code, inflate() to interpret next block
  7601. BAD -- error in block data
  7602. Notes:
  7603. - The maximum input bits used by a length/distance pair is 15 bits for the
  7604. length code, 5 bits for the length extra, 15 bits for the distance code,
  7605. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7606. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7607. checking for available input while decoding.
  7608. - The maximum bytes that a single length/distance pair can output is 258
  7609. bytes, which is the maximum length that can be coded. inflate_fast()
  7610. requires strm.avail_out >= 258 for each loop to avoid checking for
  7611. output space.
  7612. */
  7613. module.exports = function inflate_fast(strm, start) {
  7614. var state;
  7615. var _in; /* local strm.input */
  7616. var last; /* have enough input while in < last */
  7617. var _out; /* local strm.output */
  7618. var beg; /* inflate()'s initial strm.output */
  7619. var end; /* while out < end, enough space available */
  7620. //#ifdef INFLATE_STRICT
  7621. var dmax; /* maximum distance from zlib header */
  7622. //#endif
  7623. var wsize; /* window size or zero if not using window */
  7624. var whave; /* valid bytes in the window */
  7625. var wnext; /* window write index */
  7626. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  7627. var s_window; /* allocated sliding window, if wsize != 0 */
  7628. var hold; /* local strm.hold */
  7629. var bits; /* local strm.bits */
  7630. var lcode; /* local strm.lencode */
  7631. var dcode; /* local strm.distcode */
  7632. var lmask; /* mask for first level of length codes */
  7633. var dmask; /* mask for first level of distance codes */
  7634. var here; /* retrieved table entry */
  7635. var op; /* code bits, operation, extra bits, or */
  7636. /* window position, window bytes to copy */
  7637. var len; /* match length, unused bytes */
  7638. var dist; /* match distance */
  7639. var from; /* where to copy match from */
  7640. var from_source;
  7641. var input, output; // JS specific, because we have no pointers
  7642. /* copy state to local variables */
  7643. state = strm.state;
  7644. //here = state.here;
  7645. _in = strm.next_in;
  7646. input = strm.input;
  7647. last = _in + (strm.avail_in - 5);
  7648. _out = strm.next_out;
  7649. output = strm.output;
  7650. beg = _out - (start - strm.avail_out);
  7651. end = _out + (strm.avail_out - 257);
  7652. //#ifdef INFLATE_STRICT
  7653. dmax = state.dmax;
  7654. //#endif
  7655. wsize = state.wsize;
  7656. whave = state.whave;
  7657. wnext = state.wnext;
  7658. s_window = state.window;
  7659. hold = state.hold;
  7660. bits = state.bits;
  7661. lcode = state.lencode;
  7662. dcode = state.distcode;
  7663. lmask = (1 << state.lenbits) - 1;
  7664. dmask = (1 << state.distbits) - 1;
  7665. /* decode literals and length/distances until end-of-block or not enough
  7666. input data or output space */
  7667. top:
  7668. do {
  7669. if (bits < 15) {
  7670. hold += input[_in++] << bits;
  7671. bits += 8;
  7672. hold += input[_in++] << bits;
  7673. bits += 8;
  7674. }
  7675. here = lcode[hold & lmask];
  7676. dolen:
  7677. for (;;) { // Goto emulation
  7678. op = here >>> 24/*here.bits*/;
  7679. hold >>>= op;
  7680. bits -= op;
  7681. op = (here >>> 16) & 0xff/*here.op*/;
  7682. if (op === 0) { /* literal */
  7683. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7684. // "inflate: literal '%c'\n" :
  7685. // "inflate: literal 0x%02x\n", here.val));
  7686. output[_out++] = here & 0xffff/*here.val*/;
  7687. }
  7688. else if (op & 16) { /* length base */
  7689. len = here & 0xffff/*here.val*/;
  7690. op &= 15; /* number of extra bits */
  7691. if (op) {
  7692. if (bits < op) {
  7693. hold += input[_in++] << bits;
  7694. bits += 8;
  7695. }
  7696. len += hold & ((1 << op) - 1);
  7697. hold >>>= op;
  7698. bits -= op;
  7699. }
  7700. //Tracevv((stderr, "inflate: length %u\n", len));
  7701. if (bits < 15) {
  7702. hold += input[_in++] << bits;
  7703. bits += 8;
  7704. hold += input[_in++] << bits;
  7705. bits += 8;
  7706. }
  7707. here = dcode[hold & dmask];
  7708. dodist:
  7709. for (;;) { // goto emulation
  7710. op = here >>> 24/*here.bits*/;
  7711. hold >>>= op;
  7712. bits -= op;
  7713. op = (here >>> 16) & 0xff/*here.op*/;
  7714. if (op & 16) { /* distance base */
  7715. dist = here & 0xffff/*here.val*/;
  7716. op &= 15; /* number of extra bits */
  7717. if (bits < op) {
  7718. hold += input[_in++] << bits;
  7719. bits += 8;
  7720. if (bits < op) {
  7721. hold += input[_in++] << bits;
  7722. bits += 8;
  7723. }
  7724. }
  7725. dist += hold & ((1 << op) - 1);
  7726. //#ifdef INFLATE_STRICT
  7727. if (dist > dmax) {
  7728. strm.msg = 'invalid distance too far back';
  7729. state.mode = BAD;
  7730. break top;
  7731. }
  7732. //#endif
  7733. hold >>>= op;
  7734. bits -= op;
  7735. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7736. op = _out - beg; /* max distance in output */
  7737. if (dist > op) { /* see if copy from window */
  7738. op = dist - op; /* distance back in window */
  7739. if (op > whave) {
  7740. if (state.sane) {
  7741. strm.msg = 'invalid distance too far back';
  7742. state.mode = BAD;
  7743. break top;
  7744. }
  7745. // (!) This block is disabled in zlib defaults,
  7746. // don't enable it for binary compatibility
  7747. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7748. // if (len <= op - whave) {
  7749. // do {
  7750. // output[_out++] = 0;
  7751. // } while (--len);
  7752. // continue top;
  7753. // }
  7754. // len -= op - whave;
  7755. // do {
  7756. // output[_out++] = 0;
  7757. // } while (--op > whave);
  7758. // if (op === 0) {
  7759. // from = _out - dist;
  7760. // do {
  7761. // output[_out++] = output[from++];
  7762. // } while (--len);
  7763. // continue top;
  7764. // }
  7765. //#endif
  7766. }
  7767. from = 0; // window index
  7768. from_source = s_window;
  7769. if (wnext === 0) { /* very common case */
  7770. from += wsize - op;
  7771. if (op < len) { /* some from window */
  7772. len -= op;
  7773. do {
  7774. output[_out++] = s_window[from++];
  7775. } while (--op);
  7776. from = _out - dist; /* rest from output */
  7777. from_source = output;
  7778. }
  7779. }
  7780. else if (wnext < op) { /* wrap around window */
  7781. from += wsize + wnext - op;
  7782. op -= wnext;
  7783. if (op < len) { /* some from end of window */
  7784. len -= op;
  7785. do {
  7786. output[_out++] = s_window[from++];
  7787. } while (--op);
  7788. from = 0;
  7789. if (wnext < len) { /* some from start of window */
  7790. op = wnext;
  7791. len -= op;
  7792. do {
  7793. output[_out++] = s_window[from++];
  7794. } while (--op);
  7795. from = _out - dist; /* rest from output */
  7796. from_source = output;
  7797. }
  7798. }
  7799. }
  7800. else { /* contiguous in window */
  7801. from += wnext - op;
  7802. if (op < len) { /* some from window */
  7803. len -= op;
  7804. do {
  7805. output[_out++] = s_window[from++];
  7806. } while (--op);
  7807. from = _out - dist; /* rest from output */
  7808. from_source = output;
  7809. }
  7810. }
  7811. while (len > 2) {
  7812. output[_out++] = from_source[from++];
  7813. output[_out++] = from_source[from++];
  7814. output[_out++] = from_source[from++];
  7815. len -= 3;
  7816. }
  7817. if (len) {
  7818. output[_out++] = from_source[from++];
  7819. if (len > 1) {
  7820. output[_out++] = from_source[from++];
  7821. }
  7822. }
  7823. }
  7824. else {
  7825. from = _out - dist; /* copy direct from output */
  7826. do { /* minimum length is three */
  7827. output[_out++] = output[from++];
  7828. output[_out++] = output[from++];
  7829. output[_out++] = output[from++];
  7830. len -= 3;
  7831. } while (len > 2);
  7832. if (len) {
  7833. output[_out++] = output[from++];
  7834. if (len > 1) {
  7835. output[_out++] = output[from++];
  7836. }
  7837. }
  7838. }
  7839. }
  7840. else if ((op & 64) === 0) { /* 2nd level distance code */
  7841. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7842. continue dodist;
  7843. }
  7844. else {
  7845. strm.msg = 'invalid distance code';
  7846. state.mode = BAD;
  7847. break top;
  7848. }
  7849. break; // need to emulate goto via "continue"
  7850. }
  7851. }
  7852. else if ((op & 64) === 0) { /* 2nd level length code */
  7853. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7854. continue dolen;
  7855. }
  7856. else if (op & 32) { /* end-of-block */
  7857. //Tracevv((stderr, "inflate: end of block\n"));
  7858. state.mode = TYPE;
  7859. break top;
  7860. }
  7861. else {
  7862. strm.msg = 'invalid literal/length code';
  7863. state.mode = BAD;
  7864. break top;
  7865. }
  7866. break; // need to emulate goto via "continue"
  7867. }
  7868. } while (_in < last && _out < end);
  7869. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  7870. len = bits >> 3;
  7871. _in -= len;
  7872. bits -= len << 3;
  7873. hold &= (1 << bits) - 1;
  7874. /* update state and return */
  7875. strm.next_in = _in;
  7876. strm.next_out = _out;
  7877. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  7878. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  7879. state.hold = hold;
  7880. state.bits = bits;
  7881. return;
  7882. };
  7883. },{}],41:[function(require,module,exports){
  7884. 'use strict';
  7885. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7886. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7887. //
  7888. // This software is provided 'as-is', without any express or implied
  7889. // warranty. In no event will the authors be held liable for any damages
  7890. // arising from the use of this software.
  7891. //
  7892. // Permission is granted to anyone to use this software for any purpose,
  7893. // including commercial applications, and to alter it and redistribute it
  7894. // freely, subject to the following restrictions:
  7895. //
  7896. // 1. The origin of this software must not be misrepresented; you must not
  7897. // claim that you wrote the original software. If you use this software
  7898. // in a product, an acknowledgment in the product documentation would be
  7899. // appreciated but is not required.
  7900. // 2. Altered source versions must be plainly marked as such, and must not be
  7901. // misrepresented as being the original software.
  7902. // 3. This notice may not be removed or altered from any source distribution.
  7903. var utils = require('../utils/common');
  7904. var adler32 = require('./adler32');
  7905. var crc32 = require('./crc32');
  7906. var inflate_fast = require('./inffast');
  7907. var inflate_table = require('./inftrees');
  7908. var CODES = 0;
  7909. var LENS = 1;
  7910. var DISTS = 2;
  7911. /* Public constants ==========================================================*/
  7912. /* ===========================================================================*/
  7913. /* Allowed flush values; see deflate() and inflate() below for details */
  7914. //var Z_NO_FLUSH = 0;
  7915. //var Z_PARTIAL_FLUSH = 1;
  7916. //var Z_SYNC_FLUSH = 2;
  7917. //var Z_FULL_FLUSH = 3;
  7918. var Z_FINISH = 4;
  7919. var Z_BLOCK = 5;
  7920. var Z_TREES = 6;
  7921. /* Return codes for the compression/decompression functions. Negative values
  7922. * are errors, positive values are used for special but normal events.
  7923. */
  7924. var Z_OK = 0;
  7925. var Z_STREAM_END = 1;
  7926. var Z_NEED_DICT = 2;
  7927. //var Z_ERRNO = -1;
  7928. var Z_STREAM_ERROR = -2;
  7929. var Z_DATA_ERROR = -3;
  7930. var Z_MEM_ERROR = -4;
  7931. var Z_BUF_ERROR = -5;
  7932. //var Z_VERSION_ERROR = -6;
  7933. /* The deflate compression method */
  7934. var Z_DEFLATED = 8;
  7935. /* STATES ====================================================================*/
  7936. /* ===========================================================================*/
  7937. var HEAD = 1; /* i: waiting for magic header */
  7938. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  7939. var TIME = 3; /* i: waiting for modification time (gzip) */
  7940. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  7941. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  7942. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  7943. var NAME = 7; /* i: waiting for end of file name (gzip) */
  7944. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  7945. var HCRC = 9; /* i: waiting for header crc (gzip) */
  7946. var DICTID = 10; /* i: waiting for dictionary check value */
  7947. var DICT = 11; /* waiting for inflateSetDictionary() call */
  7948. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7949. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  7950. var STORED = 14; /* i: waiting for stored size (length and complement) */
  7951. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  7952. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  7953. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  7954. var LENLENS = 18; /* i: waiting for code length code lengths */
  7955. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  7956. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  7957. var LEN = 21; /* i: waiting for length/lit/eob code */
  7958. var LENEXT = 22; /* i: waiting for length extra bits */
  7959. var DIST = 23; /* i: waiting for distance code */
  7960. var DISTEXT = 24; /* i: waiting for distance extra bits */
  7961. var MATCH = 25; /* o: waiting for output space to copy string */
  7962. var LIT = 26; /* o: waiting for output space to write literal */
  7963. var CHECK = 27; /* i: waiting for 32-bit check value */
  7964. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  7965. var DONE = 29; /* finished check, done -- remain here until reset */
  7966. var BAD = 30; /* got a data error -- remain here until reset */
  7967. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  7968. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  7969. /* ===========================================================================*/
  7970. var ENOUGH_LENS = 852;
  7971. var ENOUGH_DISTS = 592;
  7972. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7973. var MAX_WBITS = 15;
  7974. /* 32K LZ77 window */
  7975. var DEF_WBITS = MAX_WBITS;
  7976. function zswap32(q) {
  7977. return (((q >>> 24) & 0xff) +
  7978. ((q >>> 8) & 0xff00) +
  7979. ((q & 0xff00) << 8) +
  7980. ((q & 0xff) << 24));
  7981. }
  7982. function InflateState() {
  7983. this.mode = 0; /* current inflate mode */
  7984. this.last = false; /* true if processing last block */
  7985. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7986. this.havedict = false; /* true if dictionary provided */
  7987. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  7988. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  7989. this.check = 0; /* protected copy of check value */
  7990. this.total = 0; /* protected copy of output count */
  7991. // TODO: may be {}
  7992. this.head = null; /* where to save gzip header information */
  7993. /* sliding window */
  7994. this.wbits = 0; /* log base 2 of requested window size */
  7995. this.wsize = 0; /* window size or zero if not using window */
  7996. this.whave = 0; /* valid bytes in the window */
  7997. this.wnext = 0; /* window write index */
  7998. this.window = null; /* allocated sliding window, if needed */
  7999. /* bit accumulator */
  8000. this.hold = 0; /* input bit accumulator */
  8001. this.bits = 0; /* number of bits in "in" */
  8002. /* for string and stored block copying */
  8003. this.length = 0; /* literal or length of data to copy */
  8004. this.offset = 0; /* distance back to copy string from */
  8005. /* for table and code decoding */
  8006. this.extra = 0; /* extra bits needed */
  8007. /* fixed and dynamic code tables */
  8008. this.lencode = null; /* starting table for length/literal codes */
  8009. this.distcode = null; /* starting table for distance codes */
  8010. this.lenbits = 0; /* index bits for lencode */
  8011. this.distbits = 0; /* index bits for distcode */
  8012. /* dynamic table building */
  8013. this.ncode = 0; /* number of code length code lengths */
  8014. this.nlen = 0; /* number of length code lengths */
  8015. this.ndist = 0; /* number of distance code lengths */
  8016. this.have = 0; /* number of code lengths in lens[] */
  8017. this.next = null; /* next available space in codes[] */
  8018. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8019. this.work = new utils.Buf16(288); /* work area for code table building */
  8020. /*
  8021. because we don't have pointers in js, we use lencode and distcode directly
  8022. as buffers so we don't need codes
  8023. */
  8024. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8025. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8026. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8027. this.sane = 0; /* if false, allow invalid distance too far */
  8028. this.back = 0; /* bits back of last unprocessed length/lit */
  8029. this.was = 0; /* initial length of match */
  8030. }
  8031. function inflateResetKeep(strm) {
  8032. var state;
  8033. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8034. state = strm.state;
  8035. strm.total_in = strm.total_out = state.total = 0;
  8036. strm.msg = ''; /*Z_NULL*/
  8037. if (state.wrap) { /* to support ill-conceived Java test suite */
  8038. strm.adler = state.wrap & 1;
  8039. }
  8040. state.mode = HEAD;
  8041. state.last = 0;
  8042. state.havedict = 0;
  8043. state.dmax = 32768;
  8044. state.head = null/*Z_NULL*/;
  8045. state.hold = 0;
  8046. state.bits = 0;
  8047. //state.lencode = state.distcode = state.next = state.codes;
  8048. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8049. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8050. state.sane = 1;
  8051. state.back = -1;
  8052. //Tracev((stderr, "inflate: reset\n"));
  8053. return Z_OK;
  8054. }
  8055. function inflateReset(strm) {
  8056. var state;
  8057. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8058. state = strm.state;
  8059. state.wsize = 0;
  8060. state.whave = 0;
  8061. state.wnext = 0;
  8062. return inflateResetKeep(strm);
  8063. }
  8064. function inflateReset2(strm, windowBits) {
  8065. var wrap;
  8066. var state;
  8067. /* get the state */
  8068. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8069. state = strm.state;
  8070. /* extract wrap request from windowBits parameter */
  8071. if (windowBits < 0) {
  8072. wrap = 0;
  8073. windowBits = -windowBits;
  8074. }
  8075. else {
  8076. wrap = (windowBits >> 4) + 1;
  8077. if (windowBits < 48) {
  8078. windowBits &= 15;
  8079. }
  8080. }
  8081. /* set number of window bits, free window if different */
  8082. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8083. return Z_STREAM_ERROR;
  8084. }
  8085. if (state.window !== null && state.wbits !== windowBits) {
  8086. state.window = null;
  8087. }
  8088. /* update state and reset the rest of it */
  8089. state.wrap = wrap;
  8090. state.wbits = windowBits;
  8091. return inflateReset(strm);
  8092. }
  8093. function inflateInit2(strm, windowBits) {
  8094. var ret;
  8095. var state;
  8096. if (!strm) { return Z_STREAM_ERROR; }
  8097. //strm.msg = Z_NULL; /* in case we return an error */
  8098. state = new InflateState();
  8099. //if (state === Z_NULL) return Z_MEM_ERROR;
  8100. //Tracev((stderr, "inflate: allocated\n"));
  8101. strm.state = state;
  8102. state.window = null/*Z_NULL*/;
  8103. ret = inflateReset2(strm, windowBits);
  8104. if (ret !== Z_OK) {
  8105. strm.state = null/*Z_NULL*/;
  8106. }
  8107. return ret;
  8108. }
  8109. function inflateInit(strm) {
  8110. return inflateInit2(strm, DEF_WBITS);
  8111. }
  8112. /*
  8113. Return state with length and distance decoding tables and index sizes set to
  8114. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8115. If BUILDFIXED is defined, then instead this routine builds the tables the
  8116. first time it's called, and returns those tables the first time and
  8117. thereafter. This reduces the size of the code by about 2K bytes, in
  8118. exchange for a little execution time. However, BUILDFIXED should not be
  8119. used for threaded applications, since the rewriting of the tables and virgin
  8120. may not be thread-safe.
  8121. */
  8122. var virgin = true;
  8123. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8124. function fixedtables(state) {
  8125. /* build fixed huffman tables if first call (may not be thread safe) */
  8126. if (virgin) {
  8127. var sym;
  8128. lenfix = new utils.Buf32(512);
  8129. distfix = new utils.Buf32(32);
  8130. /* literal/length table */
  8131. sym = 0;
  8132. while (sym < 144) { state.lens[sym++] = 8; }
  8133. while (sym < 256) { state.lens[sym++] = 9; }
  8134. while (sym < 280) { state.lens[sym++] = 7; }
  8135. while (sym < 288) { state.lens[sym++] = 8; }
  8136. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8137. /* distance table */
  8138. sym = 0;
  8139. while (sym < 32) { state.lens[sym++] = 5; }
  8140. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8141. /* do this just once */
  8142. virgin = false;
  8143. }
  8144. state.lencode = lenfix;
  8145. state.lenbits = 9;
  8146. state.distcode = distfix;
  8147. state.distbits = 5;
  8148. }
  8149. /*
  8150. Update the window with the last wsize (normally 32K) bytes written before
  8151. returning. If window does not exist yet, create it. This is only called
  8152. when a window is already in use, or when output has been written during this
  8153. inflate call, but the end of the deflate stream has not been reached yet.
  8154. It is also called to create a window for dictionary data when a dictionary
  8155. is loaded.
  8156. Providing output buffers larger than 32K to inflate() should provide a speed
  8157. advantage, since only the last 32K of output is copied to the sliding window
  8158. upon return from inflate(), and since all distances after the first 32K of
  8159. output will fall in the output data, making match copies simpler and faster.
  8160. The advantage may be dependent on the size of the processor's data caches.
  8161. */
  8162. function updatewindow(strm, src, end, copy) {
  8163. var dist;
  8164. var state = strm.state;
  8165. /* if it hasn't been done already, allocate space for the window */
  8166. if (state.window === null) {
  8167. state.wsize = 1 << state.wbits;
  8168. state.wnext = 0;
  8169. state.whave = 0;
  8170. state.window = new utils.Buf8(state.wsize);
  8171. }
  8172. /* copy state->wsize or less output bytes into the circular window */
  8173. if (copy >= state.wsize) {
  8174. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8175. state.wnext = 0;
  8176. state.whave = state.wsize;
  8177. }
  8178. else {
  8179. dist = state.wsize - state.wnext;
  8180. if (dist > copy) {
  8181. dist = copy;
  8182. }
  8183. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8184. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8185. copy -= dist;
  8186. if (copy) {
  8187. //zmemcpy(state->window, end - copy, copy);
  8188. utils.arraySet(state.window, src, end - copy, copy, 0);
  8189. state.wnext = copy;
  8190. state.whave = state.wsize;
  8191. }
  8192. else {
  8193. state.wnext += dist;
  8194. if (state.wnext === state.wsize) { state.wnext = 0; }
  8195. if (state.whave < state.wsize) { state.whave += dist; }
  8196. }
  8197. }
  8198. return 0;
  8199. }
  8200. function inflate(strm, flush) {
  8201. var state;
  8202. var input, output; // input/output buffers
  8203. var next; /* next input INDEX */
  8204. var put; /* next output INDEX */
  8205. var have, left; /* available input and output */
  8206. var hold; /* bit buffer */
  8207. var bits; /* bits in bit buffer */
  8208. var _in, _out; /* save starting available input and output */
  8209. var copy; /* number of stored or match bytes to copy */
  8210. var from; /* where to copy match bytes from */
  8211. var from_source;
  8212. var here = 0; /* current decoding table entry */
  8213. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8214. //var last; /* parent table entry */
  8215. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8216. var len; /* length to copy for repeats, bits to drop */
  8217. var ret; /* return code */
  8218. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8219. var opts;
  8220. var n; // temporary var for NEED_BITS
  8221. var order = /* permutation of code lengths */
  8222. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8223. if (!strm || !strm.state || !strm.output ||
  8224. (!strm.input && strm.avail_in !== 0)) {
  8225. return Z_STREAM_ERROR;
  8226. }
  8227. state = strm.state;
  8228. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8229. //--- LOAD() ---
  8230. put = strm.next_out;
  8231. output = strm.output;
  8232. left = strm.avail_out;
  8233. next = strm.next_in;
  8234. input = strm.input;
  8235. have = strm.avail_in;
  8236. hold = state.hold;
  8237. bits = state.bits;
  8238. //---
  8239. _in = have;
  8240. _out = left;
  8241. ret = Z_OK;
  8242. inf_leave: // goto emulation
  8243. for (;;) {
  8244. switch (state.mode) {
  8245. case HEAD:
  8246. if (state.wrap === 0) {
  8247. state.mode = TYPEDO;
  8248. break;
  8249. }
  8250. //=== NEEDBITS(16);
  8251. while (bits < 16) {
  8252. if (have === 0) { break inf_leave; }
  8253. have--;
  8254. hold += input[next++] << bits;
  8255. bits += 8;
  8256. }
  8257. //===//
  8258. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8259. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8260. //=== CRC2(state.check, hold);
  8261. hbuf[0] = hold & 0xff;
  8262. hbuf[1] = (hold >>> 8) & 0xff;
  8263. state.check = crc32(state.check, hbuf, 2, 0);
  8264. //===//
  8265. //=== INITBITS();
  8266. hold = 0;
  8267. bits = 0;
  8268. //===//
  8269. state.mode = FLAGS;
  8270. break;
  8271. }
  8272. state.flags = 0; /* expect zlib header */
  8273. if (state.head) {
  8274. state.head.done = false;
  8275. }
  8276. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8277. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8278. strm.msg = 'incorrect header check';
  8279. state.mode = BAD;
  8280. break;
  8281. }
  8282. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8283. strm.msg = 'unknown compression method';
  8284. state.mode = BAD;
  8285. break;
  8286. }
  8287. //--- DROPBITS(4) ---//
  8288. hold >>>= 4;
  8289. bits -= 4;
  8290. //---//
  8291. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8292. if (state.wbits === 0) {
  8293. state.wbits = len;
  8294. }
  8295. else if (len > state.wbits) {
  8296. strm.msg = 'invalid window size';
  8297. state.mode = BAD;
  8298. break;
  8299. }
  8300. state.dmax = 1 << len;
  8301. //Tracev((stderr, "inflate: zlib header ok\n"));
  8302. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8303. state.mode = hold & 0x200 ? DICTID : TYPE;
  8304. //=== INITBITS();
  8305. hold = 0;
  8306. bits = 0;
  8307. //===//
  8308. break;
  8309. case FLAGS:
  8310. //=== NEEDBITS(16); */
  8311. while (bits < 16) {
  8312. if (have === 0) { break inf_leave; }
  8313. have--;
  8314. hold += input[next++] << bits;
  8315. bits += 8;
  8316. }
  8317. //===//
  8318. state.flags = hold;
  8319. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8320. strm.msg = 'unknown compression method';
  8321. state.mode = BAD;
  8322. break;
  8323. }
  8324. if (state.flags & 0xe000) {
  8325. strm.msg = 'unknown header flags set';
  8326. state.mode = BAD;
  8327. break;
  8328. }
  8329. if (state.head) {
  8330. state.head.text = ((hold >> 8) & 1);
  8331. }
  8332. if (state.flags & 0x0200) {
  8333. //=== CRC2(state.check, hold);
  8334. hbuf[0] = hold & 0xff;
  8335. hbuf[1] = (hold >>> 8) & 0xff;
  8336. state.check = crc32(state.check, hbuf, 2, 0);
  8337. //===//
  8338. }
  8339. //=== INITBITS();
  8340. hold = 0;
  8341. bits = 0;
  8342. //===//
  8343. state.mode = TIME;
  8344. /* falls through */
  8345. case TIME:
  8346. //=== NEEDBITS(32); */
  8347. while (bits < 32) {
  8348. if (have === 0) { break inf_leave; }
  8349. have--;
  8350. hold += input[next++] << bits;
  8351. bits += 8;
  8352. }
  8353. //===//
  8354. if (state.head) {
  8355. state.head.time = hold;
  8356. }
  8357. if (state.flags & 0x0200) {
  8358. //=== CRC4(state.check, hold)
  8359. hbuf[0] = hold & 0xff;
  8360. hbuf[1] = (hold >>> 8) & 0xff;
  8361. hbuf[2] = (hold >>> 16) & 0xff;
  8362. hbuf[3] = (hold >>> 24) & 0xff;
  8363. state.check = crc32(state.check, hbuf, 4, 0);
  8364. //===
  8365. }
  8366. //=== INITBITS();
  8367. hold = 0;
  8368. bits = 0;
  8369. //===//
  8370. state.mode = OS;
  8371. /* falls through */
  8372. case OS:
  8373. //=== NEEDBITS(16); */
  8374. while (bits < 16) {
  8375. if (have === 0) { break inf_leave; }
  8376. have--;
  8377. hold += input[next++] << bits;
  8378. bits += 8;
  8379. }
  8380. //===//
  8381. if (state.head) {
  8382. state.head.xflags = (hold & 0xff);
  8383. state.head.os = (hold >> 8);
  8384. }
  8385. if (state.flags & 0x0200) {
  8386. //=== CRC2(state.check, hold);
  8387. hbuf[0] = hold & 0xff;
  8388. hbuf[1] = (hold >>> 8) & 0xff;
  8389. state.check = crc32(state.check, hbuf, 2, 0);
  8390. //===//
  8391. }
  8392. //=== INITBITS();
  8393. hold = 0;
  8394. bits = 0;
  8395. //===//
  8396. state.mode = EXLEN;
  8397. /* falls through */
  8398. case EXLEN:
  8399. if (state.flags & 0x0400) {
  8400. //=== NEEDBITS(16); */
  8401. while (bits < 16) {
  8402. if (have === 0) { break inf_leave; }
  8403. have--;
  8404. hold += input[next++] << bits;
  8405. bits += 8;
  8406. }
  8407. //===//
  8408. state.length = hold;
  8409. if (state.head) {
  8410. state.head.extra_len = hold;
  8411. }
  8412. if (state.flags & 0x0200) {
  8413. //=== CRC2(state.check, hold);
  8414. hbuf[0] = hold & 0xff;
  8415. hbuf[1] = (hold >>> 8) & 0xff;
  8416. state.check = crc32(state.check, hbuf, 2, 0);
  8417. //===//
  8418. }
  8419. //=== INITBITS();
  8420. hold = 0;
  8421. bits = 0;
  8422. //===//
  8423. }
  8424. else if (state.head) {
  8425. state.head.extra = null/*Z_NULL*/;
  8426. }
  8427. state.mode = EXTRA;
  8428. /* falls through */
  8429. case EXTRA:
  8430. if (state.flags & 0x0400) {
  8431. copy = state.length;
  8432. if (copy > have) { copy = have; }
  8433. if (copy) {
  8434. if (state.head) {
  8435. len = state.head.extra_len - state.length;
  8436. if (!state.head.extra) {
  8437. // Use untyped array for more convenient processing later
  8438. state.head.extra = new Array(state.head.extra_len);
  8439. }
  8440. utils.arraySet(
  8441. state.head.extra,
  8442. input,
  8443. next,
  8444. // extra field is limited to 65536 bytes
  8445. // - no need for additional size check
  8446. copy,
  8447. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8448. len
  8449. );
  8450. //zmemcpy(state.head.extra + len, next,
  8451. // len + copy > state.head.extra_max ?
  8452. // state.head.extra_max - len : copy);
  8453. }
  8454. if (state.flags & 0x0200) {
  8455. state.check = crc32(state.check, input, copy, next);
  8456. }
  8457. have -= copy;
  8458. next += copy;
  8459. state.length -= copy;
  8460. }
  8461. if (state.length) { break inf_leave; }
  8462. }
  8463. state.length = 0;
  8464. state.mode = NAME;
  8465. /* falls through */
  8466. case NAME:
  8467. if (state.flags & 0x0800) {
  8468. if (have === 0) { break inf_leave; }
  8469. copy = 0;
  8470. do {
  8471. // TODO: 2 or 1 bytes?
  8472. len = input[next + copy++];
  8473. /* use constant limit because in js we should not preallocate memory */
  8474. if (state.head && len &&
  8475. (state.length < 65536 /*state.head.name_max*/)) {
  8476. state.head.name += String.fromCharCode(len);
  8477. }
  8478. } while (len && copy < have);
  8479. if (state.flags & 0x0200) {
  8480. state.check = crc32(state.check, input, copy, next);
  8481. }
  8482. have -= copy;
  8483. next += copy;
  8484. if (len) { break inf_leave; }
  8485. }
  8486. else if (state.head) {
  8487. state.head.name = null;
  8488. }
  8489. state.length = 0;
  8490. state.mode = COMMENT;
  8491. /* falls through */
  8492. case COMMENT:
  8493. if (state.flags & 0x1000) {
  8494. if (have === 0) { break inf_leave; }
  8495. copy = 0;
  8496. do {
  8497. len = input[next + copy++];
  8498. /* use constant limit because in js we should not preallocate memory */
  8499. if (state.head && len &&
  8500. (state.length < 65536 /*state.head.comm_max*/)) {
  8501. state.head.comment += String.fromCharCode(len);
  8502. }
  8503. } while (len && copy < have);
  8504. if (state.flags & 0x0200) {
  8505. state.check = crc32(state.check, input, copy, next);
  8506. }
  8507. have -= copy;
  8508. next += copy;
  8509. if (len) { break inf_leave; }
  8510. }
  8511. else if (state.head) {
  8512. state.head.comment = null;
  8513. }
  8514. state.mode = HCRC;
  8515. /* falls through */
  8516. case HCRC:
  8517. if (state.flags & 0x0200) {
  8518. //=== NEEDBITS(16); */
  8519. while (bits < 16) {
  8520. if (have === 0) { break inf_leave; }
  8521. have--;
  8522. hold += input[next++] << bits;
  8523. bits += 8;
  8524. }
  8525. //===//
  8526. if (hold !== (state.check & 0xffff)) {
  8527. strm.msg = 'header crc mismatch';
  8528. state.mode = BAD;
  8529. break;
  8530. }
  8531. //=== INITBITS();
  8532. hold = 0;
  8533. bits = 0;
  8534. //===//
  8535. }
  8536. if (state.head) {
  8537. state.head.hcrc = ((state.flags >> 9) & 1);
  8538. state.head.done = true;
  8539. }
  8540. strm.adler = state.check = 0;
  8541. state.mode = TYPE;
  8542. break;
  8543. case DICTID:
  8544. //=== NEEDBITS(32); */
  8545. while (bits < 32) {
  8546. if (have === 0) { break inf_leave; }
  8547. have--;
  8548. hold += input[next++] << bits;
  8549. bits += 8;
  8550. }
  8551. //===//
  8552. strm.adler = state.check = zswap32(hold);
  8553. //=== INITBITS();
  8554. hold = 0;
  8555. bits = 0;
  8556. //===//
  8557. state.mode = DICT;
  8558. /* falls through */
  8559. case DICT:
  8560. if (state.havedict === 0) {
  8561. //--- RESTORE() ---
  8562. strm.next_out = put;
  8563. strm.avail_out = left;
  8564. strm.next_in = next;
  8565. strm.avail_in = have;
  8566. state.hold = hold;
  8567. state.bits = bits;
  8568. //---
  8569. return Z_NEED_DICT;
  8570. }
  8571. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8572. state.mode = TYPE;
  8573. /* falls through */
  8574. case TYPE:
  8575. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8576. /* falls through */
  8577. case TYPEDO:
  8578. if (state.last) {
  8579. //--- BYTEBITS() ---//
  8580. hold >>>= bits & 7;
  8581. bits -= bits & 7;
  8582. //---//
  8583. state.mode = CHECK;
  8584. break;
  8585. }
  8586. //=== NEEDBITS(3); */
  8587. while (bits < 3) {
  8588. if (have === 0) { break inf_leave; }
  8589. have--;
  8590. hold += input[next++] << bits;
  8591. bits += 8;
  8592. }
  8593. //===//
  8594. state.last = (hold & 0x01)/*BITS(1)*/;
  8595. //--- DROPBITS(1) ---//
  8596. hold >>>= 1;
  8597. bits -= 1;
  8598. //---//
  8599. switch ((hold & 0x03)/*BITS(2)*/) {
  8600. case 0: /* stored block */
  8601. //Tracev((stderr, "inflate: stored block%s\n",
  8602. // state.last ? " (last)" : ""));
  8603. state.mode = STORED;
  8604. break;
  8605. case 1: /* fixed block */
  8606. fixedtables(state);
  8607. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8608. // state.last ? " (last)" : ""));
  8609. state.mode = LEN_; /* decode codes */
  8610. if (flush === Z_TREES) {
  8611. //--- DROPBITS(2) ---//
  8612. hold >>>= 2;
  8613. bits -= 2;
  8614. //---//
  8615. break inf_leave;
  8616. }
  8617. break;
  8618. case 2: /* dynamic block */
  8619. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8620. // state.last ? " (last)" : ""));
  8621. state.mode = TABLE;
  8622. break;
  8623. case 3:
  8624. strm.msg = 'invalid block type';
  8625. state.mode = BAD;
  8626. }
  8627. //--- DROPBITS(2) ---//
  8628. hold >>>= 2;
  8629. bits -= 2;
  8630. //---//
  8631. break;
  8632. case STORED:
  8633. //--- BYTEBITS() ---// /* go to byte boundary */
  8634. hold >>>= bits & 7;
  8635. bits -= bits & 7;
  8636. //---//
  8637. //=== NEEDBITS(32); */
  8638. while (bits < 32) {
  8639. if (have === 0) { break inf_leave; }
  8640. have--;
  8641. hold += input[next++] << bits;
  8642. bits += 8;
  8643. }
  8644. //===//
  8645. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8646. strm.msg = 'invalid stored block lengths';
  8647. state.mode = BAD;
  8648. break;
  8649. }
  8650. state.length = hold & 0xffff;
  8651. //Tracev((stderr, "inflate: stored length %u\n",
  8652. // state.length));
  8653. //=== INITBITS();
  8654. hold = 0;
  8655. bits = 0;
  8656. //===//
  8657. state.mode = COPY_;
  8658. if (flush === Z_TREES) { break inf_leave; }
  8659. /* falls through */
  8660. case COPY_:
  8661. state.mode = COPY;
  8662. /* falls through */
  8663. case COPY:
  8664. copy = state.length;
  8665. if (copy) {
  8666. if (copy > have) { copy = have; }
  8667. if (copy > left) { copy = left; }
  8668. if (copy === 0) { break inf_leave; }
  8669. //--- zmemcpy(put, next, copy); ---
  8670. utils.arraySet(output, input, next, copy, put);
  8671. //---//
  8672. have -= copy;
  8673. next += copy;
  8674. left -= copy;
  8675. put += copy;
  8676. state.length -= copy;
  8677. break;
  8678. }
  8679. //Tracev((stderr, "inflate: stored end\n"));
  8680. state.mode = TYPE;
  8681. break;
  8682. case TABLE:
  8683. //=== NEEDBITS(14); */
  8684. while (bits < 14) {
  8685. if (have === 0) { break inf_leave; }
  8686. have--;
  8687. hold += input[next++] << bits;
  8688. bits += 8;
  8689. }
  8690. //===//
  8691. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  8692. //--- DROPBITS(5) ---//
  8693. hold >>>= 5;
  8694. bits -= 5;
  8695. //---//
  8696. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  8697. //--- DROPBITS(5) ---//
  8698. hold >>>= 5;
  8699. bits -= 5;
  8700. //---//
  8701. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  8702. //--- DROPBITS(4) ---//
  8703. hold >>>= 4;
  8704. bits -= 4;
  8705. //---//
  8706. //#ifndef PKZIP_BUG_WORKAROUND
  8707. if (state.nlen > 286 || state.ndist > 30) {
  8708. strm.msg = 'too many length or distance symbols';
  8709. state.mode = BAD;
  8710. break;
  8711. }
  8712. //#endif
  8713. //Tracev((stderr, "inflate: table sizes ok\n"));
  8714. state.have = 0;
  8715. state.mode = LENLENS;
  8716. /* falls through */
  8717. case LENLENS:
  8718. while (state.have < state.ncode) {
  8719. //=== NEEDBITS(3);
  8720. while (bits < 3) {
  8721. if (have === 0) { break inf_leave; }
  8722. have--;
  8723. hold += input[next++] << bits;
  8724. bits += 8;
  8725. }
  8726. //===//
  8727. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  8728. //--- DROPBITS(3) ---//
  8729. hold >>>= 3;
  8730. bits -= 3;
  8731. //---//
  8732. }
  8733. while (state.have < 19) {
  8734. state.lens[order[state.have++]] = 0;
  8735. }
  8736. // We have separate tables & no pointers. 2 commented lines below not needed.
  8737. //state.next = state.codes;
  8738. //state.lencode = state.next;
  8739. // Switch to use dynamic table
  8740. state.lencode = state.lendyn;
  8741. state.lenbits = 7;
  8742. opts = { bits: state.lenbits };
  8743. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  8744. state.lenbits = opts.bits;
  8745. if (ret) {
  8746. strm.msg = 'invalid code lengths set';
  8747. state.mode = BAD;
  8748. break;
  8749. }
  8750. //Tracev((stderr, "inflate: code lengths ok\n"));
  8751. state.have = 0;
  8752. state.mode = CODELENS;
  8753. /* falls through */
  8754. case CODELENS:
  8755. while (state.have < state.nlen + state.ndist) {
  8756. for (;;) {
  8757. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  8758. here_bits = here >>> 24;
  8759. here_op = (here >>> 16) & 0xff;
  8760. here_val = here & 0xffff;
  8761. if ((here_bits) <= bits) { break; }
  8762. //--- PULLBYTE() ---//
  8763. if (have === 0) { break inf_leave; }
  8764. have--;
  8765. hold += input[next++] << bits;
  8766. bits += 8;
  8767. //---//
  8768. }
  8769. if (here_val < 16) {
  8770. //--- DROPBITS(here.bits) ---//
  8771. hold >>>= here_bits;
  8772. bits -= here_bits;
  8773. //---//
  8774. state.lens[state.have++] = here_val;
  8775. }
  8776. else {
  8777. if (here_val === 16) {
  8778. //=== NEEDBITS(here.bits + 2);
  8779. n = here_bits + 2;
  8780. while (bits < n) {
  8781. if (have === 0) { break inf_leave; }
  8782. have--;
  8783. hold += input[next++] << bits;
  8784. bits += 8;
  8785. }
  8786. //===//
  8787. //--- DROPBITS(here.bits) ---//
  8788. hold >>>= here_bits;
  8789. bits -= here_bits;
  8790. //---//
  8791. if (state.have === 0) {
  8792. strm.msg = 'invalid bit length repeat';
  8793. state.mode = BAD;
  8794. break;
  8795. }
  8796. len = state.lens[state.have - 1];
  8797. copy = 3 + (hold & 0x03);//BITS(2);
  8798. //--- DROPBITS(2) ---//
  8799. hold >>>= 2;
  8800. bits -= 2;
  8801. //---//
  8802. }
  8803. else if (here_val === 17) {
  8804. //=== NEEDBITS(here.bits + 3);
  8805. n = here_bits + 3;
  8806. while (bits < n) {
  8807. if (have === 0) { break inf_leave; }
  8808. have--;
  8809. hold += input[next++] << bits;
  8810. bits += 8;
  8811. }
  8812. //===//
  8813. //--- DROPBITS(here.bits) ---//
  8814. hold >>>= here_bits;
  8815. bits -= here_bits;
  8816. //---//
  8817. len = 0;
  8818. copy = 3 + (hold & 0x07);//BITS(3);
  8819. //--- DROPBITS(3) ---//
  8820. hold >>>= 3;
  8821. bits -= 3;
  8822. //---//
  8823. }
  8824. else {
  8825. //=== NEEDBITS(here.bits + 7);
  8826. n = here_bits + 7;
  8827. while (bits < n) {
  8828. if (have === 0) { break inf_leave; }
  8829. have--;
  8830. hold += input[next++] << bits;
  8831. bits += 8;
  8832. }
  8833. //===//
  8834. //--- DROPBITS(here.bits) ---//
  8835. hold >>>= here_bits;
  8836. bits -= here_bits;
  8837. //---//
  8838. len = 0;
  8839. copy = 11 + (hold & 0x7f);//BITS(7);
  8840. //--- DROPBITS(7) ---//
  8841. hold >>>= 7;
  8842. bits -= 7;
  8843. //---//
  8844. }
  8845. if (state.have + copy > state.nlen + state.ndist) {
  8846. strm.msg = 'invalid bit length repeat';
  8847. state.mode = BAD;
  8848. break;
  8849. }
  8850. while (copy--) {
  8851. state.lens[state.have++] = len;
  8852. }
  8853. }
  8854. }
  8855. /* handle error breaks in while */
  8856. if (state.mode === BAD) { break; }
  8857. /* check for end-of-block code (better have one) */
  8858. if (state.lens[256] === 0) {
  8859. strm.msg = 'invalid code -- missing end-of-block';
  8860. state.mode = BAD;
  8861. break;
  8862. }
  8863. /* build code tables -- note: do not change the lenbits or distbits
  8864. values here (9 and 6) without reading the comments in inftrees.h
  8865. concerning the ENOUGH constants, which depend on those values */
  8866. state.lenbits = 9;
  8867. opts = { bits: state.lenbits };
  8868. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  8869. // We have separate tables & no pointers. 2 commented lines below not needed.
  8870. // state.next_index = opts.table_index;
  8871. state.lenbits = opts.bits;
  8872. // state.lencode = state.next;
  8873. if (ret) {
  8874. strm.msg = 'invalid literal/lengths set';
  8875. state.mode = BAD;
  8876. break;
  8877. }
  8878. state.distbits = 6;
  8879. //state.distcode.copy(state.codes);
  8880. // Switch to use dynamic table
  8881. state.distcode = state.distdyn;
  8882. opts = { bits: state.distbits };
  8883. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  8884. // We have separate tables & no pointers. 2 commented lines below not needed.
  8885. // state.next_index = opts.table_index;
  8886. state.distbits = opts.bits;
  8887. // state.distcode = state.next;
  8888. if (ret) {
  8889. strm.msg = 'invalid distances set';
  8890. state.mode = BAD;
  8891. break;
  8892. }
  8893. //Tracev((stderr, 'inflate: codes ok\n'));
  8894. state.mode = LEN_;
  8895. if (flush === Z_TREES) { break inf_leave; }
  8896. /* falls through */
  8897. case LEN_:
  8898. state.mode = LEN;
  8899. /* falls through */
  8900. case LEN:
  8901. if (have >= 6 && left >= 258) {
  8902. //--- RESTORE() ---
  8903. strm.next_out = put;
  8904. strm.avail_out = left;
  8905. strm.next_in = next;
  8906. strm.avail_in = have;
  8907. state.hold = hold;
  8908. state.bits = bits;
  8909. //---
  8910. inflate_fast(strm, _out);
  8911. //--- LOAD() ---
  8912. put = strm.next_out;
  8913. output = strm.output;
  8914. left = strm.avail_out;
  8915. next = strm.next_in;
  8916. input = strm.input;
  8917. have = strm.avail_in;
  8918. hold = state.hold;
  8919. bits = state.bits;
  8920. //---
  8921. if (state.mode === TYPE) {
  8922. state.back = -1;
  8923. }
  8924. break;
  8925. }
  8926. state.back = 0;
  8927. for (;;) {
  8928. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  8929. here_bits = here >>> 24;
  8930. here_op = (here >>> 16) & 0xff;
  8931. here_val = here & 0xffff;
  8932. if (here_bits <= bits) { break; }
  8933. //--- PULLBYTE() ---//
  8934. if (have === 0) { break inf_leave; }
  8935. have--;
  8936. hold += input[next++] << bits;
  8937. bits += 8;
  8938. //---//
  8939. }
  8940. if (here_op && (here_op & 0xf0) === 0) {
  8941. last_bits = here_bits;
  8942. last_op = here_op;
  8943. last_val = here_val;
  8944. for (;;) {
  8945. here = state.lencode[last_val +
  8946. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8947. here_bits = here >>> 24;
  8948. here_op = (here >>> 16) & 0xff;
  8949. here_val = here & 0xffff;
  8950. if ((last_bits + here_bits) <= bits) { break; }
  8951. //--- PULLBYTE() ---//
  8952. if (have === 0) { break inf_leave; }
  8953. have--;
  8954. hold += input[next++] << bits;
  8955. bits += 8;
  8956. //---//
  8957. }
  8958. //--- DROPBITS(last.bits) ---//
  8959. hold >>>= last_bits;
  8960. bits -= last_bits;
  8961. //---//
  8962. state.back += last_bits;
  8963. }
  8964. //--- DROPBITS(here.bits) ---//
  8965. hold >>>= here_bits;
  8966. bits -= here_bits;
  8967. //---//
  8968. state.back += here_bits;
  8969. state.length = here_val;
  8970. if (here_op === 0) {
  8971. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8972. // "inflate: literal '%c'\n" :
  8973. // "inflate: literal 0x%02x\n", here.val));
  8974. state.mode = LIT;
  8975. break;
  8976. }
  8977. if (here_op & 32) {
  8978. //Tracevv((stderr, "inflate: end of block\n"));
  8979. state.back = -1;
  8980. state.mode = TYPE;
  8981. break;
  8982. }
  8983. if (here_op & 64) {
  8984. strm.msg = 'invalid literal/length code';
  8985. state.mode = BAD;
  8986. break;
  8987. }
  8988. state.extra = here_op & 15;
  8989. state.mode = LENEXT;
  8990. /* falls through */
  8991. case LENEXT:
  8992. if (state.extra) {
  8993. //=== NEEDBITS(state.extra);
  8994. n = state.extra;
  8995. while (bits < n) {
  8996. if (have === 0) { break inf_leave; }
  8997. have--;
  8998. hold += input[next++] << bits;
  8999. bits += 8;
  9000. }
  9001. //===//
  9002. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9003. //--- DROPBITS(state.extra) ---//
  9004. hold >>>= state.extra;
  9005. bits -= state.extra;
  9006. //---//
  9007. state.back += state.extra;
  9008. }
  9009. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9010. state.was = state.length;
  9011. state.mode = DIST;
  9012. /* falls through */
  9013. case DIST:
  9014. for (;;) {
  9015. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9016. here_bits = here >>> 24;
  9017. here_op = (here >>> 16) & 0xff;
  9018. here_val = here & 0xffff;
  9019. if ((here_bits) <= bits) { break; }
  9020. //--- PULLBYTE() ---//
  9021. if (have === 0) { break inf_leave; }
  9022. have--;
  9023. hold += input[next++] << bits;
  9024. bits += 8;
  9025. //---//
  9026. }
  9027. if ((here_op & 0xf0) === 0) {
  9028. last_bits = here_bits;
  9029. last_op = here_op;
  9030. last_val = here_val;
  9031. for (;;) {
  9032. here = state.distcode[last_val +
  9033. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9034. here_bits = here >>> 24;
  9035. here_op = (here >>> 16) & 0xff;
  9036. here_val = here & 0xffff;
  9037. if ((last_bits + here_bits) <= bits) { break; }
  9038. //--- PULLBYTE() ---//
  9039. if (have === 0) { break inf_leave; }
  9040. have--;
  9041. hold += input[next++] << bits;
  9042. bits += 8;
  9043. //---//
  9044. }
  9045. //--- DROPBITS(last.bits) ---//
  9046. hold >>>= last_bits;
  9047. bits -= last_bits;
  9048. //---//
  9049. state.back += last_bits;
  9050. }
  9051. //--- DROPBITS(here.bits) ---//
  9052. hold >>>= here_bits;
  9053. bits -= here_bits;
  9054. //---//
  9055. state.back += here_bits;
  9056. if (here_op & 64) {
  9057. strm.msg = 'invalid distance code';
  9058. state.mode = BAD;
  9059. break;
  9060. }
  9061. state.offset = here_val;
  9062. state.extra = (here_op) & 15;
  9063. state.mode = DISTEXT;
  9064. /* falls through */
  9065. case DISTEXT:
  9066. if (state.extra) {
  9067. //=== NEEDBITS(state.extra);
  9068. n = state.extra;
  9069. while (bits < n) {
  9070. if (have === 0) { break inf_leave; }
  9071. have--;
  9072. hold += input[next++] << bits;
  9073. bits += 8;
  9074. }
  9075. //===//
  9076. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9077. //--- DROPBITS(state.extra) ---//
  9078. hold >>>= state.extra;
  9079. bits -= state.extra;
  9080. //---//
  9081. state.back += state.extra;
  9082. }
  9083. //#ifdef INFLATE_STRICT
  9084. if (state.offset > state.dmax) {
  9085. strm.msg = 'invalid distance too far back';
  9086. state.mode = BAD;
  9087. break;
  9088. }
  9089. //#endif
  9090. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9091. state.mode = MATCH;
  9092. /* falls through */
  9093. case MATCH:
  9094. if (left === 0) { break inf_leave; }
  9095. copy = _out - left;
  9096. if (state.offset > copy) { /* copy from window */
  9097. copy = state.offset - copy;
  9098. if (copy > state.whave) {
  9099. if (state.sane) {
  9100. strm.msg = 'invalid distance too far back';
  9101. state.mode = BAD;
  9102. break;
  9103. }
  9104. // (!) This block is disabled in zlib defaults,
  9105. // don't enable it for binary compatibility
  9106. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9107. // Trace((stderr, "inflate.c too far\n"));
  9108. // copy -= state.whave;
  9109. // if (copy > state.length) { copy = state.length; }
  9110. // if (copy > left) { copy = left; }
  9111. // left -= copy;
  9112. // state.length -= copy;
  9113. // do {
  9114. // output[put++] = 0;
  9115. // } while (--copy);
  9116. // if (state.length === 0) { state.mode = LEN; }
  9117. // break;
  9118. //#endif
  9119. }
  9120. if (copy > state.wnext) {
  9121. copy -= state.wnext;
  9122. from = state.wsize - copy;
  9123. }
  9124. else {
  9125. from = state.wnext - copy;
  9126. }
  9127. if (copy > state.length) { copy = state.length; }
  9128. from_source = state.window;
  9129. }
  9130. else { /* copy from output */
  9131. from_source = output;
  9132. from = put - state.offset;
  9133. copy = state.length;
  9134. }
  9135. if (copy > left) { copy = left; }
  9136. left -= copy;
  9137. state.length -= copy;
  9138. do {
  9139. output[put++] = from_source[from++];
  9140. } while (--copy);
  9141. if (state.length === 0) { state.mode = LEN; }
  9142. break;
  9143. case LIT:
  9144. if (left === 0) { break inf_leave; }
  9145. output[put++] = state.length;
  9146. left--;
  9147. state.mode = LEN;
  9148. break;
  9149. case CHECK:
  9150. if (state.wrap) {
  9151. //=== NEEDBITS(32);
  9152. while (bits < 32) {
  9153. if (have === 0) { break inf_leave; }
  9154. have--;
  9155. // Use '|' instead of '+' to make sure that result is signed
  9156. hold |= input[next++] << bits;
  9157. bits += 8;
  9158. }
  9159. //===//
  9160. _out -= left;
  9161. strm.total_out += _out;
  9162. state.total += _out;
  9163. if (_out) {
  9164. strm.adler = state.check =
  9165. /*UPDATE(state.check, put - _out, _out);*/
  9166. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9167. }
  9168. _out = left;
  9169. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9170. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9171. strm.msg = 'incorrect data check';
  9172. state.mode = BAD;
  9173. break;
  9174. }
  9175. //=== INITBITS();
  9176. hold = 0;
  9177. bits = 0;
  9178. //===//
  9179. //Tracev((stderr, "inflate: check matches trailer\n"));
  9180. }
  9181. state.mode = LENGTH;
  9182. /* falls through */
  9183. case LENGTH:
  9184. if (state.wrap && state.flags) {
  9185. //=== NEEDBITS(32);
  9186. while (bits < 32) {
  9187. if (have === 0) { break inf_leave; }
  9188. have--;
  9189. hold += input[next++] << bits;
  9190. bits += 8;
  9191. }
  9192. //===//
  9193. if (hold !== (state.total & 0xffffffff)) {
  9194. strm.msg = 'incorrect length check';
  9195. state.mode = BAD;
  9196. break;
  9197. }
  9198. //=== INITBITS();
  9199. hold = 0;
  9200. bits = 0;
  9201. //===//
  9202. //Tracev((stderr, "inflate: length matches trailer\n"));
  9203. }
  9204. state.mode = DONE;
  9205. /* falls through */
  9206. case DONE:
  9207. ret = Z_STREAM_END;
  9208. break inf_leave;
  9209. case BAD:
  9210. ret = Z_DATA_ERROR;
  9211. break inf_leave;
  9212. case MEM:
  9213. return Z_MEM_ERROR;
  9214. case SYNC:
  9215. /* falls through */
  9216. default:
  9217. return Z_STREAM_ERROR;
  9218. }
  9219. }
  9220. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9221. /*
  9222. Return from inflate(), updating the total counts and the check value.
  9223. If there was no progress during the inflate() call, return a buffer
  9224. error. Call updatewindow() to create and/or update the window state.
  9225. Note: a memory error from inflate() is non-recoverable.
  9226. */
  9227. //--- RESTORE() ---
  9228. strm.next_out = put;
  9229. strm.avail_out = left;
  9230. strm.next_in = next;
  9231. strm.avail_in = have;
  9232. state.hold = hold;
  9233. state.bits = bits;
  9234. //---
  9235. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9236. (state.mode < CHECK || flush !== Z_FINISH))) {
  9237. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9238. state.mode = MEM;
  9239. return Z_MEM_ERROR;
  9240. }
  9241. }
  9242. _in -= strm.avail_in;
  9243. _out -= strm.avail_out;
  9244. strm.total_in += _in;
  9245. strm.total_out += _out;
  9246. state.total += _out;
  9247. if (state.wrap && _out) {
  9248. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9249. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9250. }
  9251. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9252. (state.mode === TYPE ? 128 : 0) +
  9253. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9254. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9255. ret = Z_BUF_ERROR;
  9256. }
  9257. return ret;
  9258. }
  9259. function inflateEnd(strm) {
  9260. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9261. return Z_STREAM_ERROR;
  9262. }
  9263. var state = strm.state;
  9264. if (state.window) {
  9265. state.window = null;
  9266. }
  9267. strm.state = null;
  9268. return Z_OK;
  9269. }
  9270. function inflateGetHeader(strm, head) {
  9271. var state;
  9272. /* check state */
  9273. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9274. state = strm.state;
  9275. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9276. /* save header structure */
  9277. state.head = head;
  9278. head.done = false;
  9279. return Z_OK;
  9280. }
  9281. function inflateSetDictionary(strm, dictionary) {
  9282. var dictLength = dictionary.length;
  9283. var state;
  9284. var dictid;
  9285. var ret;
  9286. /* check state */
  9287. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9288. state = strm.state;
  9289. if (state.wrap !== 0 && state.mode !== DICT) {
  9290. return Z_STREAM_ERROR;
  9291. }
  9292. /* check for correct dictionary identifier */
  9293. if (state.mode === DICT) {
  9294. dictid = 1; /* adler32(0, null, 0)*/
  9295. /* dictid = adler32(dictid, dictionary, dictLength); */
  9296. dictid = adler32(dictid, dictionary, dictLength, 0);
  9297. if (dictid !== state.check) {
  9298. return Z_DATA_ERROR;
  9299. }
  9300. }
  9301. /* copy dictionary to window using updatewindow(), which will amend the
  9302. existing dictionary if appropriate */
  9303. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9304. if (ret) {
  9305. state.mode = MEM;
  9306. return Z_MEM_ERROR;
  9307. }
  9308. state.havedict = 1;
  9309. // Tracev((stderr, "inflate: dictionary set\n"));
  9310. return Z_OK;
  9311. }
  9312. exports.inflateReset = inflateReset;
  9313. exports.inflateReset2 = inflateReset2;
  9314. exports.inflateResetKeep = inflateResetKeep;
  9315. exports.inflateInit = inflateInit;
  9316. exports.inflateInit2 = inflateInit2;
  9317. exports.inflate = inflate;
  9318. exports.inflateEnd = inflateEnd;
  9319. exports.inflateGetHeader = inflateGetHeader;
  9320. exports.inflateSetDictionary = inflateSetDictionary;
  9321. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9322. /* Not implemented
  9323. exports.inflateCopy = inflateCopy;
  9324. exports.inflateGetDictionary = inflateGetDictionary;
  9325. exports.inflateMark = inflateMark;
  9326. exports.inflatePrime = inflatePrime;
  9327. exports.inflateSync = inflateSync;
  9328. exports.inflateSyncPoint = inflateSyncPoint;
  9329. exports.inflateUndermine = inflateUndermine;
  9330. */
  9331. },{"../utils/common":35,"./adler32":36,"./crc32":38,"./inffast":40,"./inftrees":42}],42:[function(require,module,exports){
  9332. 'use strict';
  9333. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9334. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9335. //
  9336. // This software is provided 'as-is', without any express or implied
  9337. // warranty. In no event will the authors be held liable for any damages
  9338. // arising from the use of this software.
  9339. //
  9340. // Permission is granted to anyone to use this software for any purpose,
  9341. // including commercial applications, and to alter it and redistribute it
  9342. // freely, subject to the following restrictions:
  9343. //
  9344. // 1. The origin of this software must not be misrepresented; you must not
  9345. // claim that you wrote the original software. If you use this software
  9346. // in a product, an acknowledgment in the product documentation would be
  9347. // appreciated but is not required.
  9348. // 2. Altered source versions must be plainly marked as such, and must not be
  9349. // misrepresented as being the original software.
  9350. // 3. This notice may not be removed or altered from any source distribution.
  9351. var utils = require('../utils/common');
  9352. var MAXBITS = 15;
  9353. var ENOUGH_LENS = 852;
  9354. var ENOUGH_DISTS = 592;
  9355. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9356. var CODES = 0;
  9357. var LENS = 1;
  9358. var DISTS = 2;
  9359. var lbase = [ /* Length codes 257..285 base */
  9360. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9361. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9362. ];
  9363. var lext = [ /* Length codes 257..285 extra */
  9364. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9365. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9366. ];
  9367. var dbase = [ /* Distance codes 0..29 base */
  9368. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9369. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9370. 8193, 12289, 16385, 24577, 0, 0
  9371. ];
  9372. var dext = [ /* Distance codes 0..29 extra */
  9373. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9374. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9375. 28, 28, 29, 29, 64, 64
  9376. ];
  9377. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9378. {
  9379. var bits = opts.bits;
  9380. //here = opts.here; /* table entry for duplication */
  9381. var len = 0; /* a code's length in bits */
  9382. var sym = 0; /* index of code symbols */
  9383. var min = 0, max = 0; /* minimum and maximum code lengths */
  9384. var root = 0; /* number of index bits for root table */
  9385. var curr = 0; /* number of index bits for current table */
  9386. var drop = 0; /* code bits to drop for sub-table */
  9387. var left = 0; /* number of prefix codes available */
  9388. var used = 0; /* code entries in table used */
  9389. var huff = 0; /* Huffman code */
  9390. var incr; /* for incrementing code, index */
  9391. var fill; /* index for replicating entries */
  9392. var low; /* low bits for current root entry */
  9393. var mask; /* mask for low root bits */
  9394. var next; /* next available space in table */
  9395. var base = null; /* base value table to use */
  9396. var base_index = 0;
  9397. // var shoextra; /* extra bits table to use */
  9398. var end; /* use base and extra for symbol > end */
  9399. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  9400. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  9401. var extra = null;
  9402. var extra_index = 0;
  9403. var here_bits, here_op, here_val;
  9404. /*
  9405. Process a set of code lengths to create a canonical Huffman code. The
  9406. code lengths are lens[0..codes-1]. Each length corresponds to the
  9407. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9408. symbols by length from short to long, and retaining the symbol order
  9409. for codes with equal lengths. Then the code starts with all zero bits
  9410. for the first code of the shortest length, and the codes are integer
  9411. increments for the same length, and zeros are appended as the length
  9412. increases. For the deflate format, these bits are stored backwards
  9413. from their more natural integer increment ordering, and so when the
  9414. decoding tables are built in the large loop below, the integer codes
  9415. are incremented backwards.
  9416. This routine assumes, but does not check, that all of the entries in
  9417. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9418. 1..MAXBITS is interpreted as that code length. zero means that that
  9419. symbol does not occur in this code.
  9420. The codes are sorted by computing a count of codes for each length,
  9421. creating from that a table of starting indices for each length in the
  9422. sorted table, and then entering the symbols in order in the sorted
  9423. table. The sorted table is work[], with that space being provided by
  9424. the caller.
  9425. The length counts are used for other purposes as well, i.e. finding
  9426. the minimum and maximum length codes, determining if there are any
  9427. codes at all, checking for a valid set of lengths, and looking ahead
  9428. at length counts to determine sub-table sizes when building the
  9429. decoding tables.
  9430. */
  9431. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9432. for (len = 0; len <= MAXBITS; len++) {
  9433. count[len] = 0;
  9434. }
  9435. for (sym = 0; sym < codes; sym++) {
  9436. count[lens[lens_index + sym]]++;
  9437. }
  9438. /* bound code lengths, force root to be within code lengths */
  9439. root = bits;
  9440. for (max = MAXBITS; max >= 1; max--) {
  9441. if (count[max] !== 0) { break; }
  9442. }
  9443. if (root > max) {
  9444. root = max;
  9445. }
  9446. if (max === 0) { /* no symbols to code at all */
  9447. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9448. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9449. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9450. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9451. //table.op[opts.table_index] = 64;
  9452. //table.bits[opts.table_index] = 1;
  9453. //table.val[opts.table_index++] = 0;
  9454. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9455. opts.bits = 1;
  9456. return 0; /* no symbols, but wait for decoding to report error */
  9457. }
  9458. for (min = 1; min < max; min++) {
  9459. if (count[min] !== 0) { break; }
  9460. }
  9461. if (root < min) {
  9462. root = min;
  9463. }
  9464. /* check for an over-subscribed or incomplete set of lengths */
  9465. left = 1;
  9466. for (len = 1; len <= MAXBITS; len++) {
  9467. left <<= 1;
  9468. left -= count[len];
  9469. if (left < 0) {
  9470. return -1;
  9471. } /* over-subscribed */
  9472. }
  9473. if (left > 0 && (type === CODES || max !== 1)) {
  9474. return -1; /* incomplete set */
  9475. }
  9476. /* generate offsets into symbol table for each length for sorting */
  9477. offs[1] = 0;
  9478. for (len = 1; len < MAXBITS; len++) {
  9479. offs[len + 1] = offs[len] + count[len];
  9480. }
  9481. /* sort symbols by length, by symbol order within each length */
  9482. for (sym = 0; sym < codes; sym++) {
  9483. if (lens[lens_index + sym] !== 0) {
  9484. work[offs[lens[lens_index + sym]]++] = sym;
  9485. }
  9486. }
  9487. /*
  9488. Create and fill in decoding tables. In this loop, the table being
  9489. filled is at next and has curr index bits. The code being used is huff
  9490. with length len. That code is converted to an index by dropping drop
  9491. bits off of the bottom. For codes where len is less than drop + curr,
  9492. those top drop + curr - len bits are incremented through all values to
  9493. fill the table with replicated entries.
  9494. root is the number of index bits for the root table. When len exceeds
  9495. root, sub-tables are created pointed to by the root entry with an index
  9496. of the low root bits of huff. This is saved in low to check for when a
  9497. new sub-table should be started. drop is zero when the root table is
  9498. being filled, and drop is root when sub-tables are being filled.
  9499. When a new sub-table is needed, it is necessary to look ahead in the
  9500. code lengths to determine what size sub-table is needed. The length
  9501. counts are used for this, and so count[] is decremented as codes are
  9502. entered in the tables.
  9503. used keeps track of how many table entries have been allocated from the
  9504. provided *table space. It is checked for LENS and DIST tables against
  9505. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9506. the initial root table size constants. See the comments in inftrees.h
  9507. for more information.
  9508. sym increments through all symbols, and the loop terminates when
  9509. all codes of length max, i.e. all codes, have been processed. This
  9510. routine permits incomplete codes, so another loop after this one fills
  9511. in the rest of the decoding tables with invalid code markers.
  9512. */
  9513. /* set up for code type */
  9514. // poor man optimization - use if-else instead of switch,
  9515. // to avoid deopts in old v8
  9516. if (type === CODES) {
  9517. base = extra = work; /* dummy value--not used */
  9518. end = 19;
  9519. } else if (type === LENS) {
  9520. base = lbase;
  9521. base_index -= 257;
  9522. extra = lext;
  9523. extra_index -= 257;
  9524. end = 256;
  9525. } else { /* DISTS */
  9526. base = dbase;
  9527. extra = dext;
  9528. end = -1;
  9529. }
  9530. /* initialize opts for loop */
  9531. huff = 0; /* starting code */
  9532. sym = 0; /* starting code symbol */
  9533. len = min; /* starting code length */
  9534. next = table_index; /* current table to fill in */
  9535. curr = root; /* current table index bits */
  9536. drop = 0; /* current bits to drop from code for index */
  9537. low = -1; /* trigger new sub-table when len > root */
  9538. used = 1 << root; /* use root table entries */
  9539. mask = used - 1; /* mask for comparing low */
  9540. /* check available table space */
  9541. if ((type === LENS && used > ENOUGH_LENS) ||
  9542. (type === DISTS && used > ENOUGH_DISTS)) {
  9543. return 1;
  9544. }
  9545. /* process all codes and make table entries */
  9546. for (;;) {
  9547. /* create table entry */
  9548. here_bits = len - drop;
  9549. if (work[sym] < end) {
  9550. here_op = 0;
  9551. here_val = work[sym];
  9552. }
  9553. else if (work[sym] > end) {
  9554. here_op = extra[extra_index + work[sym]];
  9555. here_val = base[base_index + work[sym]];
  9556. }
  9557. else {
  9558. here_op = 32 + 64; /* end of block */
  9559. here_val = 0;
  9560. }
  9561. /* replicate for those indices with low len bits equal to huff */
  9562. incr = 1 << (len - drop);
  9563. fill = 1 << curr;
  9564. min = fill; /* save offset to next table */
  9565. do {
  9566. fill -= incr;
  9567. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9568. } while (fill !== 0);
  9569. /* backwards increment the len-bit code huff */
  9570. incr = 1 << (len - 1);
  9571. while (huff & incr) {
  9572. incr >>= 1;
  9573. }
  9574. if (incr !== 0) {
  9575. huff &= incr - 1;
  9576. huff += incr;
  9577. } else {
  9578. huff = 0;
  9579. }
  9580. /* go to next symbol, update count, len */
  9581. sym++;
  9582. if (--count[len] === 0) {
  9583. if (len === max) { break; }
  9584. len = lens[lens_index + work[sym]];
  9585. }
  9586. /* create new sub-table if needed */
  9587. if (len > root && (huff & mask) !== low) {
  9588. /* if first time, transition to sub-tables */
  9589. if (drop === 0) {
  9590. drop = root;
  9591. }
  9592. /* increment past last table */
  9593. next += min; /* here min is 1 << curr */
  9594. /* determine length of next table */
  9595. curr = len - drop;
  9596. left = 1 << curr;
  9597. while (curr + drop < max) {
  9598. left -= count[curr + drop];
  9599. if (left <= 0) { break; }
  9600. curr++;
  9601. left <<= 1;
  9602. }
  9603. /* check for enough space */
  9604. used += 1 << curr;
  9605. if ((type === LENS && used > ENOUGH_LENS) ||
  9606. (type === DISTS && used > ENOUGH_DISTS)) {
  9607. return 1;
  9608. }
  9609. /* point entry in root table to sub-table */
  9610. low = huff & mask;
  9611. /*table.op[low] = curr;
  9612. table.bits[low] = root;
  9613. table.val[low] = next - opts.table_index;*/
  9614. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  9615. }
  9616. }
  9617. /* fill in remaining table entry if code is incomplete (guaranteed to have
  9618. at most one remaining entry, since if the code is incomplete, the
  9619. maximum code length that was allowed to get this far is one bit) */
  9620. if (huff !== 0) {
  9621. //table.op[next + huff] = 64; /* invalid code marker */
  9622. //table.bits[next + huff] = len - drop;
  9623. //table.val[next + huff] = 0;
  9624. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  9625. }
  9626. /* set return parameters */
  9627. //opts.table_index += used;
  9628. opts.bits = root;
  9629. return 0;
  9630. };
  9631. },{"../utils/common":35}],43:[function(require,module,exports){
  9632. 'use strict';
  9633. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9634. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9635. //
  9636. // This software is provided 'as-is', without any express or implied
  9637. // warranty. In no event will the authors be held liable for any damages
  9638. // arising from the use of this software.
  9639. //
  9640. // Permission is granted to anyone to use this software for any purpose,
  9641. // including commercial applications, and to alter it and redistribute it
  9642. // freely, subject to the following restrictions:
  9643. //
  9644. // 1. The origin of this software must not be misrepresented; you must not
  9645. // claim that you wrote the original software. If you use this software
  9646. // in a product, an acknowledgment in the product documentation would be
  9647. // appreciated but is not required.
  9648. // 2. Altered source versions must be plainly marked as such, and must not be
  9649. // misrepresented as being the original software.
  9650. // 3. This notice may not be removed or altered from any source distribution.
  9651. module.exports = {
  9652. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  9653. 1: 'stream end', /* Z_STREAM_END 1 */
  9654. 0: '', /* Z_OK 0 */
  9655. '-1': 'file error', /* Z_ERRNO (-1) */
  9656. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  9657. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  9658. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  9659. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  9660. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  9661. };
  9662. },{}],44:[function(require,module,exports){
  9663. 'use strict';
  9664. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9665. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9666. //
  9667. // This software is provided 'as-is', without any express or implied
  9668. // warranty. In no event will the authors be held liable for any damages
  9669. // arising from the use of this software.
  9670. //
  9671. // Permission is granted to anyone to use this software for any purpose,
  9672. // including commercial applications, and to alter it and redistribute it
  9673. // freely, subject to the following restrictions:
  9674. //
  9675. // 1. The origin of this software must not be misrepresented; you must not
  9676. // claim that you wrote the original software. If you use this software
  9677. // in a product, an acknowledgment in the product documentation would be
  9678. // appreciated but is not required.
  9679. // 2. Altered source versions must be plainly marked as such, and must not be
  9680. // misrepresented as being the original software.
  9681. // 3. This notice may not be removed or altered from any source distribution.
  9682. var utils = require('../utils/common');
  9683. /* Public constants ==========================================================*/
  9684. /* ===========================================================================*/
  9685. //var Z_FILTERED = 1;
  9686. //var Z_HUFFMAN_ONLY = 2;
  9687. //var Z_RLE = 3;
  9688. var Z_FIXED = 4;
  9689. //var Z_DEFAULT_STRATEGY = 0;
  9690. /* Possible values of the data_type field (though see inflate()) */
  9691. var Z_BINARY = 0;
  9692. var Z_TEXT = 1;
  9693. //var Z_ASCII = 1; // = Z_TEXT
  9694. var Z_UNKNOWN = 2;
  9695. /*============================================================================*/
  9696. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  9697. // From zutil.h
  9698. var STORED_BLOCK = 0;
  9699. var STATIC_TREES = 1;
  9700. var DYN_TREES = 2;
  9701. /* The three kinds of block type */
  9702. var MIN_MATCH = 3;
  9703. var MAX_MATCH = 258;
  9704. /* The minimum and maximum match lengths */
  9705. // From deflate.h
  9706. /* ===========================================================================
  9707. * Internal compression state.
  9708. */
  9709. var LENGTH_CODES = 29;
  9710. /* number of length codes, not counting the special END_BLOCK code */
  9711. var LITERALS = 256;
  9712. /* number of literal bytes 0..255 */
  9713. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9714. /* number of Literal or Length codes, including the END_BLOCK code */
  9715. var D_CODES = 30;
  9716. /* number of distance codes */
  9717. var BL_CODES = 19;
  9718. /* number of codes used to transfer the bit lengths */
  9719. var HEAP_SIZE = 2 * L_CODES + 1;
  9720. /* maximum heap size */
  9721. var MAX_BITS = 15;
  9722. /* All codes must not exceed MAX_BITS bits */
  9723. var Buf_size = 16;
  9724. /* size of bit buffer in bi_buf */
  9725. /* ===========================================================================
  9726. * Constants
  9727. */
  9728. var MAX_BL_BITS = 7;
  9729. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9730. var END_BLOCK = 256;
  9731. /* end of block literal code */
  9732. var REP_3_6 = 16;
  9733. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9734. var REPZ_3_10 = 17;
  9735. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9736. var REPZ_11_138 = 18;
  9737. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9738. /* eslint-disable comma-spacing,array-bracket-spacing */
  9739. var extra_lbits = /* extra bits for each length code */
  9740. [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];
  9741. var extra_dbits = /* extra bits for each distance code */
  9742. [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];
  9743. var extra_blbits = /* extra bits for each bit length code */
  9744. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9745. var bl_order =
  9746. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9747. /* eslint-enable comma-spacing,array-bracket-spacing */
  9748. /* The lengths of the bit length codes are sent in order of decreasing
  9749. * probability, to avoid transmitting the lengths for unused bit length codes.
  9750. */
  9751. /* ===========================================================================
  9752. * Local data. These are initialized only once.
  9753. */
  9754. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9755. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9756. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  9757. var static_ltree = new Array((L_CODES + 2) * 2);
  9758. zero(static_ltree);
  9759. /* The static literal tree. Since the bit lengths are imposed, there is no
  9760. * need for the L_CODES extra codes used during heap construction. However
  9761. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9762. * below).
  9763. */
  9764. var static_dtree = new Array(D_CODES * 2);
  9765. zero(static_dtree);
  9766. /* The static distance tree. (Actually a trivial tree since all codes use
  9767. * 5 bits.)
  9768. */
  9769. var _dist_code = new Array(DIST_CODE_LEN);
  9770. zero(_dist_code);
  9771. /* Distance codes. The first 256 values correspond to the distances
  9772. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9773. * the 15 bit distances.
  9774. */
  9775. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  9776. zero(_length_code);
  9777. /* length code for each normalized match length (0 == MIN_MATCH) */
  9778. var base_length = new Array(LENGTH_CODES);
  9779. zero(base_length);
  9780. /* First normalized length for each code (0 = MIN_MATCH) */
  9781. var base_dist = new Array(D_CODES);
  9782. zero(base_dist);
  9783. /* First normalized distance for each code (0 = distance of 1) */
  9784. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  9785. this.static_tree = static_tree; /* static tree or NULL */
  9786. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  9787. this.extra_base = extra_base; /* base index for extra_bits */
  9788. this.elems = elems; /* max number of elements in the tree */
  9789. this.max_length = max_length; /* max bit length for the codes */
  9790. // show if `static_tree` has data or dummy - needed for monomorphic objects
  9791. this.has_stree = static_tree && static_tree.length;
  9792. }
  9793. var static_l_desc;
  9794. var static_d_desc;
  9795. var static_bl_desc;
  9796. function TreeDesc(dyn_tree, stat_desc) {
  9797. this.dyn_tree = dyn_tree; /* the dynamic tree */
  9798. this.max_code = 0; /* largest code with non zero frequency */
  9799. this.stat_desc = stat_desc; /* the corresponding static tree */
  9800. }
  9801. function d_code(dist) {
  9802. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  9803. }
  9804. /* ===========================================================================
  9805. * Output a short LSB first on the stream.
  9806. * IN assertion: there is enough room in pendingBuf.
  9807. */
  9808. function put_short(s, w) {
  9809. // put_byte(s, (uch)((w) & 0xff));
  9810. // put_byte(s, (uch)((ush)(w) >> 8));
  9811. s.pending_buf[s.pending++] = (w) & 0xff;
  9812. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  9813. }
  9814. /* ===========================================================================
  9815. * Send a value on a given number of bits.
  9816. * IN assertion: length <= 16 and value fits in length bits.
  9817. */
  9818. function send_bits(s, value, length) {
  9819. if (s.bi_valid > (Buf_size - length)) {
  9820. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9821. put_short(s, s.bi_buf);
  9822. s.bi_buf = value >> (Buf_size - s.bi_valid);
  9823. s.bi_valid += length - Buf_size;
  9824. } else {
  9825. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9826. s.bi_valid += length;
  9827. }
  9828. }
  9829. function send_code(s, c, tree) {
  9830. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  9831. }
  9832. /* ===========================================================================
  9833. * Reverse the first len bits of a code, using straightforward code (a faster
  9834. * method would use a table)
  9835. * IN assertion: 1 <= len <= 15
  9836. */
  9837. function bi_reverse(code, len) {
  9838. var res = 0;
  9839. do {
  9840. res |= code & 1;
  9841. code >>>= 1;
  9842. res <<= 1;
  9843. } while (--len > 0);
  9844. return res >>> 1;
  9845. }
  9846. /* ===========================================================================
  9847. * Flush the bit buffer, keeping at most 7 bits in it.
  9848. */
  9849. function bi_flush(s) {
  9850. if (s.bi_valid === 16) {
  9851. put_short(s, s.bi_buf);
  9852. s.bi_buf = 0;
  9853. s.bi_valid = 0;
  9854. } else if (s.bi_valid >= 8) {
  9855. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  9856. s.bi_buf >>= 8;
  9857. s.bi_valid -= 8;
  9858. }
  9859. }
  9860. /* ===========================================================================
  9861. * Compute the optimal bit lengths for a tree and update the total bit length
  9862. * for the current block.
  9863. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  9864. * above are the tree nodes sorted by increasing frequency.
  9865. * OUT assertions: the field len is set to the optimal bit length, the
  9866. * array bl_count contains the frequencies for each bit length.
  9867. * The length opt_len is updated; static_len is also updated if stree is
  9868. * not null.
  9869. */
  9870. function gen_bitlen(s, desc)
  9871. // deflate_state *s;
  9872. // tree_desc *desc; /* the tree descriptor */
  9873. {
  9874. var tree = desc.dyn_tree;
  9875. var max_code = desc.max_code;
  9876. var stree = desc.stat_desc.static_tree;
  9877. var has_stree = desc.stat_desc.has_stree;
  9878. var extra = desc.stat_desc.extra_bits;
  9879. var base = desc.stat_desc.extra_base;
  9880. var max_length = desc.stat_desc.max_length;
  9881. var h; /* heap index */
  9882. var n, m; /* iterate over the tree elements */
  9883. var bits; /* bit length */
  9884. var xbits; /* extra bits */
  9885. var f; /* frequency */
  9886. var overflow = 0; /* number of elements with bit length too large */
  9887. for (bits = 0; bits <= MAX_BITS; bits++) {
  9888. s.bl_count[bits] = 0;
  9889. }
  9890. /* In a first pass, compute the optimal bit lengths (which may
  9891. * overflow in the case of the bit length tree).
  9892. */
  9893. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  9894. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9895. n = s.heap[h];
  9896. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  9897. if (bits > max_length) {
  9898. bits = max_length;
  9899. overflow++;
  9900. }
  9901. tree[n * 2 + 1]/*.Len*/ = bits;
  9902. /* We overwrite tree[n].Dad which is no longer needed */
  9903. if (n > max_code) { continue; } /* not a leaf node */
  9904. s.bl_count[bits]++;
  9905. xbits = 0;
  9906. if (n >= base) {
  9907. xbits = extra[n - base];
  9908. }
  9909. f = tree[n * 2]/*.Freq*/;
  9910. s.opt_len += f * (bits + xbits);
  9911. if (has_stree) {
  9912. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  9913. }
  9914. }
  9915. if (overflow === 0) { return; }
  9916. // Trace((stderr,"\nbit length overflow\n"));
  9917. /* This happens for example on obj2 and pic of the Calgary corpus */
  9918. /* Find the first bit length which could increase: */
  9919. do {
  9920. bits = max_length - 1;
  9921. while (s.bl_count[bits] === 0) { bits--; }
  9922. s.bl_count[bits]--; /* move one leaf down the tree */
  9923. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  9924. s.bl_count[max_length]--;
  9925. /* The brother of the overflow item also moves one step up,
  9926. * but this does not affect bl_count[max_length]
  9927. */
  9928. overflow -= 2;
  9929. } while (overflow > 0);
  9930. /* Now recompute all bit lengths, scanning in increasing frequency.
  9931. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  9932. * lengths instead of fixing only the wrong ones. This idea is taken
  9933. * from 'ar' written by Haruhiko Okumura.)
  9934. */
  9935. for (bits = max_length; bits !== 0; bits--) {
  9936. n = s.bl_count[bits];
  9937. while (n !== 0) {
  9938. m = s.heap[--h];
  9939. if (m > max_code) { continue; }
  9940. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  9941. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  9942. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  9943. tree[m * 2 + 1]/*.Len*/ = bits;
  9944. }
  9945. n--;
  9946. }
  9947. }
  9948. }
  9949. /* ===========================================================================
  9950. * Generate the codes for a given tree and bit counts (which need not be
  9951. * optimal).
  9952. * IN assertion: the array bl_count contains the bit length statistics for
  9953. * the given tree and the field len is set for all tree elements.
  9954. * OUT assertion: the field code is set for all tree elements of non
  9955. * zero code length.
  9956. */
  9957. function gen_codes(tree, max_code, bl_count)
  9958. // ct_data *tree; /* the tree to decorate */
  9959. // int max_code; /* largest code with non zero frequency */
  9960. // ushf *bl_count; /* number of codes at each bit length */
  9961. {
  9962. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  9963. var code = 0; /* running code value */
  9964. var bits; /* bit index */
  9965. var n; /* code index */
  9966. /* The distribution counts are first used to generate the code values
  9967. * without bit reversal.
  9968. */
  9969. for (bits = 1; bits <= MAX_BITS; bits++) {
  9970. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  9971. }
  9972. /* Check that the bit counts in bl_count are consistent. The last code
  9973. * must be all ones.
  9974. */
  9975. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9976. // "inconsistent bit counts");
  9977. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9978. for (n = 0; n <= max_code; n++) {
  9979. var len = tree[n * 2 + 1]/*.Len*/;
  9980. if (len === 0) { continue; }
  9981. /* Now reverse the bits */
  9982. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  9983. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  9984. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  9985. }
  9986. }
  9987. /* ===========================================================================
  9988. * Initialize the various 'constant' tables.
  9989. */
  9990. function tr_static_init() {
  9991. var n; /* iterates over tree elements */
  9992. var bits; /* bit counter */
  9993. var length; /* length value */
  9994. var code; /* code value */
  9995. var dist; /* distance index */
  9996. var bl_count = new Array(MAX_BITS + 1);
  9997. /* number of codes at each bit length for an optimal tree */
  9998. // do check in _tr_init()
  9999. //if (static_init_done) return;
  10000. /* For some embedded targets, global variables are not initialized: */
  10001. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10002. static_l_desc.static_tree = static_ltree;
  10003. static_l_desc.extra_bits = extra_lbits;
  10004. static_d_desc.static_tree = static_dtree;
  10005. static_d_desc.extra_bits = extra_dbits;
  10006. static_bl_desc.extra_bits = extra_blbits;
  10007. #endif*/
  10008. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10009. length = 0;
  10010. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10011. base_length[code] = length;
  10012. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10013. _length_code[length++] = code;
  10014. }
  10015. }
  10016. //Assert (length == 256, "tr_static_init: length != 256");
  10017. /* Note that the length 255 (match length 258) can be represented
  10018. * in two different ways: code 284 + 5 bits or code 285, so we
  10019. * overwrite length_code[255] to use the best encoding:
  10020. */
  10021. _length_code[length - 1] = code;
  10022. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10023. dist = 0;
  10024. for (code = 0; code < 16; code++) {
  10025. base_dist[code] = dist;
  10026. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10027. _dist_code[dist++] = code;
  10028. }
  10029. }
  10030. //Assert (dist == 256, "tr_static_init: dist != 256");
  10031. dist >>= 7; /* from now on, all distances are divided by 128 */
  10032. for (; code < D_CODES; code++) {
  10033. base_dist[code] = dist << 7;
  10034. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10035. _dist_code[256 + dist++] = code;
  10036. }
  10037. }
  10038. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10039. /* Construct the codes of the static literal tree */
  10040. for (bits = 0; bits <= MAX_BITS; bits++) {
  10041. bl_count[bits] = 0;
  10042. }
  10043. n = 0;
  10044. while (n <= 143) {
  10045. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10046. n++;
  10047. bl_count[8]++;
  10048. }
  10049. while (n <= 255) {
  10050. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10051. n++;
  10052. bl_count[9]++;
  10053. }
  10054. while (n <= 279) {
  10055. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10056. n++;
  10057. bl_count[7]++;
  10058. }
  10059. while (n <= 287) {
  10060. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10061. n++;
  10062. bl_count[8]++;
  10063. }
  10064. /* Codes 286 and 287 do not exist, but we must include them in the
  10065. * tree construction to get a canonical Huffman tree (longest code
  10066. * all ones)
  10067. */
  10068. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10069. /* The static distance tree is trivial: */
  10070. for (n = 0; n < D_CODES; n++) {
  10071. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10072. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10073. }
  10074. // Now data ready and we can init static trees
  10075. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10076. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10077. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10078. //static_init_done = true;
  10079. }
  10080. /* ===========================================================================
  10081. * Initialize a new block.
  10082. */
  10083. function init_block(s) {
  10084. var n; /* iterates over tree elements */
  10085. /* Initialize the trees. */
  10086. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10087. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10088. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10089. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10090. s.opt_len = s.static_len = 0;
  10091. s.last_lit = s.matches = 0;
  10092. }
  10093. /* ===========================================================================
  10094. * Flush the bit buffer and align the output on a byte boundary
  10095. */
  10096. function bi_windup(s)
  10097. {
  10098. if (s.bi_valid > 8) {
  10099. put_short(s, s.bi_buf);
  10100. } else if (s.bi_valid > 0) {
  10101. //put_byte(s, (Byte)s->bi_buf);
  10102. s.pending_buf[s.pending++] = s.bi_buf;
  10103. }
  10104. s.bi_buf = 0;
  10105. s.bi_valid = 0;
  10106. }
  10107. /* ===========================================================================
  10108. * Copy a stored block, storing first the length and its
  10109. * one's complement if requested.
  10110. */
  10111. function copy_block(s, buf, len, header)
  10112. //DeflateState *s;
  10113. //charf *buf; /* the input data */
  10114. //unsigned len; /* its length */
  10115. //int header; /* true if block header must be written */
  10116. {
  10117. bi_windup(s); /* align on byte boundary */
  10118. if (header) {
  10119. put_short(s, len);
  10120. put_short(s, ~len);
  10121. }
  10122. // while (len--) {
  10123. // put_byte(s, *buf++);
  10124. // }
  10125. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10126. s.pending += len;
  10127. }
  10128. /* ===========================================================================
  10129. * Compares to subtrees, using the tree depth as tie breaker when
  10130. * the subtrees have equal frequency. This minimizes the worst case length.
  10131. */
  10132. function smaller(tree, n, m, depth) {
  10133. var _n2 = n * 2;
  10134. var _m2 = m * 2;
  10135. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10136. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10137. }
  10138. /* ===========================================================================
  10139. * Restore the heap property by moving down the tree starting at node k,
  10140. * exchanging a node with the smallest of its two sons if necessary, stopping
  10141. * when the heap property is re-established (each father smaller than its
  10142. * two sons).
  10143. */
  10144. function pqdownheap(s, tree, k)
  10145. // deflate_state *s;
  10146. // ct_data *tree; /* the tree to restore */
  10147. // int k; /* node to move down */
  10148. {
  10149. var v = s.heap[k];
  10150. var j = k << 1; /* left son of k */
  10151. while (j <= s.heap_len) {
  10152. /* Set j to the smallest of the two sons: */
  10153. if (j < s.heap_len &&
  10154. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10155. j++;
  10156. }
  10157. /* Exit if v is smaller than both sons */
  10158. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10159. /* Exchange v with the smallest son */
  10160. s.heap[k] = s.heap[j];
  10161. k = j;
  10162. /* And continue down the tree, setting j to the left son of k */
  10163. j <<= 1;
  10164. }
  10165. s.heap[k] = v;
  10166. }
  10167. // inlined manually
  10168. // var SMALLEST = 1;
  10169. /* ===========================================================================
  10170. * Send the block data compressed using the given Huffman trees
  10171. */
  10172. function compress_block(s, ltree, dtree)
  10173. // deflate_state *s;
  10174. // const ct_data *ltree; /* literal tree */
  10175. // const ct_data *dtree; /* distance tree */
  10176. {
  10177. var dist; /* distance of matched string */
  10178. var lc; /* match length or unmatched char (if dist == 0) */
  10179. var lx = 0; /* running index in l_buf */
  10180. var code; /* the code to send */
  10181. var extra; /* number of extra bits to send */
  10182. if (s.last_lit !== 0) {
  10183. do {
  10184. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10185. lc = s.pending_buf[s.l_buf + lx];
  10186. lx++;
  10187. if (dist === 0) {
  10188. send_code(s, lc, ltree); /* send a literal byte */
  10189. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10190. } else {
  10191. /* Here, lc is the match length - MIN_MATCH */
  10192. code = _length_code[lc];
  10193. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10194. extra = extra_lbits[code];
  10195. if (extra !== 0) {
  10196. lc -= base_length[code];
  10197. send_bits(s, lc, extra); /* send the extra length bits */
  10198. }
  10199. dist--; /* dist is now the match distance - 1 */
  10200. code = d_code(dist);
  10201. //Assert (code < D_CODES, "bad d_code");
  10202. send_code(s, code, dtree); /* send the distance code */
  10203. extra = extra_dbits[code];
  10204. if (extra !== 0) {
  10205. dist -= base_dist[code];
  10206. send_bits(s, dist, extra); /* send the extra distance bits */
  10207. }
  10208. } /* literal or match pair ? */
  10209. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10210. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10211. // "pendingBuf overflow");
  10212. } while (lx < s.last_lit);
  10213. }
  10214. send_code(s, END_BLOCK, ltree);
  10215. }
  10216. /* ===========================================================================
  10217. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10218. * Update the total bit length for the current block.
  10219. * IN assertion: the field freq is set for all tree elements.
  10220. * OUT assertions: the fields len and code are set to the optimal bit length
  10221. * and corresponding code. The length opt_len is updated; static_len is
  10222. * also updated if stree is not null. The field max_code is set.
  10223. */
  10224. function build_tree(s, desc)
  10225. // deflate_state *s;
  10226. // tree_desc *desc; /* the tree descriptor */
  10227. {
  10228. var tree = desc.dyn_tree;
  10229. var stree = desc.stat_desc.static_tree;
  10230. var has_stree = desc.stat_desc.has_stree;
  10231. var elems = desc.stat_desc.elems;
  10232. var n, m; /* iterate over heap elements */
  10233. var max_code = -1; /* largest code with non zero frequency */
  10234. var node; /* new node being created */
  10235. /* Construct the initial heap, with least frequent element in
  10236. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10237. * heap[0] is not used.
  10238. */
  10239. s.heap_len = 0;
  10240. s.heap_max = HEAP_SIZE;
  10241. for (n = 0; n < elems; n++) {
  10242. if (tree[n * 2]/*.Freq*/ !== 0) {
  10243. s.heap[++s.heap_len] = max_code = n;
  10244. s.depth[n] = 0;
  10245. } else {
  10246. tree[n * 2 + 1]/*.Len*/ = 0;
  10247. }
  10248. }
  10249. /* The pkzip format requires that at least one distance code exists,
  10250. * and that at least one bit should be sent even if there is only one
  10251. * possible code. So to avoid special checks later on we force at least
  10252. * two codes of non zero frequency.
  10253. */
  10254. while (s.heap_len < 2) {
  10255. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10256. tree[node * 2]/*.Freq*/ = 1;
  10257. s.depth[node] = 0;
  10258. s.opt_len--;
  10259. if (has_stree) {
  10260. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10261. }
  10262. /* node is 0 or 1 so it does not have extra bits */
  10263. }
  10264. desc.max_code = max_code;
  10265. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10266. * establish sub-heaps of increasing lengths:
  10267. */
  10268. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10269. /* Construct the Huffman tree by repeatedly combining the least two
  10270. * frequent nodes.
  10271. */
  10272. node = elems; /* next internal node of the tree */
  10273. do {
  10274. //pqremove(s, tree, n); /* n = node of least frequency */
  10275. /*** pqremove ***/
  10276. n = s.heap[1/*SMALLEST*/];
  10277. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10278. pqdownheap(s, tree, 1/*SMALLEST*/);
  10279. /***/
  10280. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10281. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10282. s.heap[--s.heap_max] = m;
  10283. /* Create a new node father of n and m */
  10284. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10285. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10286. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10287. /* and insert the new node in the heap */
  10288. s.heap[1/*SMALLEST*/] = node++;
  10289. pqdownheap(s, tree, 1/*SMALLEST*/);
  10290. } while (s.heap_len >= 2);
  10291. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10292. /* At this point, the fields freq and dad are set. We can now
  10293. * generate the bit lengths.
  10294. */
  10295. gen_bitlen(s, desc);
  10296. /* The field len is now set, we can generate the bit codes */
  10297. gen_codes(tree, max_code, s.bl_count);
  10298. }
  10299. /* ===========================================================================
  10300. * Scan a literal or distance tree to determine the frequencies of the codes
  10301. * in the bit length tree.
  10302. */
  10303. function scan_tree(s, tree, max_code)
  10304. // deflate_state *s;
  10305. // ct_data *tree; /* the tree to be scanned */
  10306. // int max_code; /* and its largest code of non zero frequency */
  10307. {
  10308. var n; /* iterates over all tree elements */
  10309. var prevlen = -1; /* last emitted length */
  10310. var curlen; /* length of current code */
  10311. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10312. var count = 0; /* repeat count of the current code */
  10313. var max_count = 7; /* max repeat count */
  10314. var min_count = 4; /* min repeat count */
  10315. if (nextlen === 0) {
  10316. max_count = 138;
  10317. min_count = 3;
  10318. }
  10319. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  10320. for (n = 0; n <= max_code; n++) {
  10321. curlen = nextlen;
  10322. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10323. if (++count < max_count && curlen === nextlen) {
  10324. continue;
  10325. } else if (count < min_count) {
  10326. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10327. } else if (curlen !== 0) {
  10328. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10329. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  10330. } else if (count <= 10) {
  10331. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  10332. } else {
  10333. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  10334. }
  10335. count = 0;
  10336. prevlen = curlen;
  10337. if (nextlen === 0) {
  10338. max_count = 138;
  10339. min_count = 3;
  10340. } else if (curlen === nextlen) {
  10341. max_count = 6;
  10342. min_count = 3;
  10343. } else {
  10344. max_count = 7;
  10345. min_count = 4;
  10346. }
  10347. }
  10348. }
  10349. /* ===========================================================================
  10350. * Send a literal or distance tree in compressed form, using the codes in
  10351. * bl_tree.
  10352. */
  10353. function send_tree(s, tree, max_code)
  10354. // deflate_state *s;
  10355. // ct_data *tree; /* the tree to be scanned */
  10356. // int max_code; /* and its largest code of non zero frequency */
  10357. {
  10358. var n; /* iterates over all tree elements */
  10359. var prevlen = -1; /* last emitted length */
  10360. var curlen; /* length of current code */
  10361. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10362. var count = 0; /* repeat count of the current code */
  10363. var max_count = 7; /* max repeat count */
  10364. var min_count = 4; /* min repeat count */
  10365. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10366. if (nextlen === 0) {
  10367. max_count = 138;
  10368. min_count = 3;
  10369. }
  10370. for (n = 0; n <= max_code; n++) {
  10371. curlen = nextlen;
  10372. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10373. if (++count < max_count && curlen === nextlen) {
  10374. continue;
  10375. } else if (count < min_count) {
  10376. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10377. } else if (curlen !== 0) {
  10378. if (curlen !== prevlen) {
  10379. send_code(s, curlen, s.bl_tree);
  10380. count--;
  10381. }
  10382. //Assert(count >= 3 && count <= 6, " 3_6?");
  10383. send_code(s, REP_3_6, s.bl_tree);
  10384. send_bits(s, count - 3, 2);
  10385. } else if (count <= 10) {
  10386. send_code(s, REPZ_3_10, s.bl_tree);
  10387. send_bits(s, count - 3, 3);
  10388. } else {
  10389. send_code(s, REPZ_11_138, s.bl_tree);
  10390. send_bits(s, count - 11, 7);
  10391. }
  10392. count = 0;
  10393. prevlen = curlen;
  10394. if (nextlen === 0) {
  10395. max_count = 138;
  10396. min_count = 3;
  10397. } else if (curlen === nextlen) {
  10398. max_count = 6;
  10399. min_count = 3;
  10400. } else {
  10401. max_count = 7;
  10402. min_count = 4;
  10403. }
  10404. }
  10405. }
  10406. /* ===========================================================================
  10407. * Construct the Huffman tree for the bit lengths and return the index in
  10408. * bl_order of the last bit length code to send.
  10409. */
  10410. function build_bl_tree(s) {
  10411. var max_blindex; /* index of last bit length code of non zero freq */
  10412. /* Determine the bit length frequencies for literal and distance trees */
  10413. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  10414. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  10415. /* Build the bit length tree: */
  10416. build_tree(s, s.bl_desc);
  10417. /* opt_len now includes the length of the tree representations, except
  10418. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  10419. */
  10420. /* Determine the number of bit length codes to send. The pkzip format
  10421. * requires that at least 4 bit length codes be sent. (appnote.txt says
  10422. * 3 but the actual value used is 4.)
  10423. */
  10424. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  10425. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  10426. break;
  10427. }
  10428. }
  10429. /* Update opt_len to include the bit length tree and counts */
  10430. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  10431. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  10432. // s->opt_len, s->static_len));
  10433. return max_blindex;
  10434. }
  10435. /* ===========================================================================
  10436. * Send the header for a block using dynamic Huffman trees: the counts, the
  10437. * lengths of the bit length codes, the literal tree and the distance tree.
  10438. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10439. */
  10440. function send_all_trees(s, lcodes, dcodes, blcodes)
  10441. // deflate_state *s;
  10442. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  10443. {
  10444. var rank; /* index in bl_order */
  10445. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  10446. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  10447. // "too many codes");
  10448. //Tracev((stderr, "\nbl counts: "));
  10449. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  10450. send_bits(s, dcodes - 1, 5);
  10451. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  10452. for (rank = 0; rank < blcodes; rank++) {
  10453. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  10454. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  10455. }
  10456. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  10457. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  10458. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  10459. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  10460. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  10461. }
  10462. /* ===========================================================================
  10463. * Check if the data type is TEXT or BINARY, using the following algorithm:
  10464. * - TEXT if the two conditions below are satisfied:
  10465. * a) There are no non-portable control characters belonging to the
  10466. * "black list" (0..6, 14..25, 28..31).
  10467. * b) There is at least one printable character belonging to the
  10468. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  10469. * - BINARY otherwise.
  10470. * - The following partially-portable control characters form a
  10471. * "gray list" that is ignored in this detection algorithm:
  10472. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  10473. * IN assertion: the fields Freq of dyn_ltree are set.
  10474. */
  10475. function detect_data_type(s) {
  10476. /* black_mask is the bit mask of black-listed bytes
  10477. * set bits 0..6, 14..25, and 28..31
  10478. * 0xf3ffc07f = binary 11110011111111111100000001111111
  10479. */
  10480. var black_mask = 0xf3ffc07f;
  10481. var n;
  10482. /* Check for non-textual ("black-listed") bytes. */
  10483. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  10484. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  10485. return Z_BINARY;
  10486. }
  10487. }
  10488. /* Check for textual ("white-listed") bytes. */
  10489. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  10490. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  10491. return Z_TEXT;
  10492. }
  10493. for (n = 32; n < LITERALS; n++) {
  10494. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  10495. return Z_TEXT;
  10496. }
  10497. }
  10498. /* There are no "black-listed" or "white-listed" bytes:
  10499. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  10500. */
  10501. return Z_BINARY;
  10502. }
  10503. var static_init_done = false;
  10504. /* ===========================================================================
  10505. * Initialize the tree data structures for a new zlib stream.
  10506. */
  10507. function _tr_init(s)
  10508. {
  10509. if (!static_init_done) {
  10510. tr_static_init();
  10511. static_init_done = true;
  10512. }
  10513. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  10514. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  10515. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  10516. s.bi_buf = 0;
  10517. s.bi_valid = 0;
  10518. /* Initialize the first block of the first file: */
  10519. init_block(s);
  10520. }
  10521. /* ===========================================================================
  10522. * Send a stored block
  10523. */
  10524. function _tr_stored_block(s, buf, stored_len, last)
  10525. //DeflateState *s;
  10526. //charf *buf; /* input block */
  10527. //ulg stored_len; /* length of input block */
  10528. //int last; /* one if this is the last block for a file */
  10529. {
  10530. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  10531. copy_block(s, buf, stored_len, true); /* with header */
  10532. }
  10533. /* ===========================================================================
  10534. * Send one empty static block to give enough lookahead for inflate.
  10535. * This takes 10 bits, of which 7 may remain in the bit buffer.
  10536. */
  10537. function _tr_align(s) {
  10538. send_bits(s, STATIC_TREES << 1, 3);
  10539. send_code(s, END_BLOCK, static_ltree);
  10540. bi_flush(s);
  10541. }
  10542. /* ===========================================================================
  10543. * Determine the best encoding for the current block: dynamic trees, static
  10544. * trees or store, and output the encoded block to the zip file.
  10545. */
  10546. function _tr_flush_block(s, buf, stored_len, last)
  10547. //DeflateState *s;
  10548. //charf *buf; /* input block, or NULL if too old */
  10549. //ulg stored_len; /* length of input block */
  10550. //int last; /* one if this is the last block for a file */
  10551. {
  10552. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  10553. var max_blindex = 0; /* index of last bit length code of non zero freq */
  10554. /* Build the Huffman trees unless a stored block is forced */
  10555. if (s.level > 0) {
  10556. /* Check if the file is binary or text */
  10557. if (s.strm.data_type === Z_UNKNOWN) {
  10558. s.strm.data_type = detect_data_type(s);
  10559. }
  10560. /* Construct the literal and distance trees */
  10561. build_tree(s, s.l_desc);
  10562. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  10563. // s->static_len));
  10564. build_tree(s, s.d_desc);
  10565. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  10566. // s->static_len));
  10567. /* At this point, opt_len and static_len are the total bit lengths of
  10568. * the compressed block data, excluding the tree representations.
  10569. */
  10570. /* Build the bit length tree for the above two trees, and get the index
  10571. * in bl_order of the last bit length code to send.
  10572. */
  10573. max_blindex = build_bl_tree(s);
  10574. /* Determine the best encoding. Compute the block lengths in bytes. */
  10575. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  10576. static_lenb = (s.static_len + 3 + 7) >>> 3;
  10577. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  10578. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  10579. // s->last_lit));
  10580. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  10581. } else {
  10582. // Assert(buf != (char*)0, "lost buf");
  10583. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  10584. }
  10585. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  10586. /* 4: two words for the lengths */
  10587. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10588. * Otherwise we can't have processed more than WSIZE input bytes since
  10589. * the last block flush, because compression would have been
  10590. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10591. * transform a block into a stored block.
  10592. */
  10593. _tr_stored_block(s, buf, stored_len, last);
  10594. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  10595. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  10596. compress_block(s, static_ltree, static_dtree);
  10597. } else {
  10598. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  10599. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  10600. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  10601. }
  10602. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  10603. /* The above check is made mod 2^32, for files larger than 512 MB
  10604. * and uLong implemented on 32 bits.
  10605. */
  10606. init_block(s);
  10607. if (last) {
  10608. bi_windup(s);
  10609. }
  10610. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  10611. // s->compressed_len-7*last));
  10612. }
  10613. /* ===========================================================================
  10614. * Save the match info and tally the frequency counts. Return true if
  10615. * the current block must be flushed.
  10616. */
  10617. function _tr_tally(s, dist, lc)
  10618. // deflate_state *s;
  10619. // unsigned dist; /* distance of matched string */
  10620. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  10621. {
  10622. //var out_length, in_length, dcode;
  10623. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  10624. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  10625. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  10626. s.last_lit++;
  10627. if (dist === 0) {
  10628. /* lc is the unmatched char */
  10629. s.dyn_ltree[lc * 2]/*.Freq*/++;
  10630. } else {
  10631. s.matches++;
  10632. /* Here, lc is the match length - MIN_MATCH */
  10633. dist--; /* dist = match distance - 1 */
  10634. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  10635. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  10636. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  10637. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  10638. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  10639. }
  10640. // (!) This block is disabled in zlib defaults,
  10641. // don't enable it for binary compatibility
  10642. //#ifdef TRUNCATE_BLOCK
  10643. // /* Try to guess if it is profitable to stop the current block here */
  10644. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  10645. // /* Compute an upper bound for the compressed length */
  10646. // out_length = s.last_lit*8;
  10647. // in_length = s.strstart - s.block_start;
  10648. //
  10649. // for (dcode = 0; dcode < D_CODES; dcode++) {
  10650. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  10651. // }
  10652. // out_length >>>= 3;
  10653. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  10654. // // s->last_lit, in_length, out_length,
  10655. // // 100L - out_length*100L/in_length));
  10656. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  10657. // return true;
  10658. // }
  10659. // }
  10660. //#endif
  10661. return (s.last_lit === s.lit_bufsize - 1);
  10662. /* We avoid equality with lit_bufsize because of wraparound at 64K
  10663. * on 16 bit machines and because stored blocks are restricted to
  10664. * 64K-1 bytes.
  10665. */
  10666. }
  10667. exports._tr_init = _tr_init;
  10668. exports._tr_stored_block = _tr_stored_block;
  10669. exports._tr_flush_block = _tr_flush_block;
  10670. exports._tr_tally = _tr_tally;
  10671. exports._tr_align = _tr_align;
  10672. },{"../utils/common":35}],45:[function(require,module,exports){
  10673. 'use strict';
  10674. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10675. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10676. //
  10677. // This software is provided 'as-is', without any express or implied
  10678. // warranty. In no event will the authors be held liable for any damages
  10679. // arising from the use of this software.
  10680. //
  10681. // Permission is granted to anyone to use this software for any purpose,
  10682. // including commercial applications, and to alter it and redistribute it
  10683. // freely, subject to the following restrictions:
  10684. //
  10685. // 1. The origin of this software must not be misrepresented; you must not
  10686. // claim that you wrote the original software. If you use this software
  10687. // in a product, an acknowledgment in the product documentation would be
  10688. // appreciated but is not required.
  10689. // 2. Altered source versions must be plainly marked as such, and must not be
  10690. // misrepresented as being the original software.
  10691. // 3. This notice may not be removed or altered from any source distribution.
  10692. function ZStream() {
  10693. /* next input byte */
  10694. this.input = null; // JS specific, because we have no pointers
  10695. this.next_in = 0;
  10696. /* number of bytes available at input */
  10697. this.avail_in = 0;
  10698. /* total number of input bytes read so far */
  10699. this.total_in = 0;
  10700. /* next output byte should be put there */
  10701. this.output = null; // JS specific, because we have no pointers
  10702. this.next_out = 0;
  10703. /* remaining free space at output */
  10704. this.avail_out = 0;
  10705. /* total number of bytes output so far */
  10706. this.total_out = 0;
  10707. /* last error message, NULL if no error */
  10708. this.msg = ''/*Z_NULL*/;
  10709. /* not visible by applications */
  10710. this.state = null;
  10711. /* best guess about the data type: binary or text */
  10712. this.data_type = 2/*Z_UNKNOWN*/;
  10713. /* adler32 value of the uncompressed data */
  10714. this.adler = 0;
  10715. }
  10716. module.exports = ZStream;
  10717. },{}],46:[function(require,module,exports){
  10718. (function (process){
  10719. 'use strict';
  10720. if (!process.version ||
  10721. process.version.indexOf('v0.') === 0 ||
  10722. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  10723. module.exports = nextTick;
  10724. } else {
  10725. module.exports = process.nextTick;
  10726. }
  10727. function nextTick(fn, arg1, arg2, arg3) {
  10728. if (typeof fn !== 'function') {
  10729. throw new TypeError('"callback" argument must be a function');
  10730. }
  10731. var len = arguments.length;
  10732. var args, i;
  10733. switch (len) {
  10734. case 0:
  10735. case 1:
  10736. return process.nextTick(fn);
  10737. case 2:
  10738. return process.nextTick(function afterTickOne() {
  10739. fn.call(null, arg1);
  10740. });
  10741. case 3:
  10742. return process.nextTick(function afterTickTwo() {
  10743. fn.call(null, arg1, arg2);
  10744. });
  10745. case 4:
  10746. return process.nextTick(function afterTickThree() {
  10747. fn.call(null, arg1, arg2, arg3);
  10748. });
  10749. default:
  10750. args = new Array(len - 1);
  10751. i = 0;
  10752. while (i < args.length) {
  10753. args[i++] = arguments[i];
  10754. }
  10755. return process.nextTick(function afterTick() {
  10756. fn.apply(null, args);
  10757. });
  10758. }
  10759. }
  10760. }).call(this,require('_process'))
  10761. },{"_process":47}],47:[function(require,module,exports){
  10762. // shim for using process in browser
  10763. var process = module.exports = {};
  10764. // cached from whatever global is present so that test runners that stub it
  10765. // don't break things. But we need to wrap it in a try catch in case it is
  10766. // wrapped in strict mode code which doesn't define any globals. It's inside a
  10767. // function because try/catches deoptimize in certain engines.
  10768. var cachedSetTimeout;
  10769. var cachedClearTimeout;
  10770. function defaultSetTimout() {
  10771. throw new Error('setTimeout has not been defined');
  10772. }
  10773. function defaultClearTimeout () {
  10774. throw new Error('clearTimeout has not been defined');
  10775. }
  10776. (function () {
  10777. try {
  10778. if (typeof setTimeout === 'function') {
  10779. cachedSetTimeout = setTimeout;
  10780. } else {
  10781. cachedSetTimeout = defaultSetTimout;
  10782. }
  10783. } catch (e) {
  10784. cachedSetTimeout = defaultSetTimout;
  10785. }
  10786. try {
  10787. if (typeof clearTimeout === 'function') {
  10788. cachedClearTimeout = clearTimeout;
  10789. } else {
  10790. cachedClearTimeout = defaultClearTimeout;
  10791. }
  10792. } catch (e) {
  10793. cachedClearTimeout = defaultClearTimeout;
  10794. }
  10795. } ())
  10796. function runTimeout(fun) {
  10797. if (cachedSetTimeout === setTimeout) {
  10798. //normal enviroments in sane situations
  10799. return setTimeout(fun, 0);
  10800. }
  10801. // if setTimeout wasn't available but was latter defined
  10802. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  10803. cachedSetTimeout = setTimeout;
  10804. return setTimeout(fun, 0);
  10805. }
  10806. try {
  10807. // when when somebody has screwed with setTimeout but no I.E. maddness
  10808. return cachedSetTimeout(fun, 0);
  10809. } catch(e){
  10810. try {
  10811. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  10812. return cachedSetTimeout.call(null, fun, 0);
  10813. } catch(e){
  10814. // 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
  10815. return cachedSetTimeout.call(this, fun, 0);
  10816. }
  10817. }
  10818. }
  10819. function runClearTimeout(marker) {
  10820. if (cachedClearTimeout === clearTimeout) {
  10821. //normal enviroments in sane situations
  10822. return clearTimeout(marker);
  10823. }
  10824. // if clearTimeout wasn't available but was latter defined
  10825. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  10826. cachedClearTimeout = clearTimeout;
  10827. return clearTimeout(marker);
  10828. }
  10829. try {
  10830. // when when somebody has screwed with setTimeout but no I.E. maddness
  10831. return cachedClearTimeout(marker);
  10832. } catch (e){
  10833. try {
  10834. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  10835. return cachedClearTimeout.call(null, marker);
  10836. } catch (e){
  10837. // 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.
  10838. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  10839. return cachedClearTimeout.call(this, marker);
  10840. }
  10841. }
  10842. }
  10843. var queue = [];
  10844. var draining = false;
  10845. var currentQueue;
  10846. var queueIndex = -1;
  10847. function cleanUpNextTick() {
  10848. if (!draining || !currentQueue) {
  10849. return;
  10850. }
  10851. draining = false;
  10852. if (currentQueue.length) {
  10853. queue = currentQueue.concat(queue);
  10854. } else {
  10855. queueIndex = -1;
  10856. }
  10857. if (queue.length) {
  10858. drainQueue();
  10859. }
  10860. }
  10861. function drainQueue() {
  10862. if (draining) {
  10863. return;
  10864. }
  10865. var timeout = runTimeout(cleanUpNextTick);
  10866. draining = true;
  10867. var len = queue.length;
  10868. while(len) {
  10869. currentQueue = queue;
  10870. queue = [];
  10871. while (++queueIndex < len) {
  10872. if (currentQueue) {
  10873. currentQueue[queueIndex].run();
  10874. }
  10875. }
  10876. queueIndex = -1;
  10877. len = queue.length;
  10878. }
  10879. currentQueue = null;
  10880. draining = false;
  10881. runClearTimeout(timeout);
  10882. }
  10883. process.nextTick = function (fun) {
  10884. var args = new Array(arguments.length - 1);
  10885. if (arguments.length > 1) {
  10886. for (var i = 1; i < arguments.length; i++) {
  10887. args[i - 1] = arguments[i];
  10888. }
  10889. }
  10890. queue.push(new Item(fun, args));
  10891. if (queue.length === 1 && !draining) {
  10892. runTimeout(drainQueue);
  10893. }
  10894. };
  10895. // v8 likes predictible objects
  10896. function Item(fun, array) {
  10897. this.fun = fun;
  10898. this.array = array;
  10899. }
  10900. Item.prototype.run = function () {
  10901. this.fun.apply(null, this.array);
  10902. };
  10903. process.title = 'browser';
  10904. process.browser = true;
  10905. process.env = {};
  10906. process.argv = [];
  10907. process.version = ''; // empty string to avoid regexp issues
  10908. process.versions = {};
  10909. function noop() {}
  10910. process.on = noop;
  10911. process.addListener = noop;
  10912. process.once = noop;
  10913. process.off = noop;
  10914. process.removeListener = noop;
  10915. process.removeAllListeners = noop;
  10916. process.emit = noop;
  10917. process.prependListener = noop;
  10918. process.prependOnceListener = noop;
  10919. process.listeners = function (name) { return [] }
  10920. process.binding = function (name) {
  10921. throw new Error('process.binding is not supported');
  10922. };
  10923. process.cwd = function () { return '/' };
  10924. process.chdir = function (dir) {
  10925. throw new Error('process.chdir is not supported');
  10926. };
  10927. process.umask = function() { return 0; };
  10928. },{}],48:[function(require,module,exports){
  10929. module.exports = require('./lib/_stream_duplex.js');
  10930. },{"./lib/_stream_duplex.js":49}],49:[function(require,module,exports){
  10931. // Copyright Joyent, Inc. and other Node contributors.
  10932. //
  10933. // Permission is hereby granted, free of charge, to any person obtaining a
  10934. // copy of this software and associated documentation files (the
  10935. // "Software"), to deal in the Software without restriction, including
  10936. // without limitation the rights to use, copy, modify, merge, publish,
  10937. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10938. // persons to whom the Software is furnished to do so, subject to the
  10939. // following conditions:
  10940. //
  10941. // The above copyright notice and this permission notice shall be included
  10942. // in all copies or substantial portions of the Software.
  10943. //
  10944. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10945. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10946. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10947. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10948. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10949. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10950. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10951. // a duplex stream is just a stream that is both readable and writable.
  10952. // Since JS doesn't have multiple prototypal inheritance, this class
  10953. // prototypally inherits from Readable, and then parasitically from
  10954. // Writable.
  10955. 'use strict';
  10956. /*<replacement>*/
  10957. var processNextTick = require('process-nextick-args');
  10958. /*</replacement>*/
  10959. /*<replacement>*/
  10960. var objectKeys = Object.keys || function (obj) {
  10961. var keys = [];
  10962. for (var key in obj) {
  10963. keys.push(key);
  10964. }return keys;
  10965. };
  10966. /*</replacement>*/
  10967. module.exports = Duplex;
  10968. /*<replacement>*/
  10969. var util = require('core-util-is');
  10970. util.inherits = require('inherits');
  10971. /*</replacement>*/
  10972. var Readable = require('./_stream_readable');
  10973. var Writable = require('./_stream_writable');
  10974. util.inherits(Duplex, Readable);
  10975. var keys = objectKeys(Writable.prototype);
  10976. for (var v = 0; v < keys.length; v++) {
  10977. var method = keys[v];
  10978. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  10979. }
  10980. function Duplex(options) {
  10981. if (!(this instanceof Duplex)) return new Duplex(options);
  10982. Readable.call(this, options);
  10983. Writable.call(this, options);
  10984. if (options && options.readable === false) this.readable = false;
  10985. if (options && options.writable === false) this.writable = false;
  10986. this.allowHalfOpen = true;
  10987. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  10988. this.once('end', onend);
  10989. }
  10990. // the no-half-open enforcer
  10991. function onend() {
  10992. // if we allow half-open state, or if the writable side ended,
  10993. // then we're ok.
  10994. if (this.allowHalfOpen || this._writableState.ended) return;
  10995. // no more data can be written.
  10996. // But allow more writes to happen in this tick.
  10997. processNextTick(onEndNT, this);
  10998. }
  10999. function onEndNT(self) {
  11000. self.end();
  11001. }
  11002. Object.defineProperty(Duplex.prototype, 'destroyed', {
  11003. get: function () {
  11004. if (this._readableState === undefined || this._writableState === undefined) {
  11005. return false;
  11006. }
  11007. return this._readableState.destroyed && this._writableState.destroyed;
  11008. },
  11009. set: function (value) {
  11010. // we ignore the value if the stream
  11011. // has not been initialized yet
  11012. if (this._readableState === undefined || this._writableState === undefined) {
  11013. return;
  11014. }
  11015. // backward compatibility, the user is explicitly
  11016. // managing destroyed
  11017. this._readableState.destroyed = value;
  11018. this._writableState.destroyed = value;
  11019. }
  11020. });
  11021. Duplex.prototype._destroy = function (err, cb) {
  11022. this.push(null);
  11023. this.end();
  11024. processNextTick(cb, err);
  11025. };
  11026. function forEach(xs, f) {
  11027. for (var i = 0, l = xs.length; i < l; i++) {
  11028. f(xs[i], i);
  11029. }
  11030. }
  11031. },{"./_stream_readable":51,"./_stream_writable":53,"core-util-is":29,"inherits":32,"process-nextick-args":46}],50:[function(require,module,exports){
  11032. // Copyright Joyent, Inc. and other Node contributors.
  11033. //
  11034. // Permission is hereby granted, free of charge, to any person obtaining a
  11035. // copy of this software and associated documentation files (the
  11036. // "Software"), to deal in the Software without restriction, including
  11037. // without limitation the rights to use, copy, modify, merge, publish,
  11038. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11039. // persons to whom the Software is furnished to do so, subject to the
  11040. // following conditions:
  11041. //
  11042. // The above copyright notice and this permission notice shall be included
  11043. // in all copies or substantial portions of the Software.
  11044. //
  11045. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11046. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11047. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11048. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11049. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11050. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11051. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11052. // a passthrough stream.
  11053. // basically just the most minimal sort of Transform stream.
  11054. // Every written chunk gets output as-is.
  11055. 'use strict';
  11056. module.exports = PassThrough;
  11057. var Transform = require('./_stream_transform');
  11058. /*<replacement>*/
  11059. var util = require('core-util-is');
  11060. util.inherits = require('inherits');
  11061. /*</replacement>*/
  11062. util.inherits(PassThrough, Transform);
  11063. function PassThrough(options) {
  11064. if (!(this instanceof PassThrough)) return new PassThrough(options);
  11065. Transform.call(this, options);
  11066. }
  11067. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  11068. cb(null, chunk);
  11069. };
  11070. },{"./_stream_transform":52,"core-util-is":29,"inherits":32}],51:[function(require,module,exports){
  11071. (function (process,global){
  11072. // Copyright Joyent, Inc. and other Node contributors.
  11073. //
  11074. // Permission is hereby granted, free of charge, to any person obtaining a
  11075. // copy of this software and associated documentation files (the
  11076. // "Software"), to deal in the Software without restriction, including
  11077. // without limitation the rights to use, copy, modify, merge, publish,
  11078. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11079. // persons to whom the Software is furnished to do so, subject to the
  11080. // following conditions:
  11081. //
  11082. // The above copyright notice and this permission notice shall be included
  11083. // in all copies or substantial portions of the Software.
  11084. //
  11085. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11086. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11087. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11088. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11089. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11090. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11091. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11092. 'use strict';
  11093. /*<replacement>*/
  11094. var processNextTick = require('process-nextick-args');
  11095. /*</replacement>*/
  11096. module.exports = Readable;
  11097. /*<replacement>*/
  11098. var isArray = require('isarray');
  11099. /*</replacement>*/
  11100. /*<replacement>*/
  11101. var Duplex;
  11102. /*</replacement>*/
  11103. Readable.ReadableState = ReadableState;
  11104. /*<replacement>*/
  11105. var EE = require('events').EventEmitter;
  11106. var EElistenerCount = function (emitter, type) {
  11107. return emitter.listeners(type).length;
  11108. };
  11109. /*</replacement>*/
  11110. /*<replacement>*/
  11111. var Stream = require('./internal/streams/stream');
  11112. /*</replacement>*/
  11113. // TODO(bmeurer): Change this back to const once hole checks are
  11114. // properly optimized away early in Ignition+TurboFan.
  11115. /*<replacement>*/
  11116. var Buffer = require('safe-buffer').Buffer;
  11117. var OurUint8Array = global.Uint8Array || function () {};
  11118. function _uint8ArrayToBuffer(chunk) {
  11119. return Buffer.from(chunk);
  11120. }
  11121. function _isUint8Array(obj) {
  11122. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  11123. }
  11124. /*</replacement>*/
  11125. /*<replacement>*/
  11126. var util = require('core-util-is');
  11127. util.inherits = require('inherits');
  11128. /*</replacement>*/
  11129. /*<replacement>*/
  11130. var debugUtil = require('util');
  11131. var debug = void 0;
  11132. if (debugUtil && debugUtil.debuglog) {
  11133. debug = debugUtil.debuglog('stream');
  11134. } else {
  11135. debug = function () {};
  11136. }
  11137. /*</replacement>*/
  11138. var BufferList = require('./internal/streams/BufferList');
  11139. var destroyImpl = require('./internal/streams/destroy');
  11140. var StringDecoder;
  11141. util.inherits(Readable, Stream);
  11142. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  11143. function prependListener(emitter, event, fn) {
  11144. // Sadly this is not cacheable as some libraries bundle their own
  11145. // event emitter implementation with them.
  11146. if (typeof emitter.prependListener === 'function') {
  11147. return emitter.prependListener(event, fn);
  11148. } else {
  11149. // This is a hack to make sure that our error handler is attached before any
  11150. // userland ones. NEVER DO THIS. This is here only because this code needs
  11151. // to continue to work with older versions of Node.js that do not include
  11152. // the prependListener() method. The goal is to eventually remove this hack.
  11153. 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]];
  11154. }
  11155. }
  11156. function ReadableState(options, stream) {
  11157. Duplex = Duplex || require('./_stream_duplex');
  11158. options = options || {};
  11159. // object stream flag. Used to make read(n) ignore n and to
  11160. // make all the buffer merging and length checks go away
  11161. this.objectMode = !!options.objectMode;
  11162. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  11163. // the point at which it stops calling _read() to fill the buffer
  11164. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  11165. var hwm = options.highWaterMark;
  11166. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  11167. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  11168. // cast to ints.
  11169. this.highWaterMark = Math.floor(this.highWaterMark);
  11170. // A linked list is used to store data chunks instead of an array because the
  11171. // linked list can remove elements from the beginning faster than
  11172. // array.shift()
  11173. this.buffer = new BufferList();
  11174. this.length = 0;
  11175. this.pipes = null;
  11176. this.pipesCount = 0;
  11177. this.flowing = null;
  11178. this.ended = false;
  11179. this.endEmitted = false;
  11180. this.reading = false;
  11181. // a flag to be able to tell if the event 'readable'/'data' is emitted
  11182. // immediately, or on a later tick. We set this to true at first, because
  11183. // any actions that shouldn't happen until "later" should generally also
  11184. // not happen before the first read call.
  11185. this.sync = true;
  11186. // whenever we return null, then we set a flag to say
  11187. // that we're awaiting a 'readable' event emission.
  11188. this.needReadable = false;
  11189. this.emittedReadable = false;
  11190. this.readableListening = false;
  11191. this.resumeScheduled = false;
  11192. // has it been destroyed
  11193. this.destroyed = false;
  11194. // Crypto is kind of old and crusty. Historically, its default string
  11195. // encoding is 'binary' so we have to make this configurable.
  11196. // Everything else in the universe uses 'utf8', though.
  11197. this.defaultEncoding = options.defaultEncoding || 'utf8';
  11198. // the number of writers that are awaiting a drain event in .pipe()s
  11199. this.awaitDrain = 0;
  11200. // if true, a maybeReadMore has been scheduled
  11201. this.readingMore = false;
  11202. this.decoder = null;
  11203. this.encoding = null;
  11204. if (options.encoding) {
  11205. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11206. this.decoder = new StringDecoder(options.encoding);
  11207. this.encoding = options.encoding;
  11208. }
  11209. }
  11210. function Readable(options) {
  11211. Duplex = Duplex || require('./_stream_duplex');
  11212. if (!(this instanceof Readable)) return new Readable(options);
  11213. this._readableState = new ReadableState(options, this);
  11214. // legacy
  11215. this.readable = true;
  11216. if (options) {
  11217. if (typeof options.read === 'function') this._read = options.read;
  11218. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  11219. }
  11220. Stream.call(this);
  11221. }
  11222. Object.defineProperty(Readable.prototype, 'destroyed', {
  11223. get: function () {
  11224. if (this._readableState === undefined) {
  11225. return false;
  11226. }
  11227. return this._readableState.destroyed;
  11228. },
  11229. set: function (value) {
  11230. // we ignore the value if the stream
  11231. // has not been initialized yet
  11232. if (!this._readableState) {
  11233. return;
  11234. }
  11235. // backward compatibility, the user is explicitly
  11236. // managing destroyed
  11237. this._readableState.destroyed = value;
  11238. }
  11239. });
  11240. Readable.prototype.destroy = destroyImpl.destroy;
  11241. Readable.prototype._undestroy = destroyImpl.undestroy;
  11242. Readable.prototype._destroy = function (err, cb) {
  11243. this.push(null);
  11244. cb(err);
  11245. };
  11246. // Manually shove something into the read() buffer.
  11247. // This returns true if the highWaterMark has not been hit yet,
  11248. // similar to how Writable.write() returns true if you should
  11249. // write() some more.
  11250. Readable.prototype.push = function (chunk, encoding) {
  11251. var state = this._readableState;
  11252. var skipChunkCheck;
  11253. if (!state.objectMode) {
  11254. if (typeof chunk === 'string') {
  11255. encoding = encoding || state.defaultEncoding;
  11256. if (encoding !== state.encoding) {
  11257. chunk = Buffer.from(chunk, encoding);
  11258. encoding = '';
  11259. }
  11260. skipChunkCheck = true;
  11261. }
  11262. } else {
  11263. skipChunkCheck = true;
  11264. }
  11265. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  11266. };
  11267. // Unshift should *always* be something directly out of read()
  11268. Readable.prototype.unshift = function (chunk) {
  11269. return readableAddChunk(this, chunk, null, true, false);
  11270. };
  11271. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  11272. var state = stream._readableState;
  11273. if (chunk === null) {
  11274. state.reading = false;
  11275. onEofChunk(stream, state);
  11276. } else {
  11277. var er;
  11278. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  11279. if (er) {
  11280. stream.emit('error', er);
  11281. } else if (state.objectMode || chunk && chunk.length > 0) {
  11282. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  11283. chunk = _uint8ArrayToBuffer(chunk);
  11284. }
  11285. if (addToFront) {
  11286. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  11287. } else if (state.ended) {
  11288. stream.emit('error', new Error('stream.push() after EOF'));
  11289. } else {
  11290. state.reading = false;
  11291. if (state.decoder && !encoding) {
  11292. chunk = state.decoder.write(chunk);
  11293. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  11294. } else {
  11295. addChunk(stream, state, chunk, false);
  11296. }
  11297. }
  11298. } else if (!addToFront) {
  11299. state.reading = false;
  11300. }
  11301. }
  11302. return needMoreData(state);
  11303. }
  11304. function addChunk(stream, state, chunk, addToFront) {
  11305. if (state.flowing && state.length === 0 && !state.sync) {
  11306. stream.emit('data', chunk);
  11307. stream.read(0);
  11308. } else {
  11309. // update the buffer info.
  11310. state.length += state.objectMode ? 1 : chunk.length;
  11311. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  11312. if (state.needReadable) emitReadable(stream);
  11313. }
  11314. maybeReadMore(stream, state);
  11315. }
  11316. function chunkInvalid(state, chunk) {
  11317. var er;
  11318. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  11319. er = new TypeError('Invalid non-string/buffer chunk');
  11320. }
  11321. return er;
  11322. }
  11323. // if it's past the high water mark, we can push in some more.
  11324. // Also, if we have no data yet, we can stand some
  11325. // more bytes. This is to work around cases where hwm=0,
  11326. // such as the repl. Also, if the push() triggered a
  11327. // readable event, and the user called read(largeNumber) such that
  11328. // needReadable was set, then we ought to push more, so that another
  11329. // 'readable' event will be triggered.
  11330. function needMoreData(state) {
  11331. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  11332. }
  11333. Readable.prototype.isPaused = function () {
  11334. return this._readableState.flowing === false;
  11335. };
  11336. // backwards compatibility.
  11337. Readable.prototype.setEncoding = function (enc) {
  11338. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  11339. this._readableState.decoder = new StringDecoder(enc);
  11340. this._readableState.encoding = enc;
  11341. return this;
  11342. };
  11343. // Don't raise the hwm > 8MB
  11344. var MAX_HWM = 0x800000;
  11345. function computeNewHighWaterMark(n) {
  11346. if (n >= MAX_HWM) {
  11347. n = MAX_HWM;
  11348. } else {
  11349. // Get the next highest power of 2 to prevent increasing hwm excessively in
  11350. // tiny amounts
  11351. n--;
  11352. n |= n >>> 1;
  11353. n |= n >>> 2;
  11354. n |= n >>> 4;
  11355. n |= n >>> 8;
  11356. n |= n >>> 16;
  11357. n++;
  11358. }
  11359. return n;
  11360. }
  11361. // This function is designed to be inlinable, so please take care when making
  11362. // changes to the function body.
  11363. function howMuchToRead(n, state) {
  11364. if (n <= 0 || state.length === 0 && state.ended) return 0;
  11365. if (state.objectMode) return 1;
  11366. if (n !== n) {
  11367. // Only flow one buffer at a time
  11368. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  11369. }
  11370. // If we're asking for more than the current hwm, then raise the hwm.
  11371. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  11372. if (n <= state.length) return n;
  11373. // Don't have enough
  11374. if (!state.ended) {
  11375. state.needReadable = true;
  11376. return 0;
  11377. }
  11378. return state.length;
  11379. }
  11380. // you can override either this method, or the async _read(n) below.
  11381. Readable.prototype.read = function (n) {
  11382. debug('read', n);
  11383. n = parseInt(n, 10);
  11384. var state = this._readableState;
  11385. var nOrig = n;
  11386. if (n !== 0) state.emittedReadable = false;
  11387. // if we're doing read(0) to trigger a readable event, but we
  11388. // already have a bunch of data in the buffer, then just trigger
  11389. // the 'readable' event and move on.
  11390. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  11391. debug('read: emitReadable', state.length, state.ended);
  11392. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  11393. return null;
  11394. }
  11395. n = howMuchToRead(n, state);
  11396. // if we've ended, and we're now clear, then finish it up.
  11397. if (n === 0 && state.ended) {
  11398. if (state.length === 0) endReadable(this);
  11399. return null;
  11400. }
  11401. // All the actual chunk generation logic needs to be
  11402. // *below* the call to _read. The reason is that in certain
  11403. // synthetic stream cases, such as passthrough streams, _read
  11404. // may be a completely synchronous operation which may change
  11405. // the state of the read buffer, providing enough data when
  11406. // before there was *not* enough.
  11407. //
  11408. // So, the steps are:
  11409. // 1. Figure out what the state of things will be after we do
  11410. // a read from the buffer.
  11411. //
  11412. // 2. If that resulting state will trigger a _read, then call _read.
  11413. // Note that this may be asynchronous, or synchronous. Yes, it is
  11414. // deeply ugly to write APIs this way, but that still doesn't mean
  11415. // that the Readable class should behave improperly, as streams are
  11416. // designed to be sync/async agnostic.
  11417. // Take note if the _read call is sync or async (ie, if the read call
  11418. // has returned yet), so that we know whether or not it's safe to emit
  11419. // 'readable' etc.
  11420. //
  11421. // 3. Actually pull the requested chunks out of the buffer and return.
  11422. // if we need a readable event, then we need to do some reading.
  11423. var doRead = state.needReadable;
  11424. debug('need readable', doRead);
  11425. // if we currently have less than the highWaterMark, then also read some
  11426. if (state.length === 0 || state.length - n < state.highWaterMark) {
  11427. doRead = true;
  11428. debug('length less than watermark', doRead);
  11429. }
  11430. // however, if we've ended, then there's no point, and if we're already
  11431. // reading, then it's unnecessary.
  11432. if (state.ended || state.reading) {
  11433. doRead = false;
  11434. debug('reading or ended', doRead);
  11435. } else if (doRead) {
  11436. debug('do read');
  11437. state.reading = true;
  11438. state.sync = true;
  11439. // if the length is currently zero, then we *need* a readable event.
  11440. if (state.length === 0) state.needReadable = true;
  11441. // call internal read method
  11442. this._read(state.highWaterMark);
  11443. state.sync = false;
  11444. // If _read pushed data synchronously, then `reading` will be false,
  11445. // and we need to re-evaluate how much data we can return to the user.
  11446. if (!state.reading) n = howMuchToRead(nOrig, state);
  11447. }
  11448. var ret;
  11449. if (n > 0) ret = fromList(n, state);else ret = null;
  11450. if (ret === null) {
  11451. state.needReadable = true;
  11452. n = 0;
  11453. } else {
  11454. state.length -= n;
  11455. }
  11456. if (state.length === 0) {
  11457. // If we have nothing in the buffer, then we want to know
  11458. // as soon as we *do* get something into the buffer.
  11459. if (!state.ended) state.needReadable = true;
  11460. // If we tried to read() past the EOF, then emit end on the next tick.
  11461. if (nOrig !== n && state.ended) endReadable(this);
  11462. }
  11463. if (ret !== null) this.emit('data', ret);
  11464. return ret;
  11465. };
  11466. function onEofChunk(stream, state) {
  11467. if (state.ended) return;
  11468. if (state.decoder) {
  11469. var chunk = state.decoder.end();
  11470. if (chunk && chunk.length) {
  11471. state.buffer.push(chunk);
  11472. state.length += state.objectMode ? 1 : chunk.length;
  11473. }
  11474. }
  11475. state.ended = true;
  11476. // emit 'readable' now to make sure it gets picked up.
  11477. emitReadable(stream);
  11478. }
  11479. // Don't emit readable right away in sync mode, because this can trigger
  11480. // another read() call => stack overflow. This way, it might trigger
  11481. // a nextTick recursion warning, but that's not so bad.
  11482. function emitReadable(stream) {
  11483. var state = stream._readableState;
  11484. state.needReadable = false;
  11485. if (!state.emittedReadable) {
  11486. debug('emitReadable', state.flowing);
  11487. state.emittedReadable = true;
  11488. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  11489. }
  11490. }
  11491. function emitReadable_(stream) {
  11492. debug('emit readable');
  11493. stream.emit('readable');
  11494. flow(stream);
  11495. }
  11496. // at this point, the user has presumably seen the 'readable' event,
  11497. // and called read() to consume some data. that may have triggered
  11498. // in turn another _read(n) call, in which case reading = true if
  11499. // it's in progress.
  11500. // However, if we're not ended, or reading, and the length < hwm,
  11501. // then go ahead and try to read some more preemptively.
  11502. function maybeReadMore(stream, state) {
  11503. if (!state.readingMore) {
  11504. state.readingMore = true;
  11505. processNextTick(maybeReadMore_, stream, state);
  11506. }
  11507. }
  11508. function maybeReadMore_(stream, state) {
  11509. var len = state.length;
  11510. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  11511. debug('maybeReadMore read 0');
  11512. stream.read(0);
  11513. if (len === state.length)
  11514. // didn't get any data, stop spinning.
  11515. break;else len = state.length;
  11516. }
  11517. state.readingMore = false;
  11518. }
  11519. // abstract method. to be overridden in specific implementation classes.
  11520. // call cb(er, data) where data is <= n in length.
  11521. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  11522. // arbitrary, and perhaps not very meaningful.
  11523. Readable.prototype._read = function (n) {
  11524. this.emit('error', new Error('_read() is not implemented'));
  11525. };
  11526. Readable.prototype.pipe = function (dest, pipeOpts) {
  11527. var src = this;
  11528. var state = this._readableState;
  11529. switch (state.pipesCount) {
  11530. case 0:
  11531. state.pipes = dest;
  11532. break;
  11533. case 1:
  11534. state.pipes = [state.pipes, dest];
  11535. break;
  11536. default:
  11537. state.pipes.push(dest);
  11538. break;
  11539. }
  11540. state.pipesCount += 1;
  11541. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  11542. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  11543. var endFn = doEnd ? onend : unpipe;
  11544. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  11545. dest.on('unpipe', onunpipe);
  11546. function onunpipe(readable, unpipeInfo) {
  11547. debug('onunpipe');
  11548. if (readable === src) {
  11549. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  11550. unpipeInfo.hasUnpiped = true;
  11551. cleanup();
  11552. }
  11553. }
  11554. }
  11555. function onend() {
  11556. debug('onend');
  11557. dest.end();
  11558. }
  11559. // when the dest drains, it reduces the awaitDrain counter
  11560. // on the source. This would be more elegant with a .once()
  11561. // handler in flow(), but adding and removing repeatedly is
  11562. // too slow.
  11563. var ondrain = pipeOnDrain(src);
  11564. dest.on('drain', ondrain);
  11565. var cleanedUp = false;
  11566. function cleanup() {
  11567. debug('cleanup');
  11568. // cleanup event handlers once the pipe is broken
  11569. dest.removeListener('close', onclose);
  11570. dest.removeListener('finish', onfinish);
  11571. dest.removeListener('drain', ondrain);
  11572. dest.removeListener('error', onerror);
  11573. dest.removeListener('unpipe', onunpipe);
  11574. src.removeListener('end', onend);
  11575. src.removeListener('end', unpipe);
  11576. src.removeListener('data', ondata);
  11577. cleanedUp = true;
  11578. // if the reader is waiting for a drain event from this
  11579. // specific writer, then it would cause it to never start
  11580. // flowing again.
  11581. // So, if this is awaiting a drain, then we just call it now.
  11582. // If we don't know, then assume that we are waiting for one.
  11583. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  11584. }
  11585. // If the user pushes more data while we're writing to dest then we'll end up
  11586. // in ondata again. However, we only want to increase awaitDrain once because
  11587. // dest will only emit one 'drain' event for the multiple writes.
  11588. // => Introduce a guard on increasing awaitDrain.
  11589. var increasedAwaitDrain = false;
  11590. src.on('data', ondata);
  11591. function ondata(chunk) {
  11592. debug('ondata');
  11593. increasedAwaitDrain = false;
  11594. var ret = dest.write(chunk);
  11595. if (false === ret && !increasedAwaitDrain) {
  11596. // If the user unpiped during `dest.write()`, it is possible
  11597. // to get stuck in a permanently paused state if that write
  11598. // also returned false.
  11599. // => Check whether `dest` is still a piping destination.
  11600. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  11601. debug('false write response, pause', src._readableState.awaitDrain);
  11602. src._readableState.awaitDrain++;
  11603. increasedAwaitDrain = true;
  11604. }
  11605. src.pause();
  11606. }
  11607. }
  11608. // if the dest has an error, then stop piping into it.
  11609. // however, don't suppress the throwing behavior for this.
  11610. function onerror(er) {
  11611. debug('onerror', er);
  11612. unpipe();
  11613. dest.removeListener('error', onerror);
  11614. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  11615. }
  11616. // Make sure our error handler is attached before userland ones.
  11617. prependListener(dest, 'error', onerror);
  11618. // Both close and finish should trigger unpipe, but only once.
  11619. function onclose() {
  11620. dest.removeListener('finish', onfinish);
  11621. unpipe();
  11622. }
  11623. dest.once('close', onclose);
  11624. function onfinish() {
  11625. debug('onfinish');
  11626. dest.removeListener('close', onclose);
  11627. unpipe();
  11628. }
  11629. dest.once('finish', onfinish);
  11630. function unpipe() {
  11631. debug('unpipe');
  11632. src.unpipe(dest);
  11633. }
  11634. // tell the dest that it's being piped to
  11635. dest.emit('pipe', src);
  11636. // start the flow if it hasn't been started already.
  11637. if (!state.flowing) {
  11638. debug('pipe resume');
  11639. src.resume();
  11640. }
  11641. return dest;
  11642. };
  11643. function pipeOnDrain(src) {
  11644. return function () {
  11645. var state = src._readableState;
  11646. debug('pipeOnDrain', state.awaitDrain);
  11647. if (state.awaitDrain) state.awaitDrain--;
  11648. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  11649. state.flowing = true;
  11650. flow(src);
  11651. }
  11652. };
  11653. }
  11654. Readable.prototype.unpipe = function (dest) {
  11655. var state = this._readableState;
  11656. var unpipeInfo = { hasUnpiped: false };
  11657. // if we're not piping anywhere, then do nothing.
  11658. if (state.pipesCount === 0) return this;
  11659. // just one destination. most common case.
  11660. if (state.pipesCount === 1) {
  11661. // passed in one, but it's not the right one.
  11662. if (dest && dest !== state.pipes) return this;
  11663. if (!dest) dest = state.pipes;
  11664. // got a match.
  11665. state.pipes = null;
  11666. state.pipesCount = 0;
  11667. state.flowing = false;
  11668. if (dest) dest.emit('unpipe', this, unpipeInfo);
  11669. return this;
  11670. }
  11671. // slow case. multiple pipe destinations.
  11672. if (!dest) {
  11673. // remove all.
  11674. var dests = state.pipes;
  11675. var len = state.pipesCount;
  11676. state.pipes = null;
  11677. state.pipesCount = 0;
  11678. state.flowing = false;
  11679. for (var i = 0; i < len; i++) {
  11680. dests[i].emit('unpipe', this, unpipeInfo);
  11681. }return this;
  11682. }
  11683. // try to find the right one.
  11684. var index = indexOf(state.pipes, dest);
  11685. if (index === -1) return this;
  11686. state.pipes.splice(index, 1);
  11687. state.pipesCount -= 1;
  11688. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  11689. dest.emit('unpipe', this, unpipeInfo);
  11690. return this;
  11691. };
  11692. // set up data events if they are asked for
  11693. // Ensure readable listeners eventually get something
  11694. Readable.prototype.on = function (ev, fn) {
  11695. var res = Stream.prototype.on.call(this, ev, fn);
  11696. if (ev === 'data') {
  11697. // Start flowing on next tick if stream isn't explicitly paused
  11698. if (this._readableState.flowing !== false) this.resume();
  11699. } else if (ev === 'readable') {
  11700. var state = this._readableState;
  11701. if (!state.endEmitted && !state.readableListening) {
  11702. state.readableListening = state.needReadable = true;
  11703. state.emittedReadable = false;
  11704. if (!state.reading) {
  11705. processNextTick(nReadingNextTick, this);
  11706. } else if (state.length) {
  11707. emitReadable(this);
  11708. }
  11709. }
  11710. }
  11711. return res;
  11712. };
  11713. Readable.prototype.addListener = Readable.prototype.on;
  11714. function nReadingNextTick(self) {
  11715. debug('readable nexttick read 0');
  11716. self.read(0);
  11717. }
  11718. // pause() and resume() are remnants of the legacy readable stream API
  11719. // If the user uses them, then switch into old mode.
  11720. Readable.prototype.resume = function () {
  11721. var state = this._readableState;
  11722. if (!state.flowing) {
  11723. debug('resume');
  11724. state.flowing = true;
  11725. resume(this, state);
  11726. }
  11727. return this;
  11728. };
  11729. function resume(stream, state) {
  11730. if (!state.resumeScheduled) {
  11731. state.resumeScheduled = true;
  11732. processNextTick(resume_, stream, state);
  11733. }
  11734. }
  11735. function resume_(stream, state) {
  11736. if (!state.reading) {
  11737. debug('resume read 0');
  11738. stream.read(0);
  11739. }
  11740. state.resumeScheduled = false;
  11741. state.awaitDrain = 0;
  11742. stream.emit('resume');
  11743. flow(stream);
  11744. if (state.flowing && !state.reading) stream.read(0);
  11745. }
  11746. Readable.prototype.pause = function () {
  11747. debug('call pause flowing=%j', this._readableState.flowing);
  11748. if (false !== this._readableState.flowing) {
  11749. debug('pause');
  11750. this._readableState.flowing = false;
  11751. this.emit('pause');
  11752. }
  11753. return this;
  11754. };
  11755. function flow(stream) {
  11756. var state = stream._readableState;
  11757. debug('flow', state.flowing);
  11758. while (state.flowing && stream.read() !== null) {}
  11759. }
  11760. // wrap an old-style stream as the async data source.
  11761. // This is *not* part of the readable stream interface.
  11762. // It is an ugly unfortunate mess of history.
  11763. Readable.prototype.wrap = function (stream) {
  11764. var state = this._readableState;
  11765. var paused = false;
  11766. var self = this;
  11767. stream.on('end', function () {
  11768. debug('wrapped end');
  11769. if (state.decoder && !state.ended) {
  11770. var chunk = state.decoder.end();
  11771. if (chunk && chunk.length) self.push(chunk);
  11772. }
  11773. self.push(null);
  11774. });
  11775. stream.on('data', function (chunk) {
  11776. debug('wrapped data');
  11777. if (state.decoder) chunk = state.decoder.write(chunk);
  11778. // don't skip over falsy values in objectMode
  11779. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  11780. var ret = self.push(chunk);
  11781. if (!ret) {
  11782. paused = true;
  11783. stream.pause();
  11784. }
  11785. });
  11786. // proxy all the other methods.
  11787. // important when wrapping filters and duplexes.
  11788. for (var i in stream) {
  11789. if (this[i] === undefined && typeof stream[i] === 'function') {
  11790. this[i] = function (method) {
  11791. return function () {
  11792. return stream[method].apply(stream, arguments);
  11793. };
  11794. }(i);
  11795. }
  11796. }
  11797. // proxy certain important events.
  11798. for (var n = 0; n < kProxyEvents.length; n++) {
  11799. stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
  11800. }
  11801. // when we try to consume some more bytes, simply unpause the
  11802. // underlying stream.
  11803. self._read = function (n) {
  11804. debug('wrapped _read', n);
  11805. if (paused) {
  11806. paused = false;
  11807. stream.resume();
  11808. }
  11809. };
  11810. return self;
  11811. };
  11812. // exposed for testing purposes only.
  11813. Readable._fromList = fromList;
  11814. // Pluck off n bytes from an array of buffers.
  11815. // Length is the combined lengths of all the buffers in the list.
  11816. // This function is designed to be inlinable, so please take care when making
  11817. // changes to the function body.
  11818. function fromList(n, state) {
  11819. // nothing buffered
  11820. if (state.length === 0) return null;
  11821. var ret;
  11822. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  11823. // read it all, truncate the list
  11824. 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);
  11825. state.buffer.clear();
  11826. } else {
  11827. // read part of list
  11828. ret = fromListPartial(n, state.buffer, state.decoder);
  11829. }
  11830. return ret;
  11831. }
  11832. // Extracts only enough buffered data to satisfy the amount requested.
  11833. // This function is designed to be inlinable, so please take care when making
  11834. // changes to the function body.
  11835. function fromListPartial(n, list, hasStrings) {
  11836. var ret;
  11837. if (n < list.head.data.length) {
  11838. // slice is the same for buffers and strings
  11839. ret = list.head.data.slice(0, n);
  11840. list.head.data = list.head.data.slice(n);
  11841. } else if (n === list.head.data.length) {
  11842. // first chunk is a perfect match
  11843. ret = list.shift();
  11844. } else {
  11845. // result spans more than one buffer
  11846. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  11847. }
  11848. return ret;
  11849. }
  11850. // Copies a specified amount of characters from the list of buffered data
  11851. // chunks.
  11852. // This function is designed to be inlinable, so please take care when making
  11853. // changes to the function body.
  11854. function copyFromBufferString(n, list) {
  11855. var p = list.head;
  11856. var c = 1;
  11857. var ret = p.data;
  11858. n -= ret.length;
  11859. while (p = p.next) {
  11860. var str = p.data;
  11861. var nb = n > str.length ? str.length : n;
  11862. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  11863. n -= nb;
  11864. if (n === 0) {
  11865. if (nb === str.length) {
  11866. ++c;
  11867. if (p.next) list.head = p.next;else list.head = list.tail = null;
  11868. } else {
  11869. list.head = p;
  11870. p.data = str.slice(nb);
  11871. }
  11872. break;
  11873. }
  11874. ++c;
  11875. }
  11876. list.length -= c;
  11877. return ret;
  11878. }
  11879. // Copies a specified amount of bytes from the list of buffered data chunks.
  11880. // This function is designed to be inlinable, so please take care when making
  11881. // changes to the function body.
  11882. function copyFromBuffer(n, list) {
  11883. var ret = Buffer.allocUnsafe(n);
  11884. var p = list.head;
  11885. var c = 1;
  11886. p.data.copy(ret);
  11887. n -= p.data.length;
  11888. while (p = p.next) {
  11889. var buf = p.data;
  11890. var nb = n > buf.length ? buf.length : n;
  11891. buf.copy(ret, ret.length - n, 0, nb);
  11892. n -= nb;
  11893. if (n === 0) {
  11894. if (nb === buf.length) {
  11895. ++c;
  11896. if (p.next) list.head = p.next;else list.head = list.tail = null;
  11897. } else {
  11898. list.head = p;
  11899. p.data = buf.slice(nb);
  11900. }
  11901. break;
  11902. }
  11903. ++c;
  11904. }
  11905. list.length -= c;
  11906. return ret;
  11907. }
  11908. function endReadable(stream) {
  11909. var state = stream._readableState;
  11910. // If we get here before consuming all the bytes, then that is a
  11911. // bug in node. Should never happen.
  11912. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  11913. if (!state.endEmitted) {
  11914. state.ended = true;
  11915. processNextTick(endReadableNT, state, stream);
  11916. }
  11917. }
  11918. function endReadableNT(state, stream) {
  11919. // Check that we didn't get one last unshift.
  11920. if (!state.endEmitted && state.length === 0) {
  11921. state.endEmitted = true;
  11922. stream.readable = false;
  11923. stream.emit('end');
  11924. }
  11925. }
  11926. function forEach(xs, f) {
  11927. for (var i = 0, l = xs.length; i < l; i++) {
  11928. f(xs[i], i);
  11929. }
  11930. }
  11931. function indexOf(xs, x) {
  11932. for (var i = 0, l = xs.length; i < l; i++) {
  11933. if (xs[i] === x) return i;
  11934. }
  11935. return -1;
  11936. }
  11937. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11938. },{"./_stream_duplex":49,"./internal/streams/BufferList":54,"./internal/streams/destroy":55,"./internal/streams/stream":56,"_process":47,"core-util-is":29,"events":30,"inherits":32,"isarray":34,"process-nextick-args":46,"safe-buffer":62,"string_decoder/":57,"util":25}],52:[function(require,module,exports){
  11939. // Copyright Joyent, Inc. and other Node contributors.
  11940. //
  11941. // Permission is hereby granted, free of charge, to any person obtaining a
  11942. // copy of this software and associated documentation files (the
  11943. // "Software"), to deal in the Software without restriction, including
  11944. // without limitation the rights to use, copy, modify, merge, publish,
  11945. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11946. // persons to whom the Software is furnished to do so, subject to the
  11947. // following conditions:
  11948. //
  11949. // The above copyright notice and this permission notice shall be included
  11950. // in all copies or substantial portions of the Software.
  11951. //
  11952. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11953. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11954. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11955. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11956. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11957. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11958. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11959. // a transform stream is a readable/writable stream where you do
  11960. // something with the data. Sometimes it's called a "filter",
  11961. // but that's not a great name for it, since that implies a thing where
  11962. // some bits pass through, and others are simply ignored. (That would
  11963. // be a valid example of a transform, of course.)
  11964. //
  11965. // While the output is causally related to the input, it's not a
  11966. // necessarily symmetric or synchronous transformation. For example,
  11967. // a zlib stream might take multiple plain-text writes(), and then
  11968. // emit a single compressed chunk some time in the future.
  11969. //
  11970. // Here's how this works:
  11971. //
  11972. // The Transform stream has all the aspects of the readable and writable
  11973. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  11974. // internally, and returns false if there's a lot of pending writes
  11975. // buffered up. When you call read(), that calls _read(n) until
  11976. // there's enough pending readable data buffered up.
  11977. //
  11978. // In a transform stream, the written data is placed in a buffer. When
  11979. // _read(n) is called, it transforms the queued up data, calling the
  11980. // buffered _write cb's as it consumes chunks. If consuming a single
  11981. // written chunk would result in multiple output chunks, then the first
  11982. // outputted bit calls the readcb, and subsequent chunks just go into
  11983. // the read buffer, and will cause it to emit 'readable' if necessary.
  11984. //
  11985. // This way, back-pressure is actually determined by the reading side,
  11986. // since _read has to be called to start processing a new chunk. However,
  11987. // a pathological inflate type of transform can cause excessive buffering
  11988. // here. For example, imagine a stream where every byte of input is
  11989. // interpreted as an integer from 0-255, and then results in that many
  11990. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  11991. // 1kb of data being output. In this case, you could write a very small
  11992. // amount of input, and end up with a very large amount of output. In
  11993. // such a pathological inflating mechanism, there'd be no way to tell
  11994. // the system to stop doing the transform. A single 4MB write could
  11995. // cause the system to run out of memory.
  11996. //
  11997. // However, even in such a pathological case, only a single written chunk
  11998. // would be consumed, and then the rest would wait (un-transformed) until
  11999. // the results of the previous transformed chunk were consumed.
  12000. 'use strict';
  12001. module.exports = Transform;
  12002. var Duplex = require('./_stream_duplex');
  12003. /*<replacement>*/
  12004. var util = require('core-util-is');
  12005. util.inherits = require('inherits');
  12006. /*</replacement>*/
  12007. util.inherits(Transform, Duplex);
  12008. function TransformState(stream) {
  12009. this.afterTransform = function (er, data) {
  12010. return afterTransform(stream, er, data);
  12011. };
  12012. this.needTransform = false;
  12013. this.transforming = false;
  12014. this.writecb = null;
  12015. this.writechunk = null;
  12016. this.writeencoding = null;
  12017. }
  12018. function afterTransform(stream, er, data) {
  12019. var ts = stream._transformState;
  12020. ts.transforming = false;
  12021. var cb = ts.writecb;
  12022. if (!cb) {
  12023. return stream.emit('error', new Error('write callback called multiple times'));
  12024. }
  12025. ts.writechunk = null;
  12026. ts.writecb = null;
  12027. if (data !== null && data !== undefined) stream.push(data);
  12028. cb(er);
  12029. var rs = stream._readableState;
  12030. rs.reading = false;
  12031. if (rs.needReadable || rs.length < rs.highWaterMark) {
  12032. stream._read(rs.highWaterMark);
  12033. }
  12034. }
  12035. function Transform(options) {
  12036. if (!(this instanceof Transform)) return new Transform(options);
  12037. Duplex.call(this, options);
  12038. this._transformState = new TransformState(this);
  12039. var stream = this;
  12040. // start out asking for a readable event once data is transformed.
  12041. this._readableState.needReadable = true;
  12042. // we have implemented the _read method, and done the other things
  12043. // that Readable wants before the first _read call, so unset the
  12044. // sync guard flag.
  12045. this._readableState.sync = false;
  12046. if (options) {
  12047. if (typeof options.transform === 'function') this._transform = options.transform;
  12048. if (typeof options.flush === 'function') this._flush = options.flush;
  12049. }
  12050. // When the writable side finishes, then flush out anything remaining.
  12051. this.once('prefinish', function () {
  12052. if (typeof this._flush === 'function') this._flush(function (er, data) {
  12053. done(stream, er, data);
  12054. });else done(stream);
  12055. });
  12056. }
  12057. Transform.prototype.push = function (chunk, encoding) {
  12058. this._transformState.needTransform = false;
  12059. return Duplex.prototype.push.call(this, chunk, encoding);
  12060. };
  12061. // This is the part where you do stuff!
  12062. // override this function in implementation classes.
  12063. // 'chunk' is an input chunk.
  12064. //
  12065. // Call `push(newChunk)` to pass along transformed output
  12066. // to the readable side. You may call 'push' zero or more times.
  12067. //
  12068. // Call `cb(err)` when you are done with this chunk. If you pass
  12069. // an error, then that'll put the hurt on the whole operation. If you
  12070. // never call cb(), then you'll never get another chunk.
  12071. Transform.prototype._transform = function (chunk, encoding, cb) {
  12072. throw new Error('_transform() is not implemented');
  12073. };
  12074. Transform.prototype._write = function (chunk, encoding, cb) {
  12075. var ts = this._transformState;
  12076. ts.writecb = cb;
  12077. ts.writechunk = chunk;
  12078. ts.writeencoding = encoding;
  12079. if (!ts.transforming) {
  12080. var rs = this._readableState;
  12081. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  12082. }
  12083. };
  12084. // Doesn't matter what the args are here.
  12085. // _transform does all the work.
  12086. // That we got here means that the readable side wants more data.
  12087. Transform.prototype._read = function (n) {
  12088. var ts = this._transformState;
  12089. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  12090. ts.transforming = true;
  12091. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  12092. } else {
  12093. // mark that we need a transform, so that any data that comes in
  12094. // will get processed, now that we've asked for it.
  12095. ts.needTransform = true;
  12096. }
  12097. };
  12098. Transform.prototype._destroy = function (err, cb) {
  12099. var _this = this;
  12100. Duplex.prototype._destroy.call(this, err, function (err2) {
  12101. cb(err2);
  12102. _this.emit('close');
  12103. });
  12104. };
  12105. function done(stream, er, data) {
  12106. if (er) return stream.emit('error', er);
  12107. if (data !== null && data !== undefined) stream.push(data);
  12108. // if there's nothing in the write buffer, then that means
  12109. // that nothing more will ever be provided
  12110. var ws = stream._writableState;
  12111. var ts = stream._transformState;
  12112. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  12113. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  12114. return stream.push(null);
  12115. }
  12116. },{"./_stream_duplex":49,"core-util-is":29,"inherits":32}],53:[function(require,module,exports){
  12117. (function (process,global){
  12118. // Copyright Joyent, Inc. and other Node contributors.
  12119. //
  12120. // Permission is hereby granted, free of charge, to any person obtaining a
  12121. // copy of this software and associated documentation files (the
  12122. // "Software"), to deal in the Software without restriction, including
  12123. // without limitation the rights to use, copy, modify, merge, publish,
  12124. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12125. // persons to whom the Software is furnished to do so, subject to the
  12126. // following conditions:
  12127. //
  12128. // The above copyright notice and this permission notice shall be included
  12129. // in all copies or substantial portions of the Software.
  12130. //
  12131. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12132. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12133. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12134. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12135. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12136. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12137. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12138. // A bit simpler than readable streams.
  12139. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  12140. // the drain event emission and buffering.
  12141. 'use strict';
  12142. /*<replacement>*/
  12143. var processNextTick = require('process-nextick-args');
  12144. /*</replacement>*/
  12145. module.exports = Writable;
  12146. /* <replacement> */
  12147. function WriteReq(chunk, encoding, cb) {
  12148. this.chunk = chunk;
  12149. this.encoding = encoding;
  12150. this.callback = cb;
  12151. this.next = null;
  12152. }
  12153. // It seems a linked list but it is not
  12154. // there will be only 2 of these for each stream
  12155. function CorkedRequest(state) {
  12156. var _this = this;
  12157. this.next = null;
  12158. this.entry = null;
  12159. this.finish = function () {
  12160. onCorkedFinish(_this, state);
  12161. };
  12162. }
  12163. /* </replacement> */
  12164. /*<replacement>*/
  12165. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  12166. /*</replacement>*/
  12167. /*<replacement>*/
  12168. var Duplex;
  12169. /*</replacement>*/
  12170. Writable.WritableState = WritableState;
  12171. /*<replacement>*/
  12172. var util = require('core-util-is');
  12173. util.inherits = require('inherits');
  12174. /*</replacement>*/
  12175. /*<replacement>*/
  12176. var internalUtil = {
  12177. deprecate: require('util-deprecate')
  12178. };
  12179. /*</replacement>*/
  12180. /*<replacement>*/
  12181. var Stream = require('./internal/streams/stream');
  12182. /*</replacement>*/
  12183. /*<replacement>*/
  12184. var Buffer = require('safe-buffer').Buffer;
  12185. var OurUint8Array = global.Uint8Array || function () {};
  12186. function _uint8ArrayToBuffer(chunk) {
  12187. return Buffer.from(chunk);
  12188. }
  12189. function _isUint8Array(obj) {
  12190. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12191. }
  12192. /*</replacement>*/
  12193. var destroyImpl = require('./internal/streams/destroy');
  12194. util.inherits(Writable, Stream);
  12195. function nop() {}
  12196. function WritableState(options, stream) {
  12197. Duplex = Duplex || require('./_stream_duplex');
  12198. options = options || {};
  12199. // object stream flag to indicate whether or not this stream
  12200. // contains buffers or objects.
  12201. this.objectMode = !!options.objectMode;
  12202. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  12203. // the point at which write() starts returning false
  12204. // Note: 0 is a valid value, means that we always return false if
  12205. // the entire buffer is not flushed immediately on write()
  12206. var hwm = options.highWaterMark;
  12207. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  12208. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  12209. // cast to ints.
  12210. this.highWaterMark = Math.floor(this.highWaterMark);
  12211. // if _final has been called
  12212. this.finalCalled = false;
  12213. // drain event flag.
  12214. this.needDrain = false;
  12215. // at the start of calling end()
  12216. this.ending = false;
  12217. // when end() has been called, and returned
  12218. this.ended = false;
  12219. // when 'finish' is emitted
  12220. this.finished = false;
  12221. // has it been destroyed
  12222. this.destroyed = false;
  12223. // should we decode strings into buffers before passing to _write?
  12224. // this is here so that some node-core streams can optimize string
  12225. // handling at a lower level.
  12226. var noDecode = options.decodeStrings === false;
  12227. this.decodeStrings = !noDecode;
  12228. // Crypto is kind of old and crusty. Historically, its default string
  12229. // encoding is 'binary' so we have to make this configurable.
  12230. // Everything else in the universe uses 'utf8', though.
  12231. this.defaultEncoding = options.defaultEncoding || 'utf8';
  12232. // not an actual buffer we keep track of, but a measurement
  12233. // of how much we're waiting to get pushed to some underlying
  12234. // socket or file.
  12235. this.length = 0;
  12236. // a flag to see when we're in the middle of a write.
  12237. this.writing = false;
  12238. // when true all writes will be buffered until .uncork() call
  12239. this.corked = 0;
  12240. // a flag to be able to tell if the onwrite cb is called immediately,
  12241. // or on a later tick. We set this to true at first, because any
  12242. // actions that shouldn't happen until "later" should generally also
  12243. // not happen before the first write call.
  12244. this.sync = true;
  12245. // a flag to know if we're processing previously buffered items, which
  12246. // may call the _write() callback in the same tick, so that we don't
  12247. // end up in an overlapped onwrite situation.
  12248. this.bufferProcessing = false;
  12249. // the callback that's passed to _write(chunk,cb)
  12250. this.onwrite = function (er) {
  12251. onwrite(stream, er);
  12252. };
  12253. // the callback that the user supplies to write(chunk,encoding,cb)
  12254. this.writecb = null;
  12255. // the amount that is being written when _write is called.
  12256. this.writelen = 0;
  12257. this.bufferedRequest = null;
  12258. this.lastBufferedRequest = null;
  12259. // number of pending user-supplied write callbacks
  12260. // this must be 0 before 'finish' can be emitted
  12261. this.pendingcb = 0;
  12262. // emit prefinish if the only thing we're waiting for is _write cbs
  12263. // This is relevant for synchronous Transform streams
  12264. this.prefinished = false;
  12265. // True if the error was already emitted and should not be thrown again
  12266. this.errorEmitted = false;
  12267. // count buffered requests
  12268. this.bufferedRequestCount = 0;
  12269. // allocate the first CorkedRequest, there is always
  12270. // one allocated and free to use, and we maintain at most two
  12271. this.corkedRequestsFree = new CorkedRequest(this);
  12272. }
  12273. WritableState.prototype.getBuffer = function getBuffer() {
  12274. var current = this.bufferedRequest;
  12275. var out = [];
  12276. while (current) {
  12277. out.push(current);
  12278. current = current.next;
  12279. }
  12280. return out;
  12281. };
  12282. (function () {
  12283. try {
  12284. Object.defineProperty(WritableState.prototype, 'buffer', {
  12285. get: internalUtil.deprecate(function () {
  12286. return this.getBuffer();
  12287. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  12288. });
  12289. } catch (_) {}
  12290. })();
  12291. // Test _writableState for inheritance to account for Duplex streams,
  12292. // whose prototype chain only points to Readable.
  12293. var realHasInstance;
  12294. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  12295. realHasInstance = Function.prototype[Symbol.hasInstance];
  12296. Object.defineProperty(Writable, Symbol.hasInstance, {
  12297. value: function (object) {
  12298. if (realHasInstance.call(this, object)) return true;
  12299. return object && object._writableState instanceof WritableState;
  12300. }
  12301. });
  12302. } else {
  12303. realHasInstance = function (object) {
  12304. return object instanceof this;
  12305. };
  12306. }
  12307. function Writable(options) {
  12308. Duplex = Duplex || require('./_stream_duplex');
  12309. // Writable ctor is applied to Duplexes, too.
  12310. // `realHasInstance` is necessary because using plain `instanceof`
  12311. // would return false, as no `_writableState` property is attached.
  12312. // Trying to use the custom `instanceof` for Writable here will also break the
  12313. // Node.js LazyTransform implementation, which has a non-trivial getter for
  12314. // `_writableState` that would lead to infinite recursion.
  12315. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  12316. return new Writable(options);
  12317. }
  12318. this._writableState = new WritableState(options, this);
  12319. // legacy.
  12320. this.writable = true;
  12321. if (options) {
  12322. if (typeof options.write === 'function') this._write = options.write;
  12323. if (typeof options.writev === 'function') this._writev = options.writev;
  12324. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12325. if (typeof options.final === 'function') this._final = options.final;
  12326. }
  12327. Stream.call(this);
  12328. }
  12329. // Otherwise people can pipe Writable streams, which is just wrong.
  12330. Writable.prototype.pipe = function () {
  12331. this.emit('error', new Error('Cannot pipe, not readable'));
  12332. };
  12333. function writeAfterEnd(stream, cb) {
  12334. var er = new Error('write after end');
  12335. // TODO: defer error events consistently everywhere, not just the cb
  12336. stream.emit('error', er);
  12337. processNextTick(cb, er);
  12338. }
  12339. // Checks that a user-supplied chunk is valid, especially for the particular
  12340. // mode the stream is in. Currently this means that `null` is never accepted
  12341. // and undefined/non-string values are only allowed in object mode.
  12342. function validChunk(stream, state, chunk, cb) {
  12343. var valid = true;
  12344. var er = false;
  12345. if (chunk === null) {
  12346. er = new TypeError('May not write null values to stream');
  12347. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12348. er = new TypeError('Invalid non-string/buffer chunk');
  12349. }
  12350. if (er) {
  12351. stream.emit('error', er);
  12352. processNextTick(cb, er);
  12353. valid = false;
  12354. }
  12355. return valid;
  12356. }
  12357. Writable.prototype.write = function (chunk, encoding, cb) {
  12358. var state = this._writableState;
  12359. var ret = false;
  12360. var isBuf = _isUint8Array(chunk) && !state.objectMode;
  12361. if (isBuf && !Buffer.isBuffer(chunk)) {
  12362. chunk = _uint8ArrayToBuffer(chunk);
  12363. }
  12364. if (typeof encoding === 'function') {
  12365. cb = encoding;
  12366. encoding = null;
  12367. }
  12368. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  12369. if (typeof cb !== 'function') cb = nop;
  12370. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  12371. state.pendingcb++;
  12372. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  12373. }
  12374. return ret;
  12375. };
  12376. Writable.prototype.cork = function () {
  12377. var state = this._writableState;
  12378. state.corked++;
  12379. };
  12380. Writable.prototype.uncork = function () {
  12381. var state = this._writableState;
  12382. if (state.corked) {
  12383. state.corked--;
  12384. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  12385. }
  12386. };
  12387. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  12388. // node::ParseEncoding() requires lower case.
  12389. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  12390. 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);
  12391. this._writableState.defaultEncoding = encoding;
  12392. return this;
  12393. };
  12394. function decodeChunk(state, chunk, encoding) {
  12395. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  12396. chunk = Buffer.from(chunk, encoding);
  12397. }
  12398. return chunk;
  12399. }
  12400. // if we're already writing something, then just put this
  12401. // in the queue, and wait our turn. Otherwise, call _write
  12402. // If we return false, then we need a drain event, so set that flag.
  12403. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  12404. if (!isBuf) {
  12405. var newChunk = decodeChunk(state, chunk, encoding);
  12406. if (chunk !== newChunk) {
  12407. isBuf = true;
  12408. encoding = 'buffer';
  12409. chunk = newChunk;
  12410. }
  12411. }
  12412. var len = state.objectMode ? 1 : chunk.length;
  12413. state.length += len;
  12414. var ret = state.length < state.highWaterMark;
  12415. // we must ensure that previous needDrain will not be reset to false.
  12416. if (!ret) state.needDrain = true;
  12417. if (state.writing || state.corked) {
  12418. var last = state.lastBufferedRequest;
  12419. state.lastBufferedRequest = {
  12420. chunk: chunk,
  12421. encoding: encoding,
  12422. isBuf: isBuf,
  12423. callback: cb,
  12424. next: null
  12425. };
  12426. if (last) {
  12427. last.next = state.lastBufferedRequest;
  12428. } else {
  12429. state.bufferedRequest = state.lastBufferedRequest;
  12430. }
  12431. state.bufferedRequestCount += 1;
  12432. } else {
  12433. doWrite(stream, state, false, len, chunk, encoding, cb);
  12434. }
  12435. return ret;
  12436. }
  12437. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  12438. state.writelen = len;
  12439. state.writecb = cb;
  12440. state.writing = true;
  12441. state.sync = true;
  12442. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  12443. state.sync = false;
  12444. }
  12445. function onwriteError(stream, state, sync, er, cb) {
  12446. --state.pendingcb;
  12447. if (sync) {
  12448. // defer the callback if we are being called synchronously
  12449. // to avoid piling up things on the stack
  12450. processNextTick(cb, er);
  12451. // this can emit finish, and it will always happen
  12452. // after error
  12453. processNextTick(finishMaybe, stream, state);
  12454. stream._writableState.errorEmitted = true;
  12455. stream.emit('error', er);
  12456. } else {
  12457. // the caller expect this to happen before if
  12458. // it is async
  12459. cb(er);
  12460. stream._writableState.errorEmitted = true;
  12461. stream.emit('error', er);
  12462. // this can emit finish, but finish must
  12463. // always follow error
  12464. finishMaybe(stream, state);
  12465. }
  12466. }
  12467. function onwriteStateUpdate(state) {
  12468. state.writing = false;
  12469. state.writecb = null;
  12470. state.length -= state.writelen;
  12471. state.writelen = 0;
  12472. }
  12473. function onwrite(stream, er) {
  12474. var state = stream._writableState;
  12475. var sync = state.sync;
  12476. var cb = state.writecb;
  12477. onwriteStateUpdate(state);
  12478. if (er) onwriteError(stream, state, sync, er, cb);else {
  12479. // Check if we're actually ready to finish, but don't emit yet
  12480. var finished = needFinish(state);
  12481. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  12482. clearBuffer(stream, state);
  12483. }
  12484. if (sync) {
  12485. /*<replacement>*/
  12486. asyncWrite(afterWrite, stream, state, finished, cb);
  12487. /*</replacement>*/
  12488. } else {
  12489. afterWrite(stream, state, finished, cb);
  12490. }
  12491. }
  12492. }
  12493. function afterWrite(stream, state, finished, cb) {
  12494. if (!finished) onwriteDrain(stream, state);
  12495. state.pendingcb--;
  12496. cb();
  12497. finishMaybe(stream, state);
  12498. }
  12499. // Must force callback to be called on nextTick, so that we don't
  12500. // emit 'drain' before the write() consumer gets the 'false' return
  12501. // value, and has a chance to attach a 'drain' listener.
  12502. function onwriteDrain(stream, state) {
  12503. if (state.length === 0 && state.needDrain) {
  12504. state.needDrain = false;
  12505. stream.emit('drain');
  12506. }
  12507. }
  12508. // if there's something in the buffer waiting, then process it
  12509. function clearBuffer(stream, state) {
  12510. state.bufferProcessing = true;
  12511. var entry = state.bufferedRequest;
  12512. if (stream._writev && entry && entry.next) {
  12513. // Fast case, write everything using _writev()
  12514. var l = state.bufferedRequestCount;
  12515. var buffer = new Array(l);
  12516. var holder = state.corkedRequestsFree;
  12517. holder.entry = entry;
  12518. var count = 0;
  12519. var allBuffers = true;
  12520. while (entry) {
  12521. buffer[count] = entry;
  12522. if (!entry.isBuf) allBuffers = false;
  12523. entry = entry.next;
  12524. count += 1;
  12525. }
  12526. buffer.allBuffers = allBuffers;
  12527. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  12528. // doWrite is almost always async, defer these to save a bit of time
  12529. // as the hot path ends with doWrite
  12530. state.pendingcb++;
  12531. state.lastBufferedRequest = null;
  12532. if (holder.next) {
  12533. state.corkedRequestsFree = holder.next;
  12534. holder.next = null;
  12535. } else {
  12536. state.corkedRequestsFree = new CorkedRequest(state);
  12537. }
  12538. } else {
  12539. // Slow case, write chunks one-by-one
  12540. while (entry) {
  12541. var chunk = entry.chunk;
  12542. var encoding = entry.encoding;
  12543. var cb = entry.callback;
  12544. var len = state.objectMode ? 1 : chunk.length;
  12545. doWrite(stream, state, false, len, chunk, encoding, cb);
  12546. entry = entry.next;
  12547. // if we didn't call the onwrite immediately, then
  12548. // it means that we need to wait until it does.
  12549. // also, that means that the chunk and cb are currently
  12550. // being processed, so move the buffer counter past them.
  12551. if (state.writing) {
  12552. break;
  12553. }
  12554. }
  12555. if (entry === null) state.lastBufferedRequest = null;
  12556. }
  12557. state.bufferedRequestCount = 0;
  12558. state.bufferedRequest = entry;
  12559. state.bufferProcessing = false;
  12560. }
  12561. Writable.prototype._write = function (chunk, encoding, cb) {
  12562. cb(new Error('_write() is not implemented'));
  12563. };
  12564. Writable.prototype._writev = null;
  12565. Writable.prototype.end = function (chunk, encoding, cb) {
  12566. var state = this._writableState;
  12567. if (typeof chunk === 'function') {
  12568. cb = chunk;
  12569. chunk = null;
  12570. encoding = null;
  12571. } else if (typeof encoding === 'function') {
  12572. cb = encoding;
  12573. encoding = null;
  12574. }
  12575. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  12576. // .end() fully uncorks
  12577. if (state.corked) {
  12578. state.corked = 1;
  12579. this.uncork();
  12580. }
  12581. // ignore unnecessary end() calls.
  12582. if (!state.ending && !state.finished) endWritable(this, state, cb);
  12583. };
  12584. function needFinish(state) {
  12585. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  12586. }
  12587. function callFinal(stream, state) {
  12588. stream._final(function (err) {
  12589. state.pendingcb--;
  12590. if (err) {
  12591. stream.emit('error', err);
  12592. }
  12593. state.prefinished = true;
  12594. stream.emit('prefinish');
  12595. finishMaybe(stream, state);
  12596. });
  12597. }
  12598. function prefinish(stream, state) {
  12599. if (!state.prefinished && !state.finalCalled) {
  12600. if (typeof stream._final === 'function') {
  12601. state.pendingcb++;
  12602. state.finalCalled = true;
  12603. processNextTick(callFinal, stream, state);
  12604. } else {
  12605. state.prefinished = true;
  12606. stream.emit('prefinish');
  12607. }
  12608. }
  12609. }
  12610. function finishMaybe(stream, state) {
  12611. var need = needFinish(state);
  12612. if (need) {
  12613. prefinish(stream, state);
  12614. if (state.pendingcb === 0) {
  12615. state.finished = true;
  12616. stream.emit('finish');
  12617. }
  12618. }
  12619. return need;
  12620. }
  12621. function endWritable(stream, state, cb) {
  12622. state.ending = true;
  12623. finishMaybe(stream, state);
  12624. if (cb) {
  12625. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  12626. }
  12627. state.ended = true;
  12628. stream.writable = false;
  12629. }
  12630. function onCorkedFinish(corkReq, state, err) {
  12631. var entry = corkReq.entry;
  12632. corkReq.entry = null;
  12633. while (entry) {
  12634. var cb = entry.callback;
  12635. state.pendingcb--;
  12636. cb(err);
  12637. entry = entry.next;
  12638. }
  12639. if (state.corkedRequestsFree) {
  12640. state.corkedRequestsFree.next = corkReq;
  12641. } else {
  12642. state.corkedRequestsFree = corkReq;
  12643. }
  12644. }
  12645. Object.defineProperty(Writable.prototype, 'destroyed', {
  12646. get: function () {
  12647. if (this._writableState === undefined) {
  12648. return false;
  12649. }
  12650. return this._writableState.destroyed;
  12651. },
  12652. set: function (value) {
  12653. // we ignore the value if the stream
  12654. // has not been initialized yet
  12655. if (!this._writableState) {
  12656. return;
  12657. }
  12658. // backward compatibility, the user is explicitly
  12659. // managing destroyed
  12660. this._writableState.destroyed = value;
  12661. }
  12662. });
  12663. Writable.prototype.destroy = destroyImpl.destroy;
  12664. Writable.prototype._undestroy = destroyImpl.undestroy;
  12665. Writable.prototype._destroy = function (err, cb) {
  12666. this.end();
  12667. cb(err);
  12668. };
  12669. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12670. },{"./_stream_duplex":49,"./internal/streams/destroy":55,"./internal/streams/stream":56,"_process":47,"core-util-is":29,"inherits":32,"process-nextick-args":46,"safe-buffer":62,"util-deprecate":64}],54:[function(require,module,exports){
  12671. 'use strict';
  12672. /*<replacement>*/
  12673. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12674. var Buffer = require('safe-buffer').Buffer;
  12675. /*</replacement>*/
  12676. function copyBuffer(src, target, offset) {
  12677. src.copy(target, offset);
  12678. }
  12679. module.exports = function () {
  12680. function BufferList() {
  12681. _classCallCheck(this, BufferList);
  12682. this.head = null;
  12683. this.tail = null;
  12684. this.length = 0;
  12685. }
  12686. BufferList.prototype.push = function push(v) {
  12687. var entry = { data: v, next: null };
  12688. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  12689. this.tail = entry;
  12690. ++this.length;
  12691. };
  12692. BufferList.prototype.unshift = function unshift(v) {
  12693. var entry = { data: v, next: this.head };
  12694. if (this.length === 0) this.tail = entry;
  12695. this.head = entry;
  12696. ++this.length;
  12697. };
  12698. BufferList.prototype.shift = function shift() {
  12699. if (this.length === 0) return;
  12700. var ret = this.head.data;
  12701. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  12702. --this.length;
  12703. return ret;
  12704. };
  12705. BufferList.prototype.clear = function clear() {
  12706. this.head = this.tail = null;
  12707. this.length = 0;
  12708. };
  12709. BufferList.prototype.join = function join(s) {
  12710. if (this.length === 0) return '';
  12711. var p = this.head;
  12712. var ret = '' + p.data;
  12713. while (p = p.next) {
  12714. ret += s + p.data;
  12715. }return ret;
  12716. };
  12717. BufferList.prototype.concat = function concat(n) {
  12718. if (this.length === 0) return Buffer.alloc(0);
  12719. if (this.length === 1) return this.head.data;
  12720. var ret = Buffer.allocUnsafe(n >>> 0);
  12721. var p = this.head;
  12722. var i = 0;
  12723. while (p) {
  12724. copyBuffer(p.data, ret, i);
  12725. i += p.data.length;
  12726. p = p.next;
  12727. }
  12728. return ret;
  12729. };
  12730. return BufferList;
  12731. }();
  12732. },{"safe-buffer":62}],55:[function(require,module,exports){
  12733. 'use strict';
  12734. /*<replacement>*/
  12735. var processNextTick = require('process-nextick-args');
  12736. /*</replacement>*/
  12737. // undocumented cb() API, needed for core, not for public API
  12738. function destroy(err, cb) {
  12739. var _this = this;
  12740. var readableDestroyed = this._readableState && this._readableState.destroyed;
  12741. var writableDestroyed = this._writableState && this._writableState.destroyed;
  12742. if (readableDestroyed || writableDestroyed) {
  12743. if (cb) {
  12744. cb(err);
  12745. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  12746. processNextTick(emitErrorNT, this, err);
  12747. }
  12748. return;
  12749. }
  12750. // we set destroyed to true before firing error callbacks in order
  12751. // to make it re-entrance safe in case destroy() is called within callbacks
  12752. if (this._readableState) {
  12753. this._readableState.destroyed = true;
  12754. }
  12755. // if this is a duplex stream mark the writable part as destroyed as well
  12756. if (this._writableState) {
  12757. this._writableState.destroyed = true;
  12758. }
  12759. this._destroy(err || null, function (err) {
  12760. if (!cb && err) {
  12761. processNextTick(emitErrorNT, _this, err);
  12762. if (_this._writableState) {
  12763. _this._writableState.errorEmitted = true;
  12764. }
  12765. } else if (cb) {
  12766. cb(err);
  12767. }
  12768. });
  12769. }
  12770. function undestroy() {
  12771. if (this._readableState) {
  12772. this._readableState.destroyed = false;
  12773. this._readableState.reading = false;
  12774. this._readableState.ended = false;
  12775. this._readableState.endEmitted = false;
  12776. }
  12777. if (this._writableState) {
  12778. this._writableState.destroyed = false;
  12779. this._writableState.ended = false;
  12780. this._writableState.ending = false;
  12781. this._writableState.finished = false;
  12782. this._writableState.errorEmitted = false;
  12783. }
  12784. }
  12785. function emitErrorNT(self, err) {
  12786. self.emit('error', err);
  12787. }
  12788. module.exports = {
  12789. destroy: destroy,
  12790. undestroy: undestroy
  12791. };
  12792. },{"process-nextick-args":46}],56:[function(require,module,exports){
  12793. module.exports = require('events').EventEmitter;
  12794. },{"events":30}],57:[function(require,module,exports){
  12795. 'use strict';
  12796. var Buffer = require('safe-buffer').Buffer;
  12797. var isEncoding = Buffer.isEncoding || function (encoding) {
  12798. encoding = '' + encoding;
  12799. switch (encoding && encoding.toLowerCase()) {
  12800. 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':
  12801. return true;
  12802. default:
  12803. return false;
  12804. }
  12805. };
  12806. function _normalizeEncoding(enc) {
  12807. if (!enc) return 'utf8';
  12808. var retried;
  12809. while (true) {
  12810. switch (enc) {
  12811. case 'utf8':
  12812. case 'utf-8':
  12813. return 'utf8';
  12814. case 'ucs2':
  12815. case 'ucs-2':
  12816. case 'utf16le':
  12817. case 'utf-16le':
  12818. return 'utf16le';
  12819. case 'latin1':
  12820. case 'binary':
  12821. return 'latin1';
  12822. case 'base64':
  12823. case 'ascii':
  12824. case 'hex':
  12825. return enc;
  12826. default:
  12827. if (retried) return; // undefined
  12828. enc = ('' + enc).toLowerCase();
  12829. retried = true;
  12830. }
  12831. }
  12832. };
  12833. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  12834. // modules monkey-patch it to support additional encodings
  12835. function normalizeEncoding(enc) {
  12836. var nenc = _normalizeEncoding(enc);
  12837. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  12838. return nenc || enc;
  12839. }
  12840. // StringDecoder provides an interface for efficiently splitting a series of
  12841. // buffers into a series of JS strings without breaking apart multi-byte
  12842. // characters.
  12843. exports.StringDecoder = StringDecoder;
  12844. function StringDecoder(encoding) {
  12845. this.encoding = normalizeEncoding(encoding);
  12846. var nb;
  12847. switch (this.encoding) {
  12848. case 'utf16le':
  12849. this.text = utf16Text;
  12850. this.end = utf16End;
  12851. nb = 4;
  12852. break;
  12853. case 'utf8':
  12854. this.fillLast = utf8FillLast;
  12855. nb = 4;
  12856. break;
  12857. case 'base64':
  12858. this.text = base64Text;
  12859. this.end = base64End;
  12860. nb = 3;
  12861. break;
  12862. default:
  12863. this.write = simpleWrite;
  12864. this.end = simpleEnd;
  12865. return;
  12866. }
  12867. this.lastNeed = 0;
  12868. this.lastTotal = 0;
  12869. this.lastChar = Buffer.allocUnsafe(nb);
  12870. }
  12871. StringDecoder.prototype.write = function (buf) {
  12872. if (buf.length === 0) return '';
  12873. var r;
  12874. var i;
  12875. if (this.lastNeed) {
  12876. r = this.fillLast(buf);
  12877. if (r === undefined) return '';
  12878. i = this.lastNeed;
  12879. this.lastNeed = 0;
  12880. } else {
  12881. i = 0;
  12882. }
  12883. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  12884. return r || '';
  12885. };
  12886. StringDecoder.prototype.end = utf8End;
  12887. // Returns only complete characters in a Buffer
  12888. StringDecoder.prototype.text = utf8Text;
  12889. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  12890. StringDecoder.prototype.fillLast = function (buf) {
  12891. if (this.lastNeed <= buf.length) {
  12892. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  12893. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  12894. }
  12895. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  12896. this.lastNeed -= buf.length;
  12897. };
  12898. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  12899. // continuation byte.
  12900. function utf8CheckByte(byte) {
  12901. 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;
  12902. return -1;
  12903. }
  12904. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  12905. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  12906. // needed to complete the UTF-8 character (if applicable) are returned.
  12907. function utf8CheckIncomplete(self, buf, i) {
  12908. var j = buf.length - 1;
  12909. if (j < i) return 0;
  12910. var nb = utf8CheckByte(buf[j]);
  12911. if (nb >= 0) {
  12912. if (nb > 0) self.lastNeed = nb - 1;
  12913. return nb;
  12914. }
  12915. if (--j < i) return 0;
  12916. nb = utf8CheckByte(buf[j]);
  12917. if (nb >= 0) {
  12918. if (nb > 0) self.lastNeed = nb - 2;
  12919. return nb;
  12920. }
  12921. if (--j < i) return 0;
  12922. nb = utf8CheckByte(buf[j]);
  12923. if (nb >= 0) {
  12924. if (nb > 0) {
  12925. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  12926. }
  12927. return nb;
  12928. }
  12929. return 0;
  12930. }
  12931. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  12932. // needed or are available. If we see a non-continuation byte where we expect
  12933. // one, we "replace" the validated continuation bytes we've seen so far with
  12934. // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
  12935. // behavior. The continuation byte check is included three times in the case
  12936. // where all of the continuation bytes for a character exist in the same buffer.
  12937. // It is also done this way as a slight performance increase instead of using a
  12938. // loop.
  12939. function utf8CheckExtraBytes(self, buf, p) {
  12940. if ((buf[0] & 0xC0) !== 0x80) {
  12941. self.lastNeed = 0;
  12942. return '\ufffd'.repeat(p);
  12943. }
  12944. if (self.lastNeed > 1 && buf.length > 1) {
  12945. if ((buf[1] & 0xC0) !== 0x80) {
  12946. self.lastNeed = 1;
  12947. return '\ufffd'.repeat(p + 1);
  12948. }
  12949. if (self.lastNeed > 2 && buf.length > 2) {
  12950. if ((buf[2] & 0xC0) !== 0x80) {
  12951. self.lastNeed = 2;
  12952. return '\ufffd'.repeat(p + 2);
  12953. }
  12954. }
  12955. }
  12956. }
  12957. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  12958. function utf8FillLast(buf) {
  12959. var p = this.lastTotal - this.lastNeed;
  12960. var r = utf8CheckExtraBytes(this, buf, p);
  12961. if (r !== undefined) return r;
  12962. if (this.lastNeed <= buf.length) {
  12963. buf.copy(this.lastChar, p, 0, this.lastNeed);
  12964. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  12965. }
  12966. buf.copy(this.lastChar, p, 0, buf.length);
  12967. this.lastNeed -= buf.length;
  12968. }
  12969. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  12970. // partial character, the character's bytes are buffered until the required
  12971. // number of bytes are available.
  12972. function utf8Text(buf, i) {
  12973. var total = utf8CheckIncomplete(this, buf, i);
  12974. if (!this.lastNeed) return buf.toString('utf8', i);
  12975. this.lastTotal = total;
  12976. var end = buf.length - (total - this.lastNeed);
  12977. buf.copy(this.lastChar, 0, end);
  12978. return buf.toString('utf8', i, end);
  12979. }
  12980. // For UTF-8, a replacement character for each buffered byte of a (partial)
  12981. // character needs to be added to the output.
  12982. function utf8End(buf) {
  12983. var r = buf && buf.length ? this.write(buf) : '';
  12984. if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
  12985. return r;
  12986. }
  12987. // UTF-16LE typically needs two bytes per character, but even if we have an even
  12988. // number of bytes available, we need to check if we end on a leading/high
  12989. // surrogate. In that case, we need to wait for the next two bytes in order to
  12990. // decode the last character properly.
  12991. function utf16Text(buf, i) {
  12992. if ((buf.length - i) % 2 === 0) {
  12993. var r = buf.toString('utf16le', i);
  12994. if (r) {
  12995. var c = r.charCodeAt(r.length - 1);
  12996. if (c >= 0xD800 && c <= 0xDBFF) {
  12997. this.lastNeed = 2;
  12998. this.lastTotal = 4;
  12999. this.lastChar[0] = buf[buf.length - 2];
  13000. this.lastChar[1] = buf[buf.length - 1];
  13001. return r.slice(0, -1);
  13002. }
  13003. }
  13004. return r;
  13005. }
  13006. this.lastNeed = 1;
  13007. this.lastTotal = 2;
  13008. this.lastChar[0] = buf[buf.length - 1];
  13009. return buf.toString('utf16le', i, buf.length - 1);
  13010. }
  13011. // For UTF-16LE we do not explicitly append special replacement characters if we
  13012. // end on a partial character, we simply let v8 handle that.
  13013. function utf16End(buf) {
  13014. var r = buf && buf.length ? this.write(buf) : '';
  13015. if (this.lastNeed) {
  13016. var end = this.lastTotal - this.lastNeed;
  13017. return r + this.lastChar.toString('utf16le', 0, end);
  13018. }
  13019. return r;
  13020. }
  13021. function base64Text(buf, i) {
  13022. var n = (buf.length - i) % 3;
  13023. if (n === 0) return buf.toString('base64', i);
  13024. this.lastNeed = 3 - n;
  13025. this.lastTotal = 3;
  13026. if (n === 1) {
  13027. this.lastChar[0] = buf[buf.length - 1];
  13028. } else {
  13029. this.lastChar[0] = buf[buf.length - 2];
  13030. this.lastChar[1] = buf[buf.length - 1];
  13031. }
  13032. return buf.toString('base64', i, buf.length - n);
  13033. }
  13034. function base64End(buf) {
  13035. var r = buf && buf.length ? this.write(buf) : '';
  13036. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  13037. return r;
  13038. }
  13039. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  13040. function simpleWrite(buf) {
  13041. return buf.toString(this.encoding);
  13042. }
  13043. function simpleEnd(buf) {
  13044. return buf && buf.length ? this.write(buf) : '';
  13045. }
  13046. },{"safe-buffer":62}],58:[function(require,module,exports){
  13047. module.exports = require('./readable').PassThrough
  13048. },{"./readable":59}],59:[function(require,module,exports){
  13049. exports = module.exports = require('./lib/_stream_readable.js');
  13050. exports.Stream = exports;
  13051. exports.Readable = exports;
  13052. exports.Writable = require('./lib/_stream_writable.js');
  13053. exports.Duplex = require('./lib/_stream_duplex.js');
  13054. exports.Transform = require('./lib/_stream_transform.js');
  13055. exports.PassThrough = require('./lib/_stream_passthrough.js');
  13056. },{"./lib/_stream_duplex.js":49,"./lib/_stream_passthrough.js":50,"./lib/_stream_readable.js":51,"./lib/_stream_transform.js":52,"./lib/_stream_writable.js":53}],60:[function(require,module,exports){
  13057. module.exports = require('./readable').Transform
  13058. },{"./readable":59}],61:[function(require,module,exports){
  13059. module.exports = require('./lib/_stream_writable.js');
  13060. },{"./lib/_stream_writable.js":53}],62:[function(require,module,exports){
  13061. /* eslint-disable node/no-deprecated-api */
  13062. var buffer = require('buffer')
  13063. var Buffer = buffer.Buffer
  13064. // alternative to using Object.keys for old browsers
  13065. function copyProps (src, dst) {
  13066. for (var key in src) {
  13067. dst[key] = src[key]
  13068. }
  13069. }
  13070. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  13071. module.exports = buffer
  13072. } else {
  13073. // Copy properties from require('buffer')
  13074. copyProps(buffer, exports)
  13075. exports.Buffer = SafeBuffer
  13076. }
  13077. function SafeBuffer (arg, encodingOrOffset, length) {
  13078. return Buffer(arg, encodingOrOffset, length)
  13079. }
  13080. // Copy static methods from Buffer
  13081. copyProps(Buffer, SafeBuffer)
  13082. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  13083. if (typeof arg === 'number') {
  13084. throw new TypeError('Argument must not be a number')
  13085. }
  13086. return Buffer(arg, encodingOrOffset, length)
  13087. }
  13088. SafeBuffer.alloc = function (size, fill, encoding) {
  13089. if (typeof size !== 'number') {
  13090. throw new TypeError('Argument must be a number')
  13091. }
  13092. var buf = Buffer(size)
  13093. if (fill !== undefined) {
  13094. if (typeof encoding === 'string') {
  13095. buf.fill(fill, encoding)
  13096. } else {
  13097. buf.fill(fill)
  13098. }
  13099. } else {
  13100. buf.fill(0)
  13101. }
  13102. return buf
  13103. }
  13104. SafeBuffer.allocUnsafe = function (size) {
  13105. if (typeof size !== 'number') {
  13106. throw new TypeError('Argument must be a number')
  13107. }
  13108. return Buffer(size)
  13109. }
  13110. SafeBuffer.allocUnsafeSlow = function (size) {
  13111. if (typeof size !== 'number') {
  13112. throw new TypeError('Argument must be a number')
  13113. }
  13114. return buffer.SlowBuffer(size)
  13115. }
  13116. },{"buffer":28}],63:[function(require,module,exports){
  13117. // Copyright Joyent, Inc. and other Node contributors.
  13118. //
  13119. // Permission is hereby granted, free of charge, to any person obtaining a
  13120. // copy of this software and associated documentation files (the
  13121. // "Software"), to deal in the Software without restriction, including
  13122. // without limitation the rights to use, copy, modify, merge, publish,
  13123. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13124. // persons to whom the Software is furnished to do so, subject to the
  13125. // following conditions:
  13126. //
  13127. // The above copyright notice and this permission notice shall be included
  13128. // in all copies or substantial portions of the Software.
  13129. //
  13130. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13131. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13132. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13133. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13134. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13135. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13136. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13137. module.exports = Stream;
  13138. var EE = require('events').EventEmitter;
  13139. var inherits = require('inherits');
  13140. inherits(Stream, EE);
  13141. Stream.Readable = require('readable-stream/readable.js');
  13142. Stream.Writable = require('readable-stream/writable.js');
  13143. Stream.Duplex = require('readable-stream/duplex.js');
  13144. Stream.Transform = require('readable-stream/transform.js');
  13145. Stream.PassThrough = require('readable-stream/passthrough.js');
  13146. // Backwards-compat with node 0.4.x
  13147. Stream.Stream = Stream;
  13148. // old-style streams. Note that the pipe method (the only relevant
  13149. // part of this class) is overridden in the Readable class.
  13150. function Stream() {
  13151. EE.call(this);
  13152. }
  13153. Stream.prototype.pipe = function(dest, options) {
  13154. var source = this;
  13155. function ondata(chunk) {
  13156. if (dest.writable) {
  13157. if (false === dest.write(chunk) && source.pause) {
  13158. source.pause();
  13159. }
  13160. }
  13161. }
  13162. source.on('data', ondata);
  13163. function ondrain() {
  13164. if (source.readable && source.resume) {
  13165. source.resume();
  13166. }
  13167. }
  13168. dest.on('drain', ondrain);
  13169. // If the 'end' option is not supplied, dest.end() will be called when
  13170. // source gets the 'end' or 'close' events. Only dest.end() once.
  13171. if (!dest._isStdio && (!options || options.end !== false)) {
  13172. source.on('end', onend);
  13173. source.on('close', onclose);
  13174. }
  13175. var didOnEnd = false;
  13176. function onend() {
  13177. if (didOnEnd) return;
  13178. didOnEnd = true;
  13179. dest.end();
  13180. }
  13181. function onclose() {
  13182. if (didOnEnd) return;
  13183. didOnEnd = true;
  13184. if (typeof dest.destroy === 'function') dest.destroy();
  13185. }
  13186. // don't leave dangling pipes when there are errors.
  13187. function onerror(er) {
  13188. cleanup();
  13189. if (EE.listenerCount(this, 'error') === 0) {
  13190. throw er; // Unhandled stream error in pipe.
  13191. }
  13192. }
  13193. source.on('error', onerror);
  13194. dest.on('error', onerror);
  13195. // remove all the event listeners that were added.
  13196. function cleanup() {
  13197. source.removeListener('data', ondata);
  13198. dest.removeListener('drain', ondrain);
  13199. source.removeListener('end', onend);
  13200. source.removeListener('close', onclose);
  13201. source.removeListener('error', onerror);
  13202. dest.removeListener('error', onerror);
  13203. source.removeListener('end', cleanup);
  13204. source.removeListener('close', cleanup);
  13205. dest.removeListener('close', cleanup);
  13206. }
  13207. source.on('end', cleanup);
  13208. source.on('close', cleanup);
  13209. dest.on('close', cleanup);
  13210. dest.emit('pipe', source);
  13211. // Allow for unix-like usage: A.pipe(B).pipe(C)
  13212. return dest;
  13213. };
  13214. },{"events":30,"inherits":32,"readable-stream/duplex.js":48,"readable-stream/passthrough.js":58,"readable-stream/readable.js":59,"readable-stream/transform.js":60,"readable-stream/writable.js":61}],64:[function(require,module,exports){
  13215. (function (global){
  13216. /**
  13217. * Module exports.
  13218. */
  13219. module.exports = deprecate;
  13220. /**
  13221. * Mark that a method should not be used.
  13222. * Returns a modified function which warns once by default.
  13223. *
  13224. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  13225. *
  13226. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  13227. * will throw an Error when invoked.
  13228. *
  13229. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  13230. * will invoke `console.trace()` instead of `console.error()`.
  13231. *
  13232. * @param {Function} fn - the function to deprecate
  13233. * @param {String} msg - the string to print to the console when `fn` is invoked
  13234. * @returns {Function} a new "deprecated" version of `fn`
  13235. * @api public
  13236. */
  13237. function deprecate (fn, msg) {
  13238. if (config('noDeprecation')) {
  13239. return fn;
  13240. }
  13241. var warned = false;
  13242. function deprecated() {
  13243. if (!warned) {
  13244. if (config('throwDeprecation')) {
  13245. throw new Error(msg);
  13246. } else if (config('traceDeprecation')) {
  13247. console.trace(msg);
  13248. } else {
  13249. console.warn(msg);
  13250. }
  13251. warned = true;
  13252. }
  13253. return fn.apply(this, arguments);
  13254. }
  13255. return deprecated;
  13256. }
  13257. /**
  13258. * Checks `localStorage` for boolean values for the given `name`.
  13259. *
  13260. * @param {String} name
  13261. * @returns {Boolean}
  13262. * @api private
  13263. */
  13264. function config (name) {
  13265. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  13266. try {
  13267. if (!global.localStorage) return false;
  13268. } catch (_) {
  13269. return false;
  13270. }
  13271. var val = global.localStorage[name];
  13272. if (null == val) return false;
  13273. return String(val).toLowerCase() === 'true';
  13274. }
  13275. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13276. },{}],65:[function(require,module,exports){
  13277. arguments[4][32][0].apply(exports,arguments)
  13278. },{"dup":32}],66:[function(require,module,exports){
  13279. module.exports = function isBuffer(arg) {
  13280. return arg && typeof arg === 'object'
  13281. && typeof arg.copy === 'function'
  13282. && typeof arg.fill === 'function'
  13283. && typeof arg.readUInt8 === 'function';
  13284. }
  13285. },{}],67:[function(require,module,exports){
  13286. (function (process,global){
  13287. // Copyright Joyent, Inc. and other Node contributors.
  13288. //
  13289. // Permission is hereby granted, free of charge, to any person obtaining a
  13290. // copy of this software and associated documentation files (the
  13291. // "Software"), to deal in the Software without restriction, including
  13292. // without limitation the rights to use, copy, modify, merge, publish,
  13293. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13294. // persons to whom the Software is furnished to do so, subject to the
  13295. // following conditions:
  13296. //
  13297. // The above copyright notice and this permission notice shall be included
  13298. // in all copies or substantial portions of the Software.
  13299. //
  13300. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13301. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13302. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13303. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13304. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13305. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13306. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13307. var formatRegExp = /%[sdj%]/g;
  13308. exports.format = function(f) {
  13309. if (!isString(f)) {
  13310. var objects = [];
  13311. for (var i = 0; i < arguments.length; i++) {
  13312. objects.push(inspect(arguments[i]));
  13313. }
  13314. return objects.join(' ');
  13315. }
  13316. var i = 1;
  13317. var args = arguments;
  13318. var len = args.length;
  13319. var str = String(f).replace(formatRegExp, function(x) {
  13320. if (x === '%%') return '%';
  13321. if (i >= len) return x;
  13322. switch (x) {
  13323. case '%s': return String(args[i++]);
  13324. case '%d': return Number(args[i++]);
  13325. case '%j':
  13326. try {
  13327. return JSON.stringify(args[i++]);
  13328. } catch (_) {
  13329. return '[Circular]';
  13330. }
  13331. default:
  13332. return x;
  13333. }
  13334. });
  13335. for (var x = args[i]; i < len; x = args[++i]) {
  13336. if (isNull(x) || !isObject(x)) {
  13337. str += ' ' + x;
  13338. } else {
  13339. str += ' ' + inspect(x);
  13340. }
  13341. }
  13342. return str;
  13343. };
  13344. // Mark that a method should not be used.
  13345. // Returns a modified function which warns once by default.
  13346. // If --no-deprecation is set, then it is a no-op.
  13347. exports.deprecate = function(fn, msg) {
  13348. // Allow for deprecating things in the process of starting up.
  13349. if (isUndefined(global.process)) {
  13350. return function() {
  13351. return exports.deprecate(fn, msg).apply(this, arguments);
  13352. };
  13353. }
  13354. if (process.noDeprecation === true) {
  13355. return fn;
  13356. }
  13357. var warned = false;
  13358. function deprecated() {
  13359. if (!warned) {
  13360. if (process.throwDeprecation) {
  13361. throw new Error(msg);
  13362. } else if (process.traceDeprecation) {
  13363. console.trace(msg);
  13364. } else {
  13365. console.error(msg);
  13366. }
  13367. warned = true;
  13368. }
  13369. return fn.apply(this, arguments);
  13370. }
  13371. return deprecated;
  13372. };
  13373. var debugs = {};
  13374. var debugEnviron;
  13375. exports.debuglog = function(set) {
  13376. if (isUndefined(debugEnviron))
  13377. debugEnviron = process.env.NODE_DEBUG || '';
  13378. set = set.toUpperCase();
  13379. if (!debugs[set]) {
  13380. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  13381. var pid = process.pid;
  13382. debugs[set] = function() {
  13383. var msg = exports.format.apply(exports, arguments);
  13384. console.error('%s %d: %s', set, pid, msg);
  13385. };
  13386. } else {
  13387. debugs[set] = function() {};
  13388. }
  13389. }
  13390. return debugs[set];
  13391. };
  13392. /**
  13393. * Echos the value of a value. Trys to print the value out
  13394. * in the best way possible given the different types.
  13395. *
  13396. * @param {Object} obj The object to print out.
  13397. * @param {Object} opts Optional options object that alters the output.
  13398. */
  13399. /* legacy: obj, showHidden, depth, colors*/
  13400. function inspect(obj, opts) {
  13401. // default options
  13402. var ctx = {
  13403. seen: [],
  13404. stylize: stylizeNoColor
  13405. };
  13406. // legacy...
  13407. if (arguments.length >= 3) ctx.depth = arguments[2];
  13408. if (arguments.length >= 4) ctx.colors = arguments[3];
  13409. if (isBoolean(opts)) {
  13410. // legacy...
  13411. ctx.showHidden = opts;
  13412. } else if (opts) {
  13413. // got an "options" object
  13414. exports._extend(ctx, opts);
  13415. }
  13416. // set default options
  13417. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  13418. if (isUndefined(ctx.depth)) ctx.depth = 2;
  13419. if (isUndefined(ctx.colors)) ctx.colors = false;
  13420. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  13421. if (ctx.colors) ctx.stylize = stylizeWithColor;
  13422. return formatValue(ctx, obj, ctx.depth);
  13423. }
  13424. exports.inspect = inspect;
  13425. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  13426. inspect.colors = {
  13427. 'bold' : [1, 22],
  13428. 'italic' : [3, 23],
  13429. 'underline' : [4, 24],
  13430. 'inverse' : [7, 27],
  13431. 'white' : [37, 39],
  13432. 'grey' : [90, 39],
  13433. 'black' : [30, 39],
  13434. 'blue' : [34, 39],
  13435. 'cyan' : [36, 39],
  13436. 'green' : [32, 39],
  13437. 'magenta' : [35, 39],
  13438. 'red' : [31, 39],
  13439. 'yellow' : [33, 39]
  13440. };
  13441. // Don't use 'blue' not visible on cmd.exe
  13442. inspect.styles = {
  13443. 'special': 'cyan',
  13444. 'number': 'yellow',
  13445. 'boolean': 'yellow',
  13446. 'undefined': 'grey',
  13447. 'null': 'bold',
  13448. 'string': 'green',
  13449. 'date': 'magenta',
  13450. // "name": intentionally not styling
  13451. 'regexp': 'red'
  13452. };
  13453. function stylizeWithColor(str, styleType) {
  13454. var style = inspect.styles[styleType];
  13455. if (style) {
  13456. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  13457. '\u001b[' + inspect.colors[style][1] + 'm';
  13458. } else {
  13459. return str;
  13460. }
  13461. }
  13462. function stylizeNoColor(str, styleType) {
  13463. return str;
  13464. }
  13465. function arrayToHash(array) {
  13466. var hash = {};
  13467. array.forEach(function(val, idx) {
  13468. hash[val] = true;
  13469. });
  13470. return hash;
  13471. }
  13472. function formatValue(ctx, value, recurseTimes) {
  13473. // Provide a hook for user-specified inspect functions.
  13474. // Check that value is an object with an inspect function on it
  13475. if (ctx.customInspect &&
  13476. value &&
  13477. isFunction(value.inspect) &&
  13478. // Filter out the util module, it's inspect function is special
  13479. value.inspect !== exports.inspect &&
  13480. // Also filter out any prototype objects using the circular check.
  13481. !(value.constructor && value.constructor.prototype === value)) {
  13482. var ret = value.inspect(recurseTimes, ctx);
  13483. if (!isString(ret)) {
  13484. ret = formatValue(ctx, ret, recurseTimes);
  13485. }
  13486. return ret;
  13487. }
  13488. // Primitive types cannot have properties
  13489. var primitive = formatPrimitive(ctx, value);
  13490. if (primitive) {
  13491. return primitive;
  13492. }
  13493. // Look up the keys of the object.
  13494. var keys = Object.keys(value);
  13495. var visibleKeys = arrayToHash(keys);
  13496. if (ctx.showHidden) {
  13497. keys = Object.getOwnPropertyNames(value);
  13498. }
  13499. // IE doesn't make error fields non-enumerable
  13500. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  13501. if (isError(value)
  13502. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  13503. return formatError(value);
  13504. }
  13505. // Some type of object without properties can be shortcutted.
  13506. if (keys.length === 0) {
  13507. if (isFunction(value)) {
  13508. var name = value.name ? ': ' + value.name : '';
  13509. return ctx.stylize('[Function' + name + ']', 'special');
  13510. }
  13511. if (isRegExp(value)) {
  13512. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13513. }
  13514. if (isDate(value)) {
  13515. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  13516. }
  13517. if (isError(value)) {
  13518. return formatError(value);
  13519. }
  13520. }
  13521. var base = '', array = false, braces = ['{', '}'];
  13522. // Make Array say that they are Array
  13523. if (isArray(value)) {
  13524. array = true;
  13525. braces = ['[', ']'];
  13526. }
  13527. // Make functions say that they are functions
  13528. if (isFunction(value)) {
  13529. var n = value.name ? ': ' + value.name : '';
  13530. base = ' [Function' + n + ']';
  13531. }
  13532. // Make RegExps say that they are RegExps
  13533. if (isRegExp(value)) {
  13534. base = ' ' + RegExp.prototype.toString.call(value);
  13535. }
  13536. // Make dates with properties first say the date
  13537. if (isDate(value)) {
  13538. base = ' ' + Date.prototype.toUTCString.call(value);
  13539. }
  13540. // Make error with message first say the error
  13541. if (isError(value)) {
  13542. base = ' ' + formatError(value);
  13543. }
  13544. if (keys.length === 0 && (!array || value.length == 0)) {
  13545. return braces[0] + base + braces[1];
  13546. }
  13547. if (recurseTimes < 0) {
  13548. if (isRegExp(value)) {
  13549. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13550. } else {
  13551. return ctx.stylize('[Object]', 'special');
  13552. }
  13553. }
  13554. ctx.seen.push(value);
  13555. var output;
  13556. if (array) {
  13557. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  13558. } else {
  13559. output = keys.map(function(key) {
  13560. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  13561. });
  13562. }
  13563. ctx.seen.pop();
  13564. return reduceToSingleString(output, base, braces);
  13565. }
  13566. function formatPrimitive(ctx, value) {
  13567. if (isUndefined(value))
  13568. return ctx.stylize('undefined', 'undefined');
  13569. if (isString(value)) {
  13570. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  13571. .replace(/'/g, "\\'")
  13572. .replace(/\\"/g, '"') + '\'';
  13573. return ctx.stylize(simple, 'string');
  13574. }
  13575. if (isNumber(value))
  13576. return ctx.stylize('' + value, 'number');
  13577. if (isBoolean(value))
  13578. return ctx.stylize('' + value, 'boolean');
  13579. // For some reason typeof null is "object", so special case here.
  13580. if (isNull(value))
  13581. return ctx.stylize('null', 'null');
  13582. }
  13583. function formatError(value) {
  13584. return '[' + Error.prototype.toString.call(value) + ']';
  13585. }
  13586. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  13587. var output = [];
  13588. for (var i = 0, l = value.length; i < l; ++i) {
  13589. if (hasOwnProperty(value, String(i))) {
  13590. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13591. String(i), true));
  13592. } else {
  13593. output.push('');
  13594. }
  13595. }
  13596. keys.forEach(function(key) {
  13597. if (!key.match(/^\d+$/)) {
  13598. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13599. key, true));
  13600. }
  13601. });
  13602. return output;
  13603. }
  13604. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  13605. var name, str, desc;
  13606. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  13607. if (desc.get) {
  13608. if (desc.set) {
  13609. str = ctx.stylize('[Getter/Setter]', 'special');
  13610. } else {
  13611. str = ctx.stylize('[Getter]', 'special');
  13612. }
  13613. } else {
  13614. if (desc.set) {
  13615. str = ctx.stylize('[Setter]', 'special');
  13616. }
  13617. }
  13618. if (!hasOwnProperty(visibleKeys, key)) {
  13619. name = '[' + key + ']';
  13620. }
  13621. if (!str) {
  13622. if (ctx.seen.indexOf(desc.value) < 0) {
  13623. if (isNull(recurseTimes)) {
  13624. str = formatValue(ctx, desc.value, null);
  13625. } else {
  13626. str = formatValue(ctx, desc.value, recurseTimes - 1);
  13627. }
  13628. if (str.indexOf('\n') > -1) {
  13629. if (array) {
  13630. str = str.split('\n').map(function(line) {
  13631. return ' ' + line;
  13632. }).join('\n').substr(2);
  13633. } else {
  13634. str = '\n' + str.split('\n').map(function(line) {
  13635. return ' ' + line;
  13636. }).join('\n');
  13637. }
  13638. }
  13639. } else {
  13640. str = ctx.stylize('[Circular]', 'special');
  13641. }
  13642. }
  13643. if (isUndefined(name)) {
  13644. if (array && key.match(/^\d+$/)) {
  13645. return str;
  13646. }
  13647. name = JSON.stringify('' + key);
  13648. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  13649. name = name.substr(1, name.length - 2);
  13650. name = ctx.stylize(name, 'name');
  13651. } else {
  13652. name = name.replace(/'/g, "\\'")
  13653. .replace(/\\"/g, '"')
  13654. .replace(/(^"|"$)/g, "'");
  13655. name = ctx.stylize(name, 'string');
  13656. }
  13657. }
  13658. return name + ': ' + str;
  13659. }
  13660. function reduceToSingleString(output, base, braces) {
  13661. var numLinesEst = 0;
  13662. var length = output.reduce(function(prev, cur) {
  13663. numLinesEst++;
  13664. if (cur.indexOf('\n') >= 0) numLinesEst++;
  13665. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  13666. }, 0);
  13667. if (length > 60) {
  13668. return braces[0] +
  13669. (base === '' ? '' : base + '\n ') +
  13670. ' ' +
  13671. output.join(',\n ') +
  13672. ' ' +
  13673. braces[1];
  13674. }
  13675. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  13676. }
  13677. // NOTE: These type checking functions intentionally don't use `instanceof`
  13678. // because it is fragile and can be easily faked with `Object.create()`.
  13679. function isArray(ar) {
  13680. return Array.isArray(ar);
  13681. }
  13682. exports.isArray = isArray;
  13683. function isBoolean(arg) {
  13684. return typeof arg === 'boolean';
  13685. }
  13686. exports.isBoolean = isBoolean;
  13687. function isNull(arg) {
  13688. return arg === null;
  13689. }
  13690. exports.isNull = isNull;
  13691. function isNullOrUndefined(arg) {
  13692. return arg == null;
  13693. }
  13694. exports.isNullOrUndefined = isNullOrUndefined;
  13695. function isNumber(arg) {
  13696. return typeof arg === 'number';
  13697. }
  13698. exports.isNumber = isNumber;
  13699. function isString(arg) {
  13700. return typeof arg === 'string';
  13701. }
  13702. exports.isString = isString;
  13703. function isSymbol(arg) {
  13704. return typeof arg === 'symbol';
  13705. }
  13706. exports.isSymbol = isSymbol;
  13707. function isUndefined(arg) {
  13708. return arg === void 0;
  13709. }
  13710. exports.isUndefined = isUndefined;
  13711. function isRegExp(re) {
  13712. return isObject(re) && objectToString(re) === '[object RegExp]';
  13713. }
  13714. exports.isRegExp = isRegExp;
  13715. function isObject(arg) {
  13716. return typeof arg === 'object' && arg !== null;
  13717. }
  13718. exports.isObject = isObject;
  13719. function isDate(d) {
  13720. return isObject(d) && objectToString(d) === '[object Date]';
  13721. }
  13722. exports.isDate = isDate;
  13723. function isError(e) {
  13724. return isObject(e) &&
  13725. (objectToString(e) === '[object Error]' || e instanceof Error);
  13726. }
  13727. exports.isError = isError;
  13728. function isFunction(arg) {
  13729. return typeof arg === 'function';
  13730. }
  13731. exports.isFunction = isFunction;
  13732. function isPrimitive(arg) {
  13733. return arg === null ||
  13734. typeof arg === 'boolean' ||
  13735. typeof arg === 'number' ||
  13736. typeof arg === 'string' ||
  13737. typeof arg === 'symbol' || // ES6 symbol
  13738. typeof arg === 'undefined';
  13739. }
  13740. exports.isPrimitive = isPrimitive;
  13741. exports.isBuffer = require('./support/isBuffer');
  13742. function objectToString(o) {
  13743. return Object.prototype.toString.call(o);
  13744. }
  13745. function pad(n) {
  13746. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  13747. }
  13748. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  13749. 'Oct', 'Nov', 'Dec'];
  13750. // 26 Feb 16:19:34
  13751. function timestamp() {
  13752. var d = new Date();
  13753. var time = [pad(d.getHours()),
  13754. pad(d.getMinutes()),
  13755. pad(d.getSeconds())].join(':');
  13756. return [d.getDate(), months[d.getMonth()], time].join(' ');
  13757. }
  13758. // log is just a thin wrapper to console.log that prepends a timestamp
  13759. exports.log = function() {
  13760. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  13761. };
  13762. /**
  13763. * Inherit the prototype methods from one constructor into another.
  13764. *
  13765. * The Function.prototype.inherits from lang.js rewritten as a standalone
  13766. * function (not on Function.prototype). NOTE: If this file is to be loaded
  13767. * during bootstrapping this function needs to be rewritten using some native
  13768. * functions as prototype setup using normal JavaScript does not work as
  13769. * expected during bootstrapping (see mirror.js in r114903).
  13770. *
  13771. * @param {function} ctor Constructor function which needs to inherit the
  13772. * prototype.
  13773. * @param {function} superCtor Constructor function to inherit prototype from.
  13774. */
  13775. exports.inherits = require('inherits');
  13776. exports._extend = function(origin, add) {
  13777. // Don't do anything if add isn't an object
  13778. if (!add || !isObject(add)) return origin;
  13779. var keys = Object.keys(add);
  13780. var i = keys.length;
  13781. while (i--) {
  13782. origin[keys[i]] = add[keys[i]];
  13783. }
  13784. return origin;
  13785. };
  13786. function hasOwnProperty(obj, prop) {
  13787. return Object.prototype.hasOwnProperty.call(obj, prop);
  13788. }
  13789. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13790. },{"./support/isBuffer":66,"_process":47,"inherits":65}]},{},[20])(20)
  13791. });