1
0

jszip.js 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367
  1. /*!
  2. JSZip v3.2.1 - A JavaScript class for generating and reading zip files
  3. <http://stuartk.com/jszip>
  4. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  5. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  6. JSZip uses the library pako released under the MIT license :
  7. https://github.com/nodeca/pako/blob/master/LICENSE
  8. */
  9. (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.JSZip = 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){
  10. 'use strict';
  11. var utils = require('./utils');
  12. var support = require('./support');
  13. // private property
  14. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  15. // public method for encoding
  16. exports.encode = function(input) {
  17. var output = [];
  18. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  19. var i = 0, len = input.length, remainingBytes = len;
  20. var isArray = utils.getTypeOf(input) !== "string";
  21. while (i < input.length) {
  22. remainingBytes = len - i;
  23. if (!isArray) {
  24. chr1 = input.charCodeAt(i++);
  25. chr2 = i < len ? input.charCodeAt(i++) : 0;
  26. chr3 = i < len ? input.charCodeAt(i++) : 0;
  27. } else {
  28. chr1 = input[i++];
  29. chr2 = i < len ? input[i++] : 0;
  30. chr3 = i < len ? input[i++] : 0;
  31. }
  32. enc1 = chr1 >> 2;
  33. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  34. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  35. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  36. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  37. }
  38. return output.join("");
  39. };
  40. // public method for decoding
  41. exports.decode = function(input) {
  42. var chr1, chr2, chr3;
  43. var enc1, enc2, enc3, enc4;
  44. var i = 0, resultIndex = 0;
  45. var dataUrlPrefix = "data:";
  46. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  47. // This is a common error: people give a data url
  48. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  49. // wonders why things don't work.
  50. // We can detect that the string input looks like a data url but we
  51. // *can't* be sure it is one: removing everything up to the comma would
  52. // be too dangerous.
  53. throw new Error("Invalid base64 input, it looks like a data url.");
  54. }
  55. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  56. var totalLength = input.length * 3 / 4;
  57. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  58. totalLength--;
  59. }
  60. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  61. totalLength--;
  62. }
  63. if (totalLength % 1 !== 0) {
  64. // totalLength is not an integer, the length does not match a valid
  65. // base64 content. That can happen if:
  66. // - the input is not a base64 content
  67. // - the input is *almost* a base64 content, with a extra chars at the
  68. // beginning or at the end
  69. // - the input uses a base64 variant (base64url for example)
  70. throw new Error("Invalid base64 input, bad content length.");
  71. }
  72. var output;
  73. if (support.uint8array) {
  74. output = new Uint8Array(totalLength|0);
  75. } else {
  76. output = new Array(totalLength|0);
  77. }
  78. while (i < input.length) {
  79. enc1 = _keyStr.indexOf(input.charAt(i++));
  80. enc2 = _keyStr.indexOf(input.charAt(i++));
  81. enc3 = _keyStr.indexOf(input.charAt(i++));
  82. enc4 = _keyStr.indexOf(input.charAt(i++));
  83. chr1 = (enc1 << 2) | (enc2 >> 4);
  84. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  85. chr3 = ((enc3 & 3) << 6) | enc4;
  86. output[resultIndex++] = chr1;
  87. if (enc3 !== 64) {
  88. output[resultIndex++] = chr2;
  89. }
  90. if (enc4 !== 64) {
  91. output[resultIndex++] = chr3;
  92. }
  93. }
  94. return output;
  95. };
  96. },{"./support":30,"./utils":32}],2:[function(require,module,exports){
  97. 'use strict';
  98. var external = require("./external");
  99. var DataWorker = require('./stream/DataWorker');
  100. var DataLengthProbe = require('./stream/DataLengthProbe');
  101. var Crc32Probe = require('./stream/Crc32Probe');
  102. var DataLengthProbe = require('./stream/DataLengthProbe');
  103. /**
  104. * Represent a compressed object, with everything needed to decompress it.
  105. * @constructor
  106. * @param {number} compressedSize the size of the data compressed.
  107. * @param {number} uncompressedSize the size of the data after decompression.
  108. * @param {number} crc32 the crc32 of the decompressed file.
  109. * @param {object} compression the type of compression, see lib/compressions.js.
  110. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  111. */
  112. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  113. this.compressedSize = compressedSize;
  114. this.uncompressedSize = uncompressedSize;
  115. this.crc32 = crc32;
  116. this.compression = compression;
  117. this.compressedContent = data;
  118. }
  119. CompressedObject.prototype = {
  120. /**
  121. * Create a worker to get the uncompressed content.
  122. * @return {GenericWorker} the worker.
  123. */
  124. getContentWorker : function () {
  125. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  126. .pipe(this.compression.uncompressWorker())
  127. .pipe(new DataLengthProbe("data_length"));
  128. var that = this;
  129. worker.on("end", function () {
  130. if(this.streamInfo['data_length'] !== that.uncompressedSize) {
  131. throw new Error("Bug : uncompressed data size mismatch");
  132. }
  133. });
  134. return worker;
  135. },
  136. /**
  137. * Create a worker to get the compressed content.
  138. * @return {GenericWorker} the worker.
  139. */
  140. getCompressedWorker : function () {
  141. return new DataWorker(external.Promise.resolve(this.compressedContent))
  142. .withStreamInfo("compressedSize", this.compressedSize)
  143. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  144. .withStreamInfo("crc32", this.crc32)
  145. .withStreamInfo("compression", this.compression)
  146. ;
  147. }
  148. };
  149. /**
  150. * Chain the given worker with other workers to compress the content with the
  151. * given compresion.
  152. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  153. * @param {Object} compression the compression object.
  154. * @param {Object} compressionOptions the options to use when compressing.
  155. * @return {GenericWorker} the new worker compressing the content.
  156. */
  157. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  158. return uncompressedWorker
  159. .pipe(new Crc32Probe())
  160. .pipe(new DataLengthProbe("uncompressedSize"))
  161. .pipe(compression.compressWorker(compressionOptions))
  162. .pipe(new DataLengthProbe("compressedSize"))
  163. .withStreamInfo("compression", compression);
  164. };
  165. module.exports = CompressedObject;
  166. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  167. 'use strict';
  168. var GenericWorker = require("./stream/GenericWorker");
  169. exports.STORE = {
  170. magic: "\x00\x00",
  171. compressWorker : function (compressionOptions) {
  172. return new GenericWorker("STORE compression");
  173. },
  174. uncompressWorker : function () {
  175. return new GenericWorker("STORE decompression");
  176. }
  177. };
  178. exports.DEFLATE = require('./flate');
  179. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  180. 'use strict';
  181. var utils = require('./utils');
  182. /**
  183. * The following functions come from pako, from pako/lib/zlib/crc32.js
  184. * released under the MIT license, see pako https://github.com/nodeca/pako/
  185. */
  186. // Use ordinary array, since untyped makes no boost here
  187. function makeTable() {
  188. var c, table = [];
  189. for(var n =0; n < 256; n++){
  190. c = n;
  191. for(var k =0; k < 8; k++){
  192. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  193. }
  194. table[n] = c;
  195. }
  196. return table;
  197. }
  198. // Create table on load. Just 255 signed longs. Not a problem.
  199. var crcTable = makeTable();
  200. function crc32(crc, buf, len, pos) {
  201. var t = crcTable, end = pos + len;
  202. crc = crc ^ (-1);
  203. for (var i = pos; i < end; i++ ) {
  204. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  205. }
  206. return (crc ^ (-1)); // >>> 0;
  207. }
  208. // That's all for the pako functions.
  209. /**
  210. * Compute the crc32 of a string.
  211. * This is almost the same as the function crc32, but for strings. Using the
  212. * same function for the two use cases leads to horrible performances.
  213. * @param {Number} crc the starting value of the crc.
  214. * @param {String} str the string to use.
  215. * @param {Number} len the length of the string.
  216. * @param {Number} pos the starting position for the crc32 computation.
  217. * @return {Number} the computed crc32.
  218. */
  219. function crc32str(crc, str, len, pos) {
  220. var t = crcTable, end = pos + len;
  221. crc = crc ^ (-1);
  222. for (var i = pos; i < end; i++ ) {
  223. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  224. }
  225. return (crc ^ (-1)); // >>> 0;
  226. }
  227. module.exports = function crc32wrapper(input, crc) {
  228. if (typeof input === "undefined" || !input.length) {
  229. return 0;
  230. }
  231. var isArray = utils.getTypeOf(input) !== "string";
  232. if(isArray) {
  233. return crc32(crc|0, input, input.length, 0);
  234. } else {
  235. return crc32str(crc|0, input, input.length, 0);
  236. }
  237. };
  238. },{"./utils":32}],5:[function(require,module,exports){
  239. 'use strict';
  240. exports.base64 = false;
  241. exports.binary = false;
  242. exports.dir = false;
  243. exports.createFolders = true;
  244. exports.date = null;
  245. exports.compression = null;
  246. exports.compressionOptions = null;
  247. exports.comment = null;
  248. exports.unixPermissions = null;
  249. exports.dosPermissions = null;
  250. },{}],6:[function(require,module,exports){
  251. /* global Promise */
  252. 'use strict';
  253. // load the global object first:
  254. // - it should be better integrated in the system (unhandledRejection in node)
  255. // - the environment may have a custom Promise implementation (see zone.js)
  256. var ES6Promise = null;
  257. if (typeof Promise !== "undefined") {
  258. ES6Promise = Promise;
  259. } else {
  260. ES6Promise = require("lie");
  261. }
  262. /**
  263. * Let the user use/change some implementations.
  264. */
  265. module.exports = {
  266. Promise: ES6Promise
  267. };
  268. },{"lie":37}],7:[function(require,module,exports){
  269. 'use strict';
  270. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  271. var pako = require("pako");
  272. var utils = require("./utils");
  273. var GenericWorker = require("./stream/GenericWorker");
  274. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  275. exports.magic = "\x08\x00";
  276. /**
  277. * Create a worker that uses pako to inflate/deflate.
  278. * @constructor
  279. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  280. * @param {Object} options the options to use when (de)compressing.
  281. */
  282. function FlateWorker(action, options) {
  283. GenericWorker.call(this, "FlateWorker/" + action);
  284. this._pako = null;
  285. this._pakoAction = action;
  286. this._pakoOptions = options;
  287. // the `meta` object from the last chunk received
  288. // this allow this worker to pass around metadata
  289. this.meta = {};
  290. }
  291. utils.inherits(FlateWorker, GenericWorker);
  292. /**
  293. * @see GenericWorker.processChunk
  294. */
  295. FlateWorker.prototype.processChunk = function (chunk) {
  296. this.meta = chunk.meta;
  297. if (this._pako === null) {
  298. this._createPako();
  299. }
  300. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  301. };
  302. /**
  303. * @see GenericWorker.flush
  304. */
  305. FlateWorker.prototype.flush = function () {
  306. GenericWorker.prototype.flush.call(this);
  307. if (this._pako === null) {
  308. this._createPako();
  309. }
  310. this._pako.push([], true);
  311. };
  312. /**
  313. * @see GenericWorker.cleanUp
  314. */
  315. FlateWorker.prototype.cleanUp = function () {
  316. GenericWorker.prototype.cleanUp.call(this);
  317. this._pako = null;
  318. };
  319. /**
  320. * Create the _pako object.
  321. * TODO: lazy-loading this object isn't the best solution but it's the
  322. * quickest. The best solution is to lazy-load the worker list. See also the
  323. * issue #446.
  324. */
  325. FlateWorker.prototype._createPako = function () {
  326. this._pako = new pako[this._pakoAction]({
  327. raw: true,
  328. level: this._pakoOptions.level || -1 // default compression
  329. });
  330. var self = this;
  331. this._pako.onData = function(data) {
  332. self.push({
  333. data : data,
  334. meta : self.meta
  335. });
  336. };
  337. };
  338. exports.compressWorker = function (compressionOptions) {
  339. return new FlateWorker("Deflate", compressionOptions);
  340. };
  341. exports.uncompressWorker = function () {
  342. return new FlateWorker("Inflate", {});
  343. };
  344. },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
  345. 'use strict';
  346. var utils = require('../utils');
  347. var GenericWorker = require('../stream/GenericWorker');
  348. var utf8 = require('../utf8');
  349. var crc32 = require('../crc32');
  350. var signature = require('../signature');
  351. /**
  352. * Transform an integer into a string in hexadecimal.
  353. * @private
  354. * @param {number} dec the number to convert.
  355. * @param {number} bytes the number of bytes to generate.
  356. * @returns {string} the result.
  357. */
  358. var decToHex = function(dec, bytes) {
  359. var hex = "", i;
  360. for (i = 0; i < bytes; i++) {
  361. hex += String.fromCharCode(dec & 0xff);
  362. dec = dec >>> 8;
  363. }
  364. return hex;
  365. };
  366. /**
  367. * Generate the UNIX part of the external file attributes.
  368. * @param {Object} unixPermissions the unix permissions or null.
  369. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  370. * @return {Number} a 32 bit integer.
  371. *
  372. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  373. *
  374. * TTTTsstrwxrwxrwx0000000000ADVSHR
  375. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  376. * ^^^_________________________ setuid, setgid, sticky
  377. * ^^^^^^^^^________________ permissions
  378. * ^^^^^^^^^^______ not used ?
  379. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  380. */
  381. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  382. var result = unixPermissions;
  383. if (!unixPermissions) {
  384. // I can't use octal values in strict mode, hence the hexa.
  385. // 040775 => 0x41fd
  386. // 0100664 => 0x81b4
  387. result = isDir ? 0x41fd : 0x81b4;
  388. }
  389. return (result & 0xFFFF) << 16;
  390. };
  391. /**
  392. * Generate the DOS part of the external file attributes.
  393. * @param {Object} dosPermissions the dos permissions or null.
  394. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  395. * @return {Number} a 32 bit integer.
  396. *
  397. * Bit 0 Read-Only
  398. * Bit 1 Hidden
  399. * Bit 2 System
  400. * Bit 3 Volume Label
  401. * Bit 4 Directory
  402. * Bit 5 Archive
  403. */
  404. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  405. // the dir flag is already set for compatibility
  406. return (dosPermissions || 0) & 0x3F;
  407. };
  408. /**
  409. * Generate the various parts used in the construction of the final zip file.
  410. * @param {Object} streamInfo the hash with informations about the compressed file.
  411. * @param {Boolean} streamedContent is the content streamed ?
  412. * @param {Boolean} streamingEnded is the stream finished ?
  413. * @param {number} offset the current offset from the start of the zip file.
  414. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  415. * @param {Function} encodeFileName the function to encode the file name / comment.
  416. * @return {Object} the zip parts.
  417. */
  418. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  419. var file = streamInfo['file'],
  420. compression = streamInfo['compression'],
  421. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  422. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  423. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  424. comment = file.comment,
  425. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  426. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  427. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  428. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  429. dosTime,
  430. dosDate,
  431. extraFields = "",
  432. unicodePathExtraField = "",
  433. unicodeCommentExtraField = "",
  434. dir = file.dir,
  435. date = file.date;
  436. var dataInfo = {
  437. crc32 : 0,
  438. compressedSize : 0,
  439. uncompressedSize : 0
  440. };
  441. // if the content is streamed, the sizes/crc32 are only available AFTER
  442. // the end of the stream.
  443. if (!streamedContent || streamingEnded) {
  444. dataInfo.crc32 = streamInfo['crc32'];
  445. dataInfo.compressedSize = streamInfo['compressedSize'];
  446. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  447. }
  448. var bitflag = 0;
  449. if (streamedContent) {
  450. // Bit 3: the sizes/crc32 are set to zero in the local header.
  451. // The correct values are put in the data descriptor immediately
  452. // following the compressed data.
  453. bitflag |= 0x0008;
  454. }
  455. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  456. // Bit 11: Language encoding flag (EFS).
  457. bitflag |= 0x0800;
  458. }
  459. var extFileAttr = 0;
  460. var versionMadeBy = 0;
  461. if (dir) {
  462. // dos or unix, we set the dos dir flag
  463. extFileAttr |= 0x00010;
  464. }
  465. if(platform === "UNIX") {
  466. versionMadeBy = 0x031E; // UNIX, version 3.0
  467. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  468. } else { // DOS or other, fallback to DOS
  469. versionMadeBy = 0x0014; // DOS, version 2.0
  470. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  471. }
  472. // date
  473. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  474. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  475. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  476. dosTime = date.getUTCHours();
  477. dosTime = dosTime << 6;
  478. dosTime = dosTime | date.getUTCMinutes();
  479. dosTime = dosTime << 5;
  480. dosTime = dosTime | date.getUTCSeconds() / 2;
  481. dosDate = date.getUTCFullYear() - 1980;
  482. dosDate = dosDate << 4;
  483. dosDate = dosDate | (date.getUTCMonth() + 1);
  484. dosDate = dosDate << 5;
  485. dosDate = dosDate | date.getUTCDate();
  486. if (useUTF8ForFileName) {
  487. // set the unicode path extra field. unzip needs at least one extra
  488. // field to correctly handle unicode path, so using the path is as good
  489. // as any other information. This could improve the situation with
  490. // other archive managers too.
  491. // This field is usually used without the utf8 flag, with a non
  492. // unicode path in the header (winrar, winzip). This helps (a bit)
  493. // with the messy Windows' default compressed folders feature but
  494. // breaks on p7zip which doesn't seek the unicode path extra field.
  495. // So for now, UTF-8 everywhere !
  496. unicodePathExtraField =
  497. // Version
  498. decToHex(1, 1) +
  499. // NameCRC32
  500. decToHex(crc32(encodedFileName), 4) +
  501. // UnicodeName
  502. utfEncodedFileName;
  503. extraFields +=
  504. // Info-ZIP Unicode Path Extra Field
  505. "\x75\x70" +
  506. // size
  507. decToHex(unicodePathExtraField.length, 2) +
  508. // content
  509. unicodePathExtraField;
  510. }
  511. if(useUTF8ForComment) {
  512. unicodeCommentExtraField =
  513. // Version
  514. decToHex(1, 1) +
  515. // CommentCRC32
  516. decToHex(crc32(encodedComment), 4) +
  517. // UnicodeName
  518. utfEncodedComment;
  519. extraFields +=
  520. // Info-ZIP Unicode Path Extra Field
  521. "\x75\x63" +
  522. // size
  523. decToHex(unicodeCommentExtraField.length, 2) +
  524. // content
  525. unicodeCommentExtraField;
  526. }
  527. var header = "";
  528. // version needed to extract
  529. header += "\x0A\x00";
  530. // general purpose bit flag
  531. header += decToHex(bitflag, 2);
  532. // compression method
  533. header += compression.magic;
  534. // last mod file time
  535. header += decToHex(dosTime, 2);
  536. // last mod file date
  537. header += decToHex(dosDate, 2);
  538. // crc-32
  539. header += decToHex(dataInfo.crc32, 4);
  540. // compressed size
  541. header += decToHex(dataInfo.compressedSize, 4);
  542. // uncompressed size
  543. header += decToHex(dataInfo.uncompressedSize, 4);
  544. // file name length
  545. header += decToHex(encodedFileName.length, 2);
  546. // extra field length
  547. header += decToHex(extraFields.length, 2);
  548. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  549. var dirRecord = signature.CENTRAL_FILE_HEADER +
  550. // version made by (00: DOS)
  551. decToHex(versionMadeBy, 2) +
  552. // file header (common to file and central directory)
  553. header +
  554. // file comment length
  555. decToHex(encodedComment.length, 2) +
  556. // disk number start
  557. "\x00\x00" +
  558. // internal file attributes TODO
  559. "\x00\x00" +
  560. // external file attributes
  561. decToHex(extFileAttr, 4) +
  562. // relative offset of local header
  563. decToHex(offset, 4) +
  564. // file name
  565. encodedFileName +
  566. // extra field
  567. extraFields +
  568. // file comment
  569. encodedComment;
  570. return {
  571. fileRecord: fileRecord,
  572. dirRecord: dirRecord
  573. };
  574. };
  575. /**
  576. * Generate the EOCD record.
  577. * @param {Number} entriesCount the number of entries in the zip file.
  578. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  579. * @param {Number} localDirLength the length (in bytes) of the local dir.
  580. * @param {String} comment the zip file comment as a binary string.
  581. * @param {Function} encodeFileName the function to encode the comment.
  582. * @return {String} the EOCD record.
  583. */
  584. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  585. var dirEnd = "";
  586. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  587. // end of central dir signature
  588. dirEnd = signature.CENTRAL_DIRECTORY_END +
  589. // number of this disk
  590. "\x00\x00" +
  591. // number of the disk with the start of the central directory
  592. "\x00\x00" +
  593. // total number of entries in the central directory on this disk
  594. decToHex(entriesCount, 2) +
  595. // total number of entries in the central directory
  596. decToHex(entriesCount, 2) +
  597. // size of the central directory 4 bytes
  598. decToHex(centralDirLength, 4) +
  599. // offset of start of central directory with respect to the starting disk number
  600. decToHex(localDirLength, 4) +
  601. // .ZIP file comment length
  602. decToHex(encodedComment.length, 2) +
  603. // .ZIP file comment
  604. encodedComment;
  605. return dirEnd;
  606. };
  607. /**
  608. * Generate data descriptors for a file entry.
  609. * @param {Object} streamInfo the hash generated by a worker, containing informations
  610. * on the file entry.
  611. * @return {String} the data descriptors.
  612. */
  613. var generateDataDescriptors = function (streamInfo) {
  614. var descriptor = "";
  615. descriptor = signature.DATA_DESCRIPTOR +
  616. // crc-32 4 bytes
  617. decToHex(streamInfo['crc32'], 4) +
  618. // compressed size 4 bytes
  619. decToHex(streamInfo['compressedSize'], 4) +
  620. // uncompressed size 4 bytes
  621. decToHex(streamInfo['uncompressedSize'], 4);
  622. return descriptor;
  623. };
  624. /**
  625. * A worker to concatenate other workers to create a zip file.
  626. * @param {Boolean} streamFiles `true` to stream the content of the files,
  627. * `false` to accumulate it.
  628. * @param {String} comment the comment to use.
  629. * @param {String} platform the platform to use, "UNIX" or "DOS".
  630. * @param {Function} encodeFileName the function to encode file names and comments.
  631. */
  632. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  633. GenericWorker.call(this, "ZipFileWorker");
  634. // The number of bytes written so far. This doesn't count accumulated chunks.
  635. this.bytesWritten = 0;
  636. // The comment of the zip file
  637. this.zipComment = comment;
  638. // The platform "generating" the zip file.
  639. this.zipPlatform = platform;
  640. // the function to encode file names and comments.
  641. this.encodeFileName = encodeFileName;
  642. // Should we stream the content of the files ?
  643. this.streamFiles = streamFiles;
  644. // If `streamFiles` is false, we will need to accumulate the content of the
  645. // files to calculate sizes / crc32 (and write them *before* the content).
  646. // This boolean indicates if we are accumulating chunks (it will change a lot
  647. // during the lifetime of this worker).
  648. this.accumulate = false;
  649. // The buffer receiving chunks when accumulating content.
  650. this.contentBuffer = [];
  651. // The list of generated directory records.
  652. this.dirRecords = [];
  653. // The offset (in bytes) from the beginning of the zip file for the current source.
  654. this.currentSourceOffset = 0;
  655. // The total number of entries in this zip file.
  656. this.entriesCount = 0;
  657. // the name of the file currently being added, null when handling the end of the zip file.
  658. // Used for the emited metadata.
  659. this.currentFile = null;
  660. this._sources = [];
  661. }
  662. utils.inherits(ZipFileWorker, GenericWorker);
  663. /**
  664. * @see GenericWorker.push
  665. */
  666. ZipFileWorker.prototype.push = function (chunk) {
  667. var currentFilePercent = chunk.meta.percent || 0;
  668. var entriesCount = this.entriesCount;
  669. var remainingFiles = this._sources.length;
  670. if(this.accumulate) {
  671. this.contentBuffer.push(chunk);
  672. } else {
  673. this.bytesWritten += chunk.data.length;
  674. GenericWorker.prototype.push.call(this, {
  675. data : chunk.data,
  676. meta : {
  677. currentFile : this.currentFile,
  678. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  679. }
  680. });
  681. }
  682. };
  683. /**
  684. * The worker started a new source (an other worker).
  685. * @param {Object} streamInfo the streamInfo object from the new source.
  686. */
  687. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  688. this.currentSourceOffset = this.bytesWritten;
  689. this.currentFile = streamInfo['file'].name;
  690. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  691. // don't stream folders (because they don't have any content)
  692. if(streamedContent) {
  693. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  694. this.push({
  695. data : record.fileRecord,
  696. meta : {percent:0}
  697. });
  698. } else {
  699. // we need to wait for the whole file before pushing anything
  700. this.accumulate = true;
  701. }
  702. };
  703. /**
  704. * The worker finished a source (an other worker).
  705. * @param {Object} streamInfo the streamInfo object from the finished source.
  706. */
  707. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  708. this.accumulate = false;
  709. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  710. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  711. this.dirRecords.push(record.dirRecord);
  712. if(streamedContent) {
  713. // after the streamed file, we put data descriptors
  714. this.push({
  715. data : generateDataDescriptors(streamInfo),
  716. meta : {percent:100}
  717. });
  718. } else {
  719. // the content wasn't streamed, we need to push everything now
  720. // first the file record, then the content
  721. this.push({
  722. data : record.fileRecord,
  723. meta : {percent:0}
  724. });
  725. while(this.contentBuffer.length) {
  726. this.push(this.contentBuffer.shift());
  727. }
  728. }
  729. this.currentFile = null;
  730. };
  731. /**
  732. * @see GenericWorker.flush
  733. */
  734. ZipFileWorker.prototype.flush = function () {
  735. var localDirLength = this.bytesWritten;
  736. for(var i = 0; i < this.dirRecords.length; i++) {
  737. this.push({
  738. data : this.dirRecords[i],
  739. meta : {percent:100}
  740. });
  741. }
  742. var centralDirLength = this.bytesWritten - localDirLength;
  743. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  744. this.push({
  745. data : dirEnd,
  746. meta : {percent:100}
  747. });
  748. };
  749. /**
  750. * Prepare the next source to be read.
  751. */
  752. ZipFileWorker.prototype.prepareNextSource = function () {
  753. this.previous = this._sources.shift();
  754. this.openedSource(this.previous.streamInfo);
  755. if (this.isPaused) {
  756. this.previous.pause();
  757. } else {
  758. this.previous.resume();
  759. }
  760. };
  761. /**
  762. * @see GenericWorker.registerPrevious
  763. */
  764. ZipFileWorker.prototype.registerPrevious = function (previous) {
  765. this._sources.push(previous);
  766. var self = this;
  767. previous.on('data', function (chunk) {
  768. self.processChunk(chunk);
  769. });
  770. previous.on('end', function () {
  771. self.closedSource(self.previous.streamInfo);
  772. if(self._sources.length) {
  773. self.prepareNextSource();
  774. } else {
  775. self.end();
  776. }
  777. });
  778. previous.on('error', function (e) {
  779. self.error(e);
  780. });
  781. return this;
  782. };
  783. /**
  784. * @see GenericWorker.resume
  785. */
  786. ZipFileWorker.prototype.resume = function () {
  787. if(!GenericWorker.prototype.resume.call(this)) {
  788. return false;
  789. }
  790. if (!this.previous && this._sources.length) {
  791. this.prepareNextSource();
  792. return true;
  793. }
  794. if (!this.previous && !this._sources.length && !this.generatedError) {
  795. this.end();
  796. return true;
  797. }
  798. };
  799. /**
  800. * @see GenericWorker.error
  801. */
  802. ZipFileWorker.prototype.error = function (e) {
  803. var sources = this._sources;
  804. if(!GenericWorker.prototype.error.call(this, e)) {
  805. return false;
  806. }
  807. for(var i = 0; i < sources.length; i++) {
  808. try {
  809. sources[i].error(e);
  810. } catch(e) {
  811. // the `error` exploded, nothing to do
  812. }
  813. }
  814. return true;
  815. };
  816. /**
  817. * @see GenericWorker.lock
  818. */
  819. ZipFileWorker.prototype.lock = function () {
  820. GenericWorker.prototype.lock.call(this);
  821. var sources = this._sources;
  822. for(var i = 0; i < sources.length; i++) {
  823. sources[i].lock();
  824. }
  825. };
  826. module.exports = ZipFileWorker;
  827. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  828. 'use strict';
  829. var compressions = require('../compressions');
  830. var ZipFileWorker = require('./ZipFileWorker');
  831. /**
  832. * Find the compression to use.
  833. * @param {String} fileCompression the compression defined at the file level, if any.
  834. * @param {String} zipCompression the compression defined at the load() level.
  835. * @return {Object} the compression object to use.
  836. */
  837. var getCompression = function (fileCompression, zipCompression) {
  838. var compressionName = fileCompression || zipCompression;
  839. var compression = compressions[compressionName];
  840. if (!compression) {
  841. throw new Error(compressionName + " is not a valid compression method !");
  842. }
  843. return compression;
  844. };
  845. /**
  846. * Create a worker to generate a zip file.
  847. * @param {JSZip} zip the JSZip instance at the right root level.
  848. * @param {Object} options to generate the zip file.
  849. * @param {String} comment the comment to use.
  850. */
  851. exports.generateWorker = function (zip, options, comment) {
  852. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  853. var entriesCount = 0;
  854. try {
  855. zip.forEach(function (relativePath, file) {
  856. entriesCount++;
  857. var compression = getCompression(file.options.compression, options.compression);
  858. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  859. var dir = file.dir, date = file.date;
  860. file._compressWorker(compression, compressionOptions)
  861. .withStreamInfo("file", {
  862. name : relativePath,
  863. dir : dir,
  864. date : date,
  865. comment : file.comment || "",
  866. unixPermissions : file.unixPermissions,
  867. dosPermissions : file.dosPermissions
  868. })
  869. .pipe(zipFileWorker);
  870. });
  871. zipFileWorker.entriesCount = entriesCount;
  872. } catch (e) {
  873. zipFileWorker.error(e);
  874. }
  875. return zipFileWorker;
  876. };
  877. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  878. 'use strict';
  879. /**
  880. * Representation a of zip file in js
  881. * @constructor
  882. */
  883. function JSZip() {
  884. // if this constructor is used without `new`, it adds `new` before itself:
  885. if(!(this instanceof JSZip)) {
  886. return new JSZip();
  887. }
  888. if(arguments.length) {
  889. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  890. }
  891. // object containing the files :
  892. // {
  893. // "folder/" : {...},
  894. // "folder/data.txt" : {...}
  895. // }
  896. this.files = {};
  897. this.comment = null;
  898. // Where we are in the hierarchy
  899. this.root = "";
  900. this.clone = function() {
  901. var newObj = new JSZip();
  902. for (var i in this) {
  903. if (typeof this[i] !== "function") {
  904. newObj[i] = this[i];
  905. }
  906. }
  907. return newObj;
  908. };
  909. }
  910. JSZip.prototype = require('./object');
  911. JSZip.prototype.loadAsync = require('./load');
  912. JSZip.support = require('./support');
  913. JSZip.defaults = require('./defaults');
  914. // TODO find a better way to handle this version,
  915. // a require('package.json').version doesn't work with webpack, see #327
  916. JSZip.version = "3.2.0";
  917. JSZip.loadAsync = function (content, options) {
  918. return new JSZip().loadAsync(content, options);
  919. };
  920. JSZip.external = require("./external");
  921. module.exports = JSZip;
  922. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  923. 'use strict';
  924. var utils = require('./utils');
  925. var external = require("./external");
  926. var utf8 = require('./utf8');
  927. var utils = require('./utils');
  928. var ZipEntries = require('./zipEntries');
  929. var Crc32Probe = require('./stream/Crc32Probe');
  930. var nodejsUtils = require("./nodejsUtils");
  931. /**
  932. * Check the CRC32 of an entry.
  933. * @param {ZipEntry} zipEntry the zip entry to check.
  934. * @return {Promise} the result.
  935. */
  936. function checkEntryCRC32(zipEntry) {
  937. return new external.Promise(function (resolve, reject) {
  938. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  939. worker.on("error", function (e) {
  940. reject(e);
  941. })
  942. .on("end", function () {
  943. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  944. reject(new Error("Corrupted zip : CRC32 mismatch"));
  945. } else {
  946. resolve();
  947. }
  948. })
  949. .resume();
  950. });
  951. }
  952. module.exports = function(data, options) {
  953. var zip = this;
  954. options = utils.extend(options || {}, {
  955. base64: false,
  956. checkCRC32: false,
  957. optimizedBinaryString: false,
  958. createFolders: false,
  959. decodeFileName: utf8.utf8decode
  960. });
  961. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  962. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  963. }
  964. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  965. .then(function(data) {
  966. var zipEntries = new ZipEntries(options);
  967. zipEntries.load(data);
  968. return zipEntries;
  969. }).then(function checkCRC32(zipEntries) {
  970. var promises = [external.Promise.resolve(zipEntries)];
  971. var files = zipEntries.files;
  972. if (options.checkCRC32) {
  973. for (var i = 0; i < files.length; i++) {
  974. promises.push(checkEntryCRC32(files[i]));
  975. }
  976. }
  977. return external.Promise.all(promises);
  978. }).then(function addFiles(results) {
  979. var zipEntries = results.shift();
  980. var files = zipEntries.files;
  981. for (var i = 0; i < files.length; i++) {
  982. var input = files[i];
  983. zip.file(input.fileNameStr, input.decompressed, {
  984. binary: true,
  985. optimizedBinaryString: true,
  986. date: input.date,
  987. dir: input.dir,
  988. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  989. unixPermissions : input.unixPermissions,
  990. dosPermissions : input.dosPermissions,
  991. createFolders: options.createFolders
  992. });
  993. }
  994. if (zipEntries.zipComment.length) {
  995. zip.comment = zipEntries.zipComment;
  996. }
  997. return zip;
  998. });
  999. };
  1000. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1001. "use strict";
  1002. var utils = require('../utils');
  1003. var GenericWorker = require('../stream/GenericWorker');
  1004. /**
  1005. * A worker that use a nodejs stream as source.
  1006. * @constructor
  1007. * @param {String} filename the name of the file entry for this stream.
  1008. * @param {Readable} stream the nodejs stream.
  1009. */
  1010. function NodejsStreamInputAdapter(filename, stream) {
  1011. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1012. this._upstreamEnded = false;
  1013. this._bindStream(stream);
  1014. }
  1015. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1016. /**
  1017. * Prepare the stream and bind the callbacks on it.
  1018. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1019. * @param {Stream} stream the nodejs stream to use.
  1020. */
  1021. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1022. var self = this;
  1023. this._stream = stream;
  1024. stream.pause();
  1025. stream
  1026. .on("data", function (chunk) {
  1027. self.push({
  1028. data: chunk,
  1029. meta : {
  1030. percent : 0
  1031. }
  1032. });
  1033. })
  1034. .on("error", function (e) {
  1035. if(self.isPaused) {
  1036. this.generatedError = e;
  1037. } else {
  1038. self.error(e);
  1039. }
  1040. })
  1041. .on("end", function () {
  1042. if(self.isPaused) {
  1043. self._upstreamEnded = true;
  1044. } else {
  1045. self.end();
  1046. }
  1047. });
  1048. };
  1049. NodejsStreamInputAdapter.prototype.pause = function () {
  1050. if(!GenericWorker.prototype.pause.call(this)) {
  1051. return false;
  1052. }
  1053. this._stream.pause();
  1054. return true;
  1055. };
  1056. NodejsStreamInputAdapter.prototype.resume = function () {
  1057. if(!GenericWorker.prototype.resume.call(this)) {
  1058. return false;
  1059. }
  1060. if(this._upstreamEnded) {
  1061. this.end();
  1062. } else {
  1063. this._stream.resume();
  1064. }
  1065. return true;
  1066. };
  1067. module.exports = NodejsStreamInputAdapter;
  1068. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1069. 'use strict';
  1070. var Readable = require('readable-stream').Readable;
  1071. var utils = require('../utils');
  1072. utils.inherits(NodejsStreamOutputAdapter, Readable);
  1073. /**
  1074. * A nodejs stream using a worker as source.
  1075. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1076. * @constructor
  1077. * @param {StreamHelper} helper the helper wrapping the worker
  1078. * @param {Object} options the nodejs stream options
  1079. * @param {Function} updateCb the update callback.
  1080. */
  1081. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1082. Readable.call(this, options);
  1083. this._helper = helper;
  1084. var self = this;
  1085. helper.on("data", function (data, meta) {
  1086. if (!self.push(data)) {
  1087. self._helper.pause();
  1088. }
  1089. if(updateCb) {
  1090. updateCb(meta);
  1091. }
  1092. })
  1093. .on("error", function(e) {
  1094. self.emit('error', e);
  1095. })
  1096. .on("end", function () {
  1097. self.push(null);
  1098. });
  1099. }
  1100. NodejsStreamOutputAdapter.prototype._read = function() {
  1101. this._helper.resume();
  1102. };
  1103. module.exports = NodejsStreamOutputAdapter;
  1104. },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
  1105. 'use strict';
  1106. module.exports = {
  1107. /**
  1108. * True if this is running in Nodejs, will be undefined in a browser.
  1109. * In a browser, browserify won't include this file and the whole module
  1110. * will be resolved an empty object.
  1111. */
  1112. isNode : typeof Buffer !== "undefined",
  1113. /**
  1114. * Create a new nodejs Buffer from an existing content.
  1115. * @param {Object} data the data to pass to the constructor.
  1116. * @param {String} encoding the encoding to use.
  1117. * @return {Buffer} a new Buffer.
  1118. */
  1119. newBufferFrom: function(data, encoding) {
  1120. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  1121. return Buffer.from(data, encoding);
  1122. } else {
  1123. if (typeof data === "number") {
  1124. // Safeguard for old Node.js versions. On newer versions,
  1125. // Buffer.from(number) / Buffer(number, encoding) already throw.
  1126. throw new Error("The \"data\" argument must not be a number");
  1127. }
  1128. return new Buffer(data, encoding);
  1129. }
  1130. },
  1131. /**
  1132. * Create a new nodejs Buffer with the specified size.
  1133. * @param {Integer} size the size of the buffer.
  1134. * @return {Buffer} a new Buffer.
  1135. */
  1136. allocBuffer: function (size) {
  1137. if (Buffer.alloc) {
  1138. return Buffer.alloc(size);
  1139. } else {
  1140. var buf = new Buffer(size);
  1141. buf.fill(0);
  1142. return buf;
  1143. }
  1144. },
  1145. /**
  1146. * Find out if an object is a Buffer.
  1147. * @param {Object} b the object to test.
  1148. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1149. */
  1150. isBuffer : function(b){
  1151. return Buffer.isBuffer(b);
  1152. },
  1153. isStream : function (obj) {
  1154. return obj &&
  1155. typeof obj.on === "function" &&
  1156. typeof obj.pause === "function" &&
  1157. typeof obj.resume === "function";
  1158. }
  1159. };
  1160. },{}],15:[function(require,module,exports){
  1161. 'use strict';
  1162. var utf8 = require('./utf8');
  1163. var utils = require('./utils');
  1164. var GenericWorker = require('./stream/GenericWorker');
  1165. var StreamHelper = require('./stream/StreamHelper');
  1166. var defaults = require('./defaults');
  1167. var CompressedObject = require('./compressedObject');
  1168. var ZipObject = require('./zipObject');
  1169. var generate = require("./generate");
  1170. var nodejsUtils = require("./nodejsUtils");
  1171. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1172. /**
  1173. * Add a file in the current folder.
  1174. * @private
  1175. * @param {string} name the name of the file
  1176. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1177. * @param {Object} originalOptions the options of the file
  1178. * @return {Object} the new file.
  1179. */
  1180. var fileAdd = function(name, data, originalOptions) {
  1181. // be sure sub folders exist
  1182. var dataType = utils.getTypeOf(data),
  1183. parent;
  1184. /*
  1185. * Correct options.
  1186. */
  1187. var o = utils.extend(originalOptions || {}, defaults);
  1188. o.date = o.date || new Date();
  1189. if (o.compression !== null) {
  1190. o.compression = o.compression.toUpperCase();
  1191. }
  1192. if (typeof o.unixPermissions === "string") {
  1193. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1194. }
  1195. // UNX_IFDIR 0040000 see zipinfo.c
  1196. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1197. o.dir = true;
  1198. }
  1199. // Bit 4 Directory
  1200. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1201. o.dir = true;
  1202. }
  1203. if (o.dir) {
  1204. name = forceTrailingSlash(name);
  1205. }
  1206. if (o.createFolders && (parent = parentFolder(name))) {
  1207. folderAdd.call(this, parent, true);
  1208. }
  1209. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1210. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1211. o.binary = !isUnicodeString;
  1212. }
  1213. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1214. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1215. o.base64 = false;
  1216. o.binary = true;
  1217. data = "";
  1218. o.compression = "STORE";
  1219. dataType = "string";
  1220. }
  1221. /*
  1222. * Convert content to fit.
  1223. */
  1224. var zipObjectContent = null;
  1225. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1226. zipObjectContent = data;
  1227. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1228. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1229. } else {
  1230. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1231. }
  1232. var object = new ZipObject(name, zipObjectContent, o);
  1233. this.files[name] = object;
  1234. /*
  1235. TODO: we can't throw an exception because we have async promises
  1236. (we can have a promise of a Date() for example) but returning a
  1237. promise is useless because file(name, data) returns the JSZip
  1238. object for chaining. Should we break that to allow the user
  1239. to catch the error ?
  1240. return external.Promise.resolve(zipObjectContent)
  1241. .then(function () {
  1242. return object;
  1243. });
  1244. */
  1245. };
  1246. /**
  1247. * Find the parent folder of the path.
  1248. * @private
  1249. * @param {string} path the path to use
  1250. * @return {string} the parent folder, or ""
  1251. */
  1252. var parentFolder = function (path) {
  1253. if (path.slice(-1) === '/') {
  1254. path = path.substring(0, path.length - 1);
  1255. }
  1256. var lastSlash = path.lastIndexOf('/');
  1257. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1258. };
  1259. /**
  1260. * Returns the path with a slash at the end.
  1261. * @private
  1262. * @param {String} path the path to check.
  1263. * @return {String} the path with a trailing slash.
  1264. */
  1265. var forceTrailingSlash = function(path) {
  1266. // Check the name ends with a /
  1267. if (path.slice(-1) !== "/") {
  1268. path += "/"; // IE doesn't like substr(-1)
  1269. }
  1270. return path;
  1271. };
  1272. /**
  1273. * Add a (sub) folder in the current folder.
  1274. * @private
  1275. * @param {string} name the folder's name
  1276. * @param {boolean=} [createFolders] If true, automatically create sub
  1277. * folders. Defaults to false.
  1278. * @return {Object} the new folder.
  1279. */
  1280. var folderAdd = function(name, createFolders) {
  1281. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1282. name = forceTrailingSlash(name);
  1283. // Does this folder already exist?
  1284. if (!this.files[name]) {
  1285. fileAdd.call(this, name, null, {
  1286. dir: true,
  1287. createFolders: createFolders
  1288. });
  1289. }
  1290. return this.files[name];
  1291. };
  1292. /**
  1293. * Cross-window, cross-Node-context regular expression detection
  1294. * @param {Object} object Anything
  1295. * @return {Boolean} true if the object is a regular expression,
  1296. * false otherwise
  1297. */
  1298. function isRegExp(object) {
  1299. return Object.prototype.toString.call(object) === "[object RegExp]";
  1300. }
  1301. // return the actual prototype of JSZip
  1302. var out = {
  1303. /**
  1304. * @see loadAsync
  1305. */
  1306. load: function() {
  1307. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1308. },
  1309. /**
  1310. * Call a callback function for each entry at this folder level.
  1311. * @param {Function} cb the callback function:
  1312. * function (relativePath, file) {...}
  1313. * It takes 2 arguments : the relative path and the file.
  1314. */
  1315. forEach: function(cb) {
  1316. var filename, relativePath, file;
  1317. for (filename in this.files) {
  1318. if (!this.files.hasOwnProperty(filename)) {
  1319. continue;
  1320. }
  1321. file = this.files[filename];
  1322. relativePath = filename.slice(this.root.length, filename.length);
  1323. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1324. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1325. }
  1326. }
  1327. },
  1328. /**
  1329. * Filter nested files/folders with the specified function.
  1330. * @param {Function} search the predicate to use :
  1331. * function (relativePath, file) {...}
  1332. * It takes 2 arguments : the relative path and the file.
  1333. * @return {Array} An array of matching elements.
  1334. */
  1335. filter: function(search) {
  1336. var result = [];
  1337. this.forEach(function (relativePath, entry) {
  1338. if (search(relativePath, entry)) { // the file matches the function
  1339. result.push(entry);
  1340. }
  1341. });
  1342. return result;
  1343. },
  1344. /**
  1345. * Add a file to the zip file, or search a file.
  1346. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1347. * the name of the file to find (if no data) or a regex to match files.
  1348. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1349. * @param {Object} o File options
  1350. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1351. * a file (when searching by string) or an array of files (when searching by regex).
  1352. */
  1353. file: function(name, data, o) {
  1354. if (arguments.length === 1) {
  1355. if (isRegExp(name)) {
  1356. var regexp = name;
  1357. return this.filter(function(relativePath, file) {
  1358. return !file.dir && regexp.test(relativePath);
  1359. });
  1360. }
  1361. else { // text
  1362. var obj = this.files[this.root + name];
  1363. if (obj && !obj.dir) {
  1364. return obj;
  1365. } else {
  1366. return null;
  1367. }
  1368. }
  1369. }
  1370. else { // more than one argument : we have data !
  1371. name = this.root + name;
  1372. fileAdd.call(this, name, data, o);
  1373. }
  1374. return this;
  1375. },
  1376. /**
  1377. * Add a directory to the zip file, or search.
  1378. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1379. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1380. */
  1381. folder: function(arg) {
  1382. if (!arg) {
  1383. return this;
  1384. }
  1385. if (isRegExp(arg)) {
  1386. return this.filter(function(relativePath, file) {
  1387. return file.dir && arg.test(relativePath);
  1388. });
  1389. }
  1390. // else, name is a new folder
  1391. var name = this.root + arg;
  1392. var newFolder = folderAdd.call(this, name);
  1393. // Allow chaining by returning a new object with this folder as the root
  1394. var ret = this.clone();
  1395. ret.root = newFolder.name;
  1396. return ret;
  1397. },
  1398. /**
  1399. * Delete a file, or a directory and all sub-files, from the zip
  1400. * @param {string} name the name of the file to delete
  1401. * @return {JSZip} this JSZip object
  1402. */
  1403. remove: function(name) {
  1404. name = this.root + name;
  1405. var file = this.files[name];
  1406. if (!file) {
  1407. // Look for any folders
  1408. if (name.slice(-1) !== "/") {
  1409. name += "/";
  1410. }
  1411. file = this.files[name];
  1412. }
  1413. if (file && !file.dir) {
  1414. // file
  1415. delete this.files[name];
  1416. } else {
  1417. // maybe a folder, delete recursively
  1418. var kids = this.filter(function(relativePath, file) {
  1419. return file.name.slice(0, name.length) === name;
  1420. });
  1421. for (var i = 0; i < kids.length; i++) {
  1422. delete this.files[kids[i].name];
  1423. }
  1424. }
  1425. return this;
  1426. },
  1427. /**
  1428. * Generate the complete zip file
  1429. * @param {Object} options the options to generate the zip file :
  1430. * - compression, "STORE" by default.
  1431. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1432. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1433. */
  1434. generate: function(options) {
  1435. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1436. },
  1437. /**
  1438. * Generate the complete zip file as an internal stream.
  1439. * @param {Object} options the options to generate the zip file :
  1440. * - compression, "STORE" by default.
  1441. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1442. * @return {StreamHelper} the streamed zip file.
  1443. */
  1444. generateInternalStream: function(options) {
  1445. var worker, opts = {};
  1446. try {
  1447. opts = utils.extend(options || {}, {
  1448. streamFiles: false,
  1449. compression: "STORE",
  1450. compressionOptions : null,
  1451. type: "",
  1452. platform: "DOS",
  1453. comment: null,
  1454. mimeType: 'application/zip',
  1455. encodeFileName: utf8.utf8encode
  1456. });
  1457. opts.type = opts.type.toLowerCase();
  1458. opts.compression = opts.compression.toUpperCase();
  1459. // "binarystring" is prefered but the internals use "string".
  1460. if(opts.type === "binarystring") {
  1461. opts.type = "string";
  1462. }
  1463. if (!opts.type) {
  1464. throw new Error("No output type specified.");
  1465. }
  1466. utils.checkSupport(opts.type);
  1467. // accept nodejs `process.platform`
  1468. if(
  1469. opts.platform === 'darwin' ||
  1470. opts.platform === 'freebsd' ||
  1471. opts.platform === 'linux' ||
  1472. opts.platform === 'sunos'
  1473. ) {
  1474. opts.platform = "UNIX";
  1475. }
  1476. if (opts.platform === 'win32') {
  1477. opts.platform = "DOS";
  1478. }
  1479. var comment = opts.comment || this.comment || "";
  1480. worker = generate.generateWorker(this, opts, comment);
  1481. } catch (e) {
  1482. worker = new GenericWorker("error");
  1483. worker.error(e);
  1484. }
  1485. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1486. },
  1487. /**
  1488. * Generate the complete zip file asynchronously.
  1489. * @see generateInternalStream
  1490. */
  1491. generateAsync: function(options, onUpdate) {
  1492. return this.generateInternalStream(options).accumulate(onUpdate);
  1493. },
  1494. /**
  1495. * Generate the complete zip file asynchronously.
  1496. * @see generateInternalStream
  1497. */
  1498. generateNodeStream: function(options, onUpdate) {
  1499. options = options || {};
  1500. if (!options.type) {
  1501. options.type = "nodebuffer";
  1502. }
  1503. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1504. }
  1505. };
  1506. module.exports = out;
  1507. },{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){
  1508. /*
  1509. * This file is used by module bundlers (browserify/webpack/etc) when
  1510. * including a stream implementation. We use "readable-stream" to get a
  1511. * consistent behavior between nodejs versions but bundlers often have a shim
  1512. * for "stream". Using this shim greatly improve the compatibility and greatly
  1513. * reduce the final size of the bundle (only one stream implementation, not
  1514. * two).
  1515. */
  1516. module.exports = require("stream");
  1517. },{"stream":undefined}],17:[function(require,module,exports){
  1518. 'use strict';
  1519. var DataReader = require('./DataReader');
  1520. var utils = require('../utils');
  1521. function ArrayReader(data) {
  1522. DataReader.call(this, data);
  1523. for(var i = 0; i < this.data.length; i++) {
  1524. data[i] = data[i] & 0xFF;
  1525. }
  1526. }
  1527. utils.inherits(ArrayReader, DataReader);
  1528. /**
  1529. * @see DataReader.byteAt
  1530. */
  1531. ArrayReader.prototype.byteAt = function(i) {
  1532. return this.data[this.zero + i];
  1533. };
  1534. /**
  1535. * @see DataReader.lastIndexOfSignature
  1536. */
  1537. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1538. var sig0 = sig.charCodeAt(0),
  1539. sig1 = sig.charCodeAt(1),
  1540. sig2 = sig.charCodeAt(2),
  1541. sig3 = sig.charCodeAt(3);
  1542. for (var i = this.length - 4; i >= 0; --i) {
  1543. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1544. return i - this.zero;
  1545. }
  1546. }
  1547. return -1;
  1548. };
  1549. /**
  1550. * @see DataReader.readAndCheckSignature
  1551. */
  1552. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1553. var sig0 = sig.charCodeAt(0),
  1554. sig1 = sig.charCodeAt(1),
  1555. sig2 = sig.charCodeAt(2),
  1556. sig3 = sig.charCodeAt(3),
  1557. data = this.readData(4);
  1558. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1559. };
  1560. /**
  1561. * @see DataReader.readData
  1562. */
  1563. ArrayReader.prototype.readData = function(size) {
  1564. this.checkOffset(size);
  1565. if(size === 0) {
  1566. return [];
  1567. }
  1568. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1569. this.index += size;
  1570. return result;
  1571. };
  1572. module.exports = ArrayReader;
  1573. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1574. 'use strict';
  1575. var utils = require('../utils');
  1576. function DataReader(data) {
  1577. this.data = data; // type : see implementation
  1578. this.length = data.length;
  1579. this.index = 0;
  1580. this.zero = 0;
  1581. }
  1582. DataReader.prototype = {
  1583. /**
  1584. * Check that the offset will not go too far.
  1585. * @param {string} offset the additional offset to check.
  1586. * @throws {Error} an Error if the offset is out of bounds.
  1587. */
  1588. checkOffset: function(offset) {
  1589. this.checkIndex(this.index + offset);
  1590. },
  1591. /**
  1592. * Check that the specified index will not be too far.
  1593. * @param {string} newIndex the index to check.
  1594. * @throws {Error} an Error if the index is out of bounds.
  1595. */
  1596. checkIndex: function(newIndex) {
  1597. if (this.length < this.zero + newIndex || newIndex < 0) {
  1598. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1599. }
  1600. },
  1601. /**
  1602. * Change the index.
  1603. * @param {number} newIndex The new index.
  1604. * @throws {Error} if the new index is out of the data.
  1605. */
  1606. setIndex: function(newIndex) {
  1607. this.checkIndex(newIndex);
  1608. this.index = newIndex;
  1609. },
  1610. /**
  1611. * Skip the next n bytes.
  1612. * @param {number} n the number of bytes to skip.
  1613. * @throws {Error} if the new index is out of the data.
  1614. */
  1615. skip: function(n) {
  1616. this.setIndex(this.index + n);
  1617. },
  1618. /**
  1619. * Get the byte at the specified index.
  1620. * @param {number} i the index to use.
  1621. * @return {number} a byte.
  1622. */
  1623. byteAt: function(i) {
  1624. // see implementations
  1625. },
  1626. /**
  1627. * Get the next number with a given byte size.
  1628. * @param {number} size the number of bytes to read.
  1629. * @return {number} the corresponding number.
  1630. */
  1631. readInt: function(size) {
  1632. var result = 0,
  1633. i;
  1634. this.checkOffset(size);
  1635. for (i = this.index + size - 1; i >= this.index; i--) {
  1636. result = (result << 8) + this.byteAt(i);
  1637. }
  1638. this.index += size;
  1639. return result;
  1640. },
  1641. /**
  1642. * Get the next string with a given byte size.
  1643. * @param {number} size the number of bytes to read.
  1644. * @return {string} the corresponding string.
  1645. */
  1646. readString: function(size) {
  1647. return utils.transformTo("string", this.readData(size));
  1648. },
  1649. /**
  1650. * Get raw data without conversion, <size> bytes.
  1651. * @param {number} size the number of bytes to read.
  1652. * @return {Object} the raw data, implementation specific.
  1653. */
  1654. readData: function(size) {
  1655. // see implementations
  1656. },
  1657. /**
  1658. * Find the last occurence of a zip signature (4 bytes).
  1659. * @param {string} sig the signature to find.
  1660. * @return {number} the index of the last occurence, -1 if not found.
  1661. */
  1662. lastIndexOfSignature: function(sig) {
  1663. // see implementations
  1664. },
  1665. /**
  1666. * Read the signature (4 bytes) at the current position and compare it with sig.
  1667. * @param {string} sig the expected signature
  1668. * @return {boolean} true if the signature matches, false otherwise.
  1669. */
  1670. readAndCheckSignature: function(sig) {
  1671. // see implementations
  1672. },
  1673. /**
  1674. * Get the next date.
  1675. * @return {Date} the date.
  1676. */
  1677. readDate: function() {
  1678. var dostime = this.readInt(4);
  1679. return new Date(Date.UTC(
  1680. ((dostime >> 25) & 0x7f) + 1980, // year
  1681. ((dostime >> 21) & 0x0f) - 1, // month
  1682. (dostime >> 16) & 0x1f, // day
  1683. (dostime >> 11) & 0x1f, // hour
  1684. (dostime >> 5) & 0x3f, // minute
  1685. (dostime & 0x1f) << 1)); // second
  1686. }
  1687. };
  1688. module.exports = DataReader;
  1689. },{"../utils":32}],19:[function(require,module,exports){
  1690. 'use strict';
  1691. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1692. var utils = require('../utils');
  1693. function NodeBufferReader(data) {
  1694. Uint8ArrayReader.call(this, data);
  1695. }
  1696. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1697. /**
  1698. * @see DataReader.readData
  1699. */
  1700. NodeBufferReader.prototype.readData = function(size) {
  1701. this.checkOffset(size);
  1702. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1703. this.index += size;
  1704. return result;
  1705. };
  1706. module.exports = NodeBufferReader;
  1707. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  1708. 'use strict';
  1709. var DataReader = require('./DataReader');
  1710. var utils = require('../utils');
  1711. function StringReader(data) {
  1712. DataReader.call(this, data);
  1713. }
  1714. utils.inherits(StringReader, DataReader);
  1715. /**
  1716. * @see DataReader.byteAt
  1717. */
  1718. StringReader.prototype.byteAt = function(i) {
  1719. return this.data.charCodeAt(this.zero + i);
  1720. };
  1721. /**
  1722. * @see DataReader.lastIndexOfSignature
  1723. */
  1724. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1725. return this.data.lastIndexOf(sig) - this.zero;
  1726. };
  1727. /**
  1728. * @see DataReader.readAndCheckSignature
  1729. */
  1730. StringReader.prototype.readAndCheckSignature = function (sig) {
  1731. var data = this.readData(4);
  1732. return sig === data;
  1733. };
  1734. /**
  1735. * @see DataReader.readData
  1736. */
  1737. StringReader.prototype.readData = function(size) {
  1738. this.checkOffset(size);
  1739. // this will work because the constructor applied the "& 0xff" mask.
  1740. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1741. this.index += size;
  1742. return result;
  1743. };
  1744. module.exports = StringReader;
  1745. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  1746. 'use strict';
  1747. var ArrayReader = require('./ArrayReader');
  1748. var utils = require('../utils');
  1749. function Uint8ArrayReader(data) {
  1750. ArrayReader.call(this, data);
  1751. }
  1752. utils.inherits(Uint8ArrayReader, ArrayReader);
  1753. /**
  1754. * @see DataReader.readData
  1755. */
  1756. Uint8ArrayReader.prototype.readData = function(size) {
  1757. this.checkOffset(size);
  1758. if(size === 0) {
  1759. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1760. return new Uint8Array(0);
  1761. }
  1762. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  1763. this.index += size;
  1764. return result;
  1765. };
  1766. module.exports = Uint8ArrayReader;
  1767. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  1768. 'use strict';
  1769. var utils = require('../utils');
  1770. var support = require('../support');
  1771. var ArrayReader = require('./ArrayReader');
  1772. var StringReader = require('./StringReader');
  1773. var NodeBufferReader = require('./NodeBufferReader');
  1774. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1775. /**
  1776. * Create a reader adapted to the data.
  1777. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  1778. * @return {DataReader} the data reader.
  1779. */
  1780. module.exports = function (data) {
  1781. var type = utils.getTypeOf(data);
  1782. utils.checkSupport(type);
  1783. if (type === "string" && !support.uint8array) {
  1784. return new StringReader(data);
  1785. }
  1786. if (type === "nodebuffer") {
  1787. return new NodeBufferReader(data);
  1788. }
  1789. if (support.uint8array) {
  1790. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  1791. }
  1792. return new ArrayReader(utils.transformTo("array", data));
  1793. };
  1794. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  1795. 'use strict';
  1796. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1797. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1798. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1799. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1800. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1801. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1802. },{}],24:[function(require,module,exports){
  1803. 'use strict';
  1804. var GenericWorker = require('./GenericWorker');
  1805. var utils = require('../utils');
  1806. /**
  1807. * A worker which convert chunks to a specified type.
  1808. * @constructor
  1809. * @param {String} destType the destination type.
  1810. */
  1811. function ConvertWorker(destType) {
  1812. GenericWorker.call(this, "ConvertWorker to " + destType);
  1813. this.destType = destType;
  1814. }
  1815. utils.inherits(ConvertWorker, GenericWorker);
  1816. /**
  1817. * @see GenericWorker.processChunk
  1818. */
  1819. ConvertWorker.prototype.processChunk = function (chunk) {
  1820. this.push({
  1821. data : utils.transformTo(this.destType, chunk.data),
  1822. meta : chunk.meta
  1823. });
  1824. };
  1825. module.exports = ConvertWorker;
  1826. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  1827. 'use strict';
  1828. var GenericWorker = require('./GenericWorker');
  1829. var crc32 = require('../crc32');
  1830. var utils = require('../utils');
  1831. /**
  1832. * A worker which calculate the crc32 of the data flowing through.
  1833. * @constructor
  1834. */
  1835. function Crc32Probe() {
  1836. GenericWorker.call(this, "Crc32Probe");
  1837. this.withStreamInfo("crc32", 0);
  1838. }
  1839. utils.inherits(Crc32Probe, GenericWorker);
  1840. /**
  1841. * @see GenericWorker.processChunk
  1842. */
  1843. Crc32Probe.prototype.processChunk = function (chunk) {
  1844. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  1845. this.push(chunk);
  1846. };
  1847. module.exports = Crc32Probe;
  1848. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  1849. 'use strict';
  1850. var utils = require('../utils');
  1851. var GenericWorker = require('./GenericWorker');
  1852. /**
  1853. * A worker which calculate the total length of the data flowing through.
  1854. * @constructor
  1855. * @param {String} propName the name used to expose the length
  1856. */
  1857. function DataLengthProbe(propName) {
  1858. GenericWorker.call(this, "DataLengthProbe for " + propName);
  1859. this.propName = propName;
  1860. this.withStreamInfo(propName, 0);
  1861. }
  1862. utils.inherits(DataLengthProbe, GenericWorker);
  1863. /**
  1864. * @see GenericWorker.processChunk
  1865. */
  1866. DataLengthProbe.prototype.processChunk = function (chunk) {
  1867. if(chunk) {
  1868. var length = this.streamInfo[this.propName] || 0;
  1869. this.streamInfo[this.propName] = length + chunk.data.length;
  1870. }
  1871. GenericWorker.prototype.processChunk.call(this, chunk);
  1872. };
  1873. module.exports = DataLengthProbe;
  1874. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  1875. 'use strict';
  1876. var utils = require('../utils');
  1877. var GenericWorker = require('./GenericWorker');
  1878. // the size of the generated chunks
  1879. // TODO expose this as a public variable
  1880. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  1881. /**
  1882. * A worker that reads a content and emits chunks.
  1883. * @constructor
  1884. * @param {Promise} dataP the promise of the data to split
  1885. */
  1886. function DataWorker(dataP) {
  1887. GenericWorker.call(this, "DataWorker");
  1888. var self = this;
  1889. this.dataIsReady = false;
  1890. this.index = 0;
  1891. this.max = 0;
  1892. this.data = null;
  1893. this.type = "";
  1894. this._tickScheduled = false;
  1895. dataP.then(function (data) {
  1896. self.dataIsReady = true;
  1897. self.data = data;
  1898. self.max = data && data.length || 0;
  1899. self.type = utils.getTypeOf(data);
  1900. if(!self.isPaused) {
  1901. self._tickAndRepeat();
  1902. }
  1903. }, function (e) {
  1904. self.error(e);
  1905. });
  1906. }
  1907. utils.inherits(DataWorker, GenericWorker);
  1908. /**
  1909. * @see GenericWorker.cleanUp
  1910. */
  1911. DataWorker.prototype.cleanUp = function () {
  1912. GenericWorker.prototype.cleanUp.call(this);
  1913. this.data = null;
  1914. };
  1915. /**
  1916. * @see GenericWorker.resume
  1917. */
  1918. DataWorker.prototype.resume = function () {
  1919. if(!GenericWorker.prototype.resume.call(this)) {
  1920. return false;
  1921. }
  1922. if (!this._tickScheduled && this.dataIsReady) {
  1923. this._tickScheduled = true;
  1924. utils.delay(this._tickAndRepeat, [], this);
  1925. }
  1926. return true;
  1927. };
  1928. /**
  1929. * Trigger a tick a schedule an other call to this function.
  1930. */
  1931. DataWorker.prototype._tickAndRepeat = function() {
  1932. this._tickScheduled = false;
  1933. if(this.isPaused || this.isFinished) {
  1934. return;
  1935. }
  1936. this._tick();
  1937. if(!this.isFinished) {
  1938. utils.delay(this._tickAndRepeat, [], this);
  1939. this._tickScheduled = true;
  1940. }
  1941. };
  1942. /**
  1943. * Read and push a chunk.
  1944. */
  1945. DataWorker.prototype._tick = function() {
  1946. if(this.isPaused || this.isFinished) {
  1947. return false;
  1948. }
  1949. var size = DEFAULT_BLOCK_SIZE;
  1950. var data = null, nextIndex = Math.min(this.max, this.index + size);
  1951. if (this.index >= this.max) {
  1952. // EOF
  1953. return this.end();
  1954. } else {
  1955. switch(this.type) {
  1956. case "string":
  1957. data = this.data.substring(this.index, nextIndex);
  1958. break;
  1959. case "uint8array":
  1960. data = this.data.subarray(this.index, nextIndex);
  1961. break;
  1962. case "array":
  1963. case "nodebuffer":
  1964. data = this.data.slice(this.index, nextIndex);
  1965. break;
  1966. }
  1967. this.index = nextIndex;
  1968. return this.push({
  1969. data : data,
  1970. meta : {
  1971. percent : this.max ? this.index / this.max * 100 : 0
  1972. }
  1973. });
  1974. }
  1975. };
  1976. module.exports = DataWorker;
  1977. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  1978. 'use strict';
  1979. /**
  1980. * A worker that does nothing but passing chunks to the next one. This is like
  1981. * a nodejs stream but with some differences. On the good side :
  1982. * - it works on IE 6-9 without any issue / polyfill
  1983. * - it weights less than the full dependencies bundled with browserify
  1984. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  1985. *
  1986. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  1987. * object containing anything (`percent` for example), see each worker for more
  1988. * details. The latter is the real data (String, Uint8Array, etc).
  1989. *
  1990. * @constructor
  1991. * @param {String} name the name of the stream (mainly used for debugging purposes)
  1992. */
  1993. function GenericWorker(name) {
  1994. // the name of the worker
  1995. this.name = name || "default";
  1996. // an object containing metadata about the workers chain
  1997. this.streamInfo = {};
  1998. // an error which happened when the worker was paused
  1999. this.generatedError = null;
  2000. // an object containing metadata to be merged by this worker into the general metadata
  2001. this.extraStreamInfo = {};
  2002. // true if the stream is paused (and should not do anything), false otherwise
  2003. this.isPaused = true;
  2004. // true if the stream is finished (and should not do anything), false otherwise
  2005. this.isFinished = false;
  2006. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2007. this.isLocked = false;
  2008. // the event listeners
  2009. this._listeners = {
  2010. 'data':[],
  2011. 'end':[],
  2012. 'error':[]
  2013. };
  2014. // the previous worker, if any
  2015. this.previous = null;
  2016. }
  2017. GenericWorker.prototype = {
  2018. /**
  2019. * Push a chunk to the next workers.
  2020. * @param {Object} chunk the chunk to push
  2021. */
  2022. push : function (chunk) {
  2023. this.emit("data", chunk);
  2024. },
  2025. /**
  2026. * End the stream.
  2027. * @return {Boolean} true if this call ended the worker, false otherwise.
  2028. */
  2029. end : function () {
  2030. if (this.isFinished) {
  2031. return false;
  2032. }
  2033. this.flush();
  2034. try {
  2035. this.emit("end");
  2036. this.cleanUp();
  2037. this.isFinished = true;
  2038. } catch (e) {
  2039. this.emit("error", e);
  2040. }
  2041. return true;
  2042. },
  2043. /**
  2044. * End the stream with an error.
  2045. * @param {Error} e the error which caused the premature end.
  2046. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2047. */
  2048. error : function (e) {
  2049. if (this.isFinished) {
  2050. return false;
  2051. }
  2052. if(this.isPaused) {
  2053. this.generatedError = e;
  2054. } else {
  2055. this.isFinished = true;
  2056. this.emit("error", e);
  2057. // in the workers chain exploded in the middle of the chain,
  2058. // the error event will go downward but we also need to notify
  2059. // workers upward that there has been an error.
  2060. if(this.previous) {
  2061. this.previous.error(e);
  2062. }
  2063. this.cleanUp();
  2064. }
  2065. return true;
  2066. },
  2067. /**
  2068. * Add a callback on an event.
  2069. * @param {String} name the name of the event (data, end, error)
  2070. * @param {Function} listener the function to call when the event is triggered
  2071. * @return {GenericWorker} the current object for chainability
  2072. */
  2073. on : function (name, listener) {
  2074. this._listeners[name].push(listener);
  2075. return this;
  2076. },
  2077. /**
  2078. * Clean any references when a worker is ending.
  2079. */
  2080. cleanUp : function () {
  2081. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2082. this._listeners = [];
  2083. },
  2084. /**
  2085. * Trigger an event. This will call registered callback with the provided arg.
  2086. * @param {String} name the name of the event (data, end, error)
  2087. * @param {Object} arg the argument to call the callback with.
  2088. */
  2089. emit : function (name, arg) {
  2090. if (this._listeners[name]) {
  2091. for(var i = 0; i < this._listeners[name].length; i++) {
  2092. this._listeners[name][i].call(this, arg);
  2093. }
  2094. }
  2095. },
  2096. /**
  2097. * Chain a worker with an other.
  2098. * @param {Worker} next the worker receiving events from the current one.
  2099. * @return {worker} the next worker for chainability
  2100. */
  2101. pipe : function (next) {
  2102. return next.registerPrevious(this);
  2103. },
  2104. /**
  2105. * Same as `pipe` in the other direction.
  2106. * Using an API with `pipe(next)` is very easy.
  2107. * Implementing the API with the point of view of the next one registering
  2108. * a source is easier, see the ZipFileWorker.
  2109. * @param {Worker} previous the previous worker, sending events to this one
  2110. * @return {Worker} the current worker for chainability
  2111. */
  2112. registerPrevious : function (previous) {
  2113. if (this.isLocked) {
  2114. throw new Error("The stream '" + this + "' has already been used.");
  2115. }
  2116. // sharing the streamInfo...
  2117. this.streamInfo = previous.streamInfo;
  2118. // ... and adding our own bits
  2119. this.mergeStreamInfo();
  2120. this.previous = previous;
  2121. var self = this;
  2122. previous.on('data', function (chunk) {
  2123. self.processChunk(chunk);
  2124. });
  2125. previous.on('end', function () {
  2126. self.end();
  2127. });
  2128. previous.on('error', function (e) {
  2129. self.error(e);
  2130. });
  2131. return this;
  2132. },
  2133. /**
  2134. * Pause the stream so it doesn't send events anymore.
  2135. * @return {Boolean} true if this call paused the worker, false otherwise.
  2136. */
  2137. pause : function () {
  2138. if(this.isPaused || this.isFinished) {
  2139. return false;
  2140. }
  2141. this.isPaused = true;
  2142. if(this.previous) {
  2143. this.previous.pause();
  2144. }
  2145. return true;
  2146. },
  2147. /**
  2148. * Resume a paused stream.
  2149. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2150. */
  2151. resume : function () {
  2152. if(!this.isPaused || this.isFinished) {
  2153. return false;
  2154. }
  2155. this.isPaused = false;
  2156. // if true, the worker tried to resume but failed
  2157. var withError = false;
  2158. if(this.generatedError) {
  2159. this.error(this.generatedError);
  2160. withError = true;
  2161. }
  2162. if(this.previous) {
  2163. this.previous.resume();
  2164. }
  2165. return !withError;
  2166. },
  2167. /**
  2168. * Flush any remaining bytes as the stream is ending.
  2169. */
  2170. flush : function () {},
  2171. /**
  2172. * Process a chunk. This is usually the method overridden.
  2173. * @param {Object} chunk the chunk to process.
  2174. */
  2175. processChunk : function(chunk) {
  2176. this.push(chunk);
  2177. },
  2178. /**
  2179. * Add a key/value to be added in the workers chain streamInfo once activated.
  2180. * @param {String} key the key to use
  2181. * @param {Object} value the associated value
  2182. * @return {Worker} the current worker for chainability
  2183. */
  2184. withStreamInfo : function (key, value) {
  2185. this.extraStreamInfo[key] = value;
  2186. this.mergeStreamInfo();
  2187. return this;
  2188. },
  2189. /**
  2190. * Merge this worker's streamInfo into the chain's streamInfo.
  2191. */
  2192. mergeStreamInfo : function () {
  2193. for(var key in this.extraStreamInfo) {
  2194. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2195. continue;
  2196. }
  2197. this.streamInfo[key] = this.extraStreamInfo[key];
  2198. }
  2199. },
  2200. /**
  2201. * Lock the stream to prevent further updates on the workers chain.
  2202. * After calling this method, all calls to pipe will fail.
  2203. */
  2204. lock: function () {
  2205. if (this.isLocked) {
  2206. throw new Error("The stream '" + this + "' has already been used.");
  2207. }
  2208. this.isLocked = true;
  2209. if (this.previous) {
  2210. this.previous.lock();
  2211. }
  2212. },
  2213. /**
  2214. *
  2215. * Pretty print the workers chain.
  2216. */
  2217. toString : function () {
  2218. var me = "Worker " + this.name;
  2219. if (this.previous) {
  2220. return this.previous + " -> " + me;
  2221. } else {
  2222. return me;
  2223. }
  2224. }
  2225. };
  2226. module.exports = GenericWorker;
  2227. },{}],29:[function(require,module,exports){
  2228. 'use strict';
  2229. var utils = require('../utils');
  2230. var ConvertWorker = require('./ConvertWorker');
  2231. var GenericWorker = require('./GenericWorker');
  2232. var base64 = require('../base64');
  2233. var support = require("../support");
  2234. var external = require("../external");
  2235. var NodejsStreamOutputAdapter = null;
  2236. if (support.nodestream) {
  2237. try {
  2238. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2239. } catch(e) {}
  2240. }
  2241. /**
  2242. * Apply the final transformation of the data. If the user wants a Blob for
  2243. * example, it's easier to work with an U8intArray and finally do the
  2244. * ArrayBuffer/Blob conversion.
  2245. * @param {String} type the name of the final type
  2246. * @param {String|Uint8Array|Buffer} content the content to transform
  2247. * @param {String} mimeType the mime type of the content, if applicable.
  2248. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2249. */
  2250. function transformZipOutput(type, content, mimeType) {
  2251. switch(type) {
  2252. case "blob" :
  2253. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  2254. case "base64" :
  2255. return base64.encode(content);
  2256. default :
  2257. return utils.transformTo(type, content);
  2258. }
  2259. }
  2260. /**
  2261. * Concatenate an array of data of the given type.
  2262. * @param {String} type the type of the data in the given array.
  2263. * @param {Array} dataArray the array containing the data chunks to concatenate
  2264. * @return {String|Uint8Array|Buffer} the concatenated data
  2265. * @throws Error if the asked type is unsupported
  2266. */
  2267. function concat (type, dataArray) {
  2268. var i, index = 0, res = null, totalLength = 0;
  2269. for(i = 0; i < dataArray.length; i++) {
  2270. totalLength += dataArray[i].length;
  2271. }
  2272. switch(type) {
  2273. case "string":
  2274. return dataArray.join("");
  2275. case "array":
  2276. return Array.prototype.concat.apply([], dataArray);
  2277. case "uint8array":
  2278. res = new Uint8Array(totalLength);
  2279. for(i = 0; i < dataArray.length; i++) {
  2280. res.set(dataArray[i], index);
  2281. index += dataArray[i].length;
  2282. }
  2283. return res;
  2284. case "nodebuffer":
  2285. return Buffer.concat(dataArray);
  2286. default:
  2287. throw new Error("concat : unsupported type '" + type + "'");
  2288. }
  2289. }
  2290. /**
  2291. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2292. * complete block.
  2293. * @param {StreamHelper} helper the helper to use.
  2294. * @param {Function} updateCallback a callback called on each update. Called
  2295. * with one arg :
  2296. * - the metadata linked to the update received.
  2297. * @return Promise the promise for the accumulation.
  2298. */
  2299. function accumulate(helper, updateCallback) {
  2300. return new external.Promise(function (resolve, reject){
  2301. var dataArray = [];
  2302. var chunkType = helper._internalType,
  2303. resultType = helper._outputType,
  2304. mimeType = helper._mimeType;
  2305. helper
  2306. .on('data', function (data, meta) {
  2307. dataArray.push(data);
  2308. if(updateCallback) {
  2309. updateCallback(meta);
  2310. }
  2311. })
  2312. .on('error', function(err) {
  2313. dataArray = [];
  2314. reject(err);
  2315. })
  2316. .on('end', function (){
  2317. try {
  2318. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  2319. resolve(result);
  2320. } catch (e) {
  2321. reject(e);
  2322. }
  2323. dataArray = [];
  2324. })
  2325. .resume();
  2326. });
  2327. }
  2328. /**
  2329. * An helper to easily use workers outside of JSZip.
  2330. * @constructor
  2331. * @param {Worker} worker the worker to wrap
  2332. * @param {String} outputType the type of data expected by the use
  2333. * @param {String} mimeType the mime type of the content, if applicable.
  2334. */
  2335. function StreamHelper(worker, outputType, mimeType) {
  2336. var internalType = outputType;
  2337. switch(outputType) {
  2338. case "blob":
  2339. case "arraybuffer":
  2340. internalType = "uint8array";
  2341. break;
  2342. case "base64":
  2343. internalType = "string";
  2344. break;
  2345. }
  2346. try {
  2347. // the type used internally
  2348. this._internalType = internalType;
  2349. // the type used to output results
  2350. this._outputType = outputType;
  2351. // the mime type
  2352. this._mimeType = mimeType;
  2353. utils.checkSupport(internalType);
  2354. this._worker = worker.pipe(new ConvertWorker(internalType));
  2355. // the last workers can be rewired without issues but we need to
  2356. // prevent any updates on previous workers.
  2357. worker.lock();
  2358. } catch(e) {
  2359. this._worker = new GenericWorker("error");
  2360. this._worker.error(e);
  2361. }
  2362. }
  2363. StreamHelper.prototype = {
  2364. /**
  2365. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2366. * complete block.
  2367. * @param {Function} updateCb the update callback.
  2368. * @return Promise the promise for the accumulation.
  2369. */
  2370. accumulate : function (updateCb) {
  2371. return accumulate(this, updateCb);
  2372. },
  2373. /**
  2374. * Add a listener on an event triggered on a stream.
  2375. * @param {String} evt the name of the event
  2376. * @param {Function} fn the listener
  2377. * @return {StreamHelper} the current helper.
  2378. */
  2379. on : function (evt, fn) {
  2380. var self = this;
  2381. if(evt === "data") {
  2382. this._worker.on(evt, function (chunk) {
  2383. fn.call(self, chunk.data, chunk.meta);
  2384. });
  2385. } else {
  2386. this._worker.on(evt, function () {
  2387. utils.delay(fn, arguments, self);
  2388. });
  2389. }
  2390. return this;
  2391. },
  2392. /**
  2393. * Resume the flow of chunks.
  2394. * @return {StreamHelper} the current helper.
  2395. */
  2396. resume : function () {
  2397. utils.delay(this._worker.resume, [], this._worker);
  2398. return this;
  2399. },
  2400. /**
  2401. * Pause the flow of chunks.
  2402. * @return {StreamHelper} the current helper.
  2403. */
  2404. pause : function () {
  2405. this._worker.pause();
  2406. return this;
  2407. },
  2408. /**
  2409. * Return a nodejs stream for this helper.
  2410. * @param {Function} updateCb the update callback.
  2411. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2412. */
  2413. toNodejsStream : function (updateCb) {
  2414. utils.checkSupport("nodestream");
  2415. if (this._outputType !== "nodebuffer") {
  2416. // an object stream containing blob/arraybuffer/uint8array/string
  2417. // is strange and I don't know if it would be useful.
  2418. // I you find this comment and have a good usecase, please open a
  2419. // bug report !
  2420. throw new Error(this._outputType + " is not supported by this method");
  2421. }
  2422. return new NodejsStreamOutputAdapter(this, {
  2423. objectMode : this._outputType !== "nodebuffer"
  2424. }, updateCb);
  2425. }
  2426. };
  2427. module.exports = StreamHelper;
  2428. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2429. 'use strict';
  2430. exports.base64 = true;
  2431. exports.array = true;
  2432. exports.string = true;
  2433. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2434. exports.nodebuffer = typeof Buffer !== "undefined";
  2435. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2436. exports.uint8array = typeof Uint8Array !== "undefined";
  2437. if (typeof ArrayBuffer === "undefined") {
  2438. exports.blob = false;
  2439. }
  2440. else {
  2441. var buffer = new ArrayBuffer(0);
  2442. try {
  2443. exports.blob = new Blob([buffer], {
  2444. type: "application/zip"
  2445. }).size === 0;
  2446. }
  2447. catch (e) {
  2448. try {
  2449. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2450. var builder = new Builder();
  2451. builder.append(buffer);
  2452. exports.blob = builder.getBlob('application/zip').size === 0;
  2453. }
  2454. catch (e) {
  2455. exports.blob = false;
  2456. }
  2457. }
  2458. }
  2459. try {
  2460. exports.nodestream = !!require('readable-stream').Readable;
  2461. } catch(e) {
  2462. exports.nodestream = false;
  2463. }
  2464. },{"readable-stream":16}],31:[function(require,module,exports){
  2465. 'use strict';
  2466. var utils = require('./utils');
  2467. var support = require('./support');
  2468. var nodejsUtils = require('./nodejsUtils');
  2469. var GenericWorker = require('./stream/GenericWorker');
  2470. /**
  2471. * The following functions come from pako, from pako/lib/utils/strings
  2472. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2473. */
  2474. // Table with utf8 lengths (calculated by first byte of sequence)
  2475. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2476. // because max possible codepoint is 0x10ffff
  2477. var _utf8len = new Array(256);
  2478. for (var i=0; i<256; i++) {
  2479. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2480. }
  2481. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2482. // convert string to array (typed, when possible)
  2483. var string2buf = function (str) {
  2484. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2485. // count binary size
  2486. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2487. c = str.charCodeAt(m_pos);
  2488. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2489. c2 = str.charCodeAt(m_pos+1);
  2490. if ((c2 & 0xfc00) === 0xdc00) {
  2491. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2492. m_pos++;
  2493. }
  2494. }
  2495. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2496. }
  2497. // allocate buffer
  2498. if (support.uint8array) {
  2499. buf = new Uint8Array(buf_len);
  2500. } else {
  2501. buf = new Array(buf_len);
  2502. }
  2503. // convert
  2504. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2505. c = str.charCodeAt(m_pos);
  2506. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2507. c2 = str.charCodeAt(m_pos+1);
  2508. if ((c2 & 0xfc00) === 0xdc00) {
  2509. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2510. m_pos++;
  2511. }
  2512. }
  2513. if (c < 0x80) {
  2514. /* one byte */
  2515. buf[i++] = c;
  2516. } else if (c < 0x800) {
  2517. /* two bytes */
  2518. buf[i++] = 0xC0 | (c >>> 6);
  2519. buf[i++] = 0x80 | (c & 0x3f);
  2520. } else if (c < 0x10000) {
  2521. /* three bytes */
  2522. buf[i++] = 0xE0 | (c >>> 12);
  2523. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2524. buf[i++] = 0x80 | (c & 0x3f);
  2525. } else {
  2526. /* four bytes */
  2527. buf[i++] = 0xf0 | (c >>> 18);
  2528. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2529. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2530. buf[i++] = 0x80 | (c & 0x3f);
  2531. }
  2532. }
  2533. return buf;
  2534. };
  2535. // Calculate max possible position in utf8 buffer,
  2536. // that will not break sequence. If that's not possible
  2537. // - (very small limits) return max size as is.
  2538. //
  2539. // buf[] - utf8 bytes array
  2540. // max - length limit (mandatory);
  2541. var utf8border = function(buf, max) {
  2542. var pos;
  2543. max = max || buf.length;
  2544. if (max > buf.length) { max = buf.length; }
  2545. // go back from last position, until start of sequence found
  2546. pos = max-1;
  2547. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2548. // Fuckup - very small and broken sequence,
  2549. // return max, because we should return something anyway.
  2550. if (pos < 0) { return max; }
  2551. // If we came to start of buffer - that means vuffer is too small,
  2552. // return max too.
  2553. if (pos === 0) { return max; }
  2554. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2555. };
  2556. // convert array to string
  2557. var buf2string = function (buf) {
  2558. var str, i, out, c, c_len;
  2559. var len = buf.length;
  2560. // Reserve max possible length (2 words per char)
  2561. // NB: by unknown reasons, Array is significantly faster for
  2562. // String.fromCharCode.apply than Uint16Array.
  2563. var utf16buf = new Array(len*2);
  2564. for (out=0, i=0; i<len;) {
  2565. c = buf[i++];
  2566. // quick process ascii
  2567. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2568. c_len = _utf8len[c];
  2569. // skip 5 & 6 byte codes
  2570. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2571. // apply mask on first byte
  2572. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2573. // join the rest
  2574. while (c_len > 1 && i < len) {
  2575. c = (c << 6) | (buf[i++] & 0x3f);
  2576. c_len--;
  2577. }
  2578. // terminated by end of string?
  2579. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2580. if (c < 0x10000) {
  2581. utf16buf[out++] = c;
  2582. } else {
  2583. c -= 0x10000;
  2584. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2585. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2586. }
  2587. }
  2588. // shrinkBuf(utf16buf, out)
  2589. if (utf16buf.length !== out) {
  2590. if(utf16buf.subarray) {
  2591. utf16buf = utf16buf.subarray(0, out);
  2592. } else {
  2593. utf16buf.length = out;
  2594. }
  2595. }
  2596. // return String.fromCharCode.apply(null, utf16buf);
  2597. return utils.applyFromCharCode(utf16buf);
  2598. };
  2599. // That's all for the pako functions.
  2600. /**
  2601. * Transform a javascript string into an array (typed if possible) of bytes,
  2602. * UTF-8 encoded.
  2603. * @param {String} str the string to encode
  2604. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  2605. */
  2606. exports.utf8encode = function utf8encode(str) {
  2607. if (support.nodebuffer) {
  2608. return nodejsUtils.newBufferFrom(str, "utf-8");
  2609. }
  2610. return string2buf(str);
  2611. };
  2612. /**
  2613. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2614. * string into a javascript string.
  2615. * @param {Array|Uint8Array|Buffer} buf the data de decode
  2616. * @return {String} the decoded string.
  2617. */
  2618. exports.utf8decode = function utf8decode(buf) {
  2619. if (support.nodebuffer) {
  2620. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2621. }
  2622. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  2623. return buf2string(buf);
  2624. };
  2625. /**
  2626. * A worker to decode utf8 encoded binary chunks into string chunks.
  2627. * @constructor
  2628. */
  2629. function Utf8DecodeWorker() {
  2630. GenericWorker.call(this, "utf-8 decode");
  2631. // the last bytes if a chunk didn't end with a complete codepoint.
  2632. this.leftOver = null;
  2633. }
  2634. utils.inherits(Utf8DecodeWorker, GenericWorker);
  2635. /**
  2636. * @see GenericWorker.processChunk
  2637. */
  2638. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  2639. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  2640. // 1st step, re-use what's left of the previous chunk
  2641. if (this.leftOver && this.leftOver.length) {
  2642. if(support.uint8array) {
  2643. var previousData = data;
  2644. data = new Uint8Array(previousData.length + this.leftOver.length);
  2645. data.set(this.leftOver, 0);
  2646. data.set(previousData, this.leftOver.length);
  2647. } else {
  2648. data = this.leftOver.concat(data);
  2649. }
  2650. this.leftOver = null;
  2651. }
  2652. var nextBoundary = utf8border(data);
  2653. var usableData = data;
  2654. if (nextBoundary !== data.length) {
  2655. if (support.uint8array) {
  2656. usableData = data.subarray(0, nextBoundary);
  2657. this.leftOver = data.subarray(nextBoundary, data.length);
  2658. } else {
  2659. usableData = data.slice(0, nextBoundary);
  2660. this.leftOver = data.slice(nextBoundary, data.length);
  2661. }
  2662. }
  2663. this.push({
  2664. data : exports.utf8decode(usableData),
  2665. meta : chunk.meta
  2666. });
  2667. };
  2668. /**
  2669. * @see GenericWorker.flush
  2670. */
  2671. Utf8DecodeWorker.prototype.flush = function () {
  2672. if(this.leftOver && this.leftOver.length) {
  2673. this.push({
  2674. data : exports.utf8decode(this.leftOver),
  2675. meta : {}
  2676. });
  2677. this.leftOver = null;
  2678. }
  2679. };
  2680. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  2681. /**
  2682. * A worker to endcode string chunks into utf8 encoded binary chunks.
  2683. * @constructor
  2684. */
  2685. function Utf8EncodeWorker() {
  2686. GenericWorker.call(this, "utf-8 encode");
  2687. }
  2688. utils.inherits(Utf8EncodeWorker, GenericWorker);
  2689. /**
  2690. * @see GenericWorker.processChunk
  2691. */
  2692. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  2693. this.push({
  2694. data : exports.utf8encode(chunk.data),
  2695. meta : chunk.meta
  2696. });
  2697. };
  2698. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  2699. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  2700. 'use strict';
  2701. var support = require('./support');
  2702. var base64 = require('./base64');
  2703. var nodejsUtils = require('./nodejsUtils');
  2704. var setImmediate = require('set-immediate-shim');
  2705. var external = require("./external");
  2706. /**
  2707. * Convert a string that pass as a "binary string": it should represent a byte
  2708. * array but may have > 255 char codes. Be sure to take only the first byte
  2709. * and returns the byte array.
  2710. * @param {String} str the string to transform.
  2711. * @return {Array|Uint8Array} the string in a binary format.
  2712. */
  2713. function string2binary(str) {
  2714. var result = null;
  2715. if (support.uint8array) {
  2716. result = new Uint8Array(str.length);
  2717. } else {
  2718. result = new Array(str.length);
  2719. }
  2720. return stringToArrayLike(str, result);
  2721. }
  2722. /**
  2723. * Create a new blob with the given content and the given type.
  2724. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  2725. * an Uint8Array because the stock browser of android 4 won't accept it (it
  2726. * will be silently converted to a string, "[object Uint8Array]").
  2727. *
  2728. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  2729. * when a large amount of Array is used to create the Blob, the amount of
  2730. * memory consumed is nearly 100 times the original data amount.
  2731. *
  2732. * @param {String} type the mime type of the blob.
  2733. * @return {Blob} the created blob.
  2734. */
  2735. exports.newBlob = function(part, type) {
  2736. exports.checkSupport("blob");
  2737. try {
  2738. // Blob constructor
  2739. return new Blob([part], {
  2740. type: type
  2741. });
  2742. }
  2743. catch (e) {
  2744. try {
  2745. // deprecated, browser only, old way
  2746. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2747. var builder = new Builder();
  2748. builder.append(part);
  2749. return builder.getBlob(type);
  2750. }
  2751. catch (e) {
  2752. // well, fuck ?!
  2753. throw new Error("Bug : can't construct the Blob.");
  2754. }
  2755. }
  2756. };
  2757. /**
  2758. * The identity function.
  2759. * @param {Object} input the input.
  2760. * @return {Object} the same input.
  2761. */
  2762. function identity(input) {
  2763. return input;
  2764. }
  2765. /**
  2766. * Fill in an array with a string.
  2767. * @param {String} str the string to use.
  2768. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  2769. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  2770. */
  2771. function stringToArrayLike(str, array) {
  2772. for (var i = 0; i < str.length; ++i) {
  2773. array[i] = str.charCodeAt(i) & 0xFF;
  2774. }
  2775. return array;
  2776. }
  2777. /**
  2778. * An helper for the function arrayLikeToString.
  2779. * This contains static informations and functions that
  2780. * can be optimized by the browser JIT compiler.
  2781. */
  2782. var arrayToStringHelper = {
  2783. /**
  2784. * Transform an array of int into a string, chunk by chunk.
  2785. * See the performances notes on arrayLikeToString.
  2786. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2787. * @param {String} type the type of the array.
  2788. * @param {Integer} chunk the chunk size.
  2789. * @return {String} the resulting string.
  2790. * @throws Error if the chunk is too big for the stack.
  2791. */
  2792. stringifyByChunk: function(array, type, chunk) {
  2793. var result = [], k = 0, len = array.length;
  2794. // shortcut
  2795. if (len <= chunk) {
  2796. return String.fromCharCode.apply(null, array);
  2797. }
  2798. while (k < len) {
  2799. if (type === "array" || type === "nodebuffer") {
  2800. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  2801. }
  2802. else {
  2803. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  2804. }
  2805. k += chunk;
  2806. }
  2807. return result.join("");
  2808. },
  2809. /**
  2810. * Call String.fromCharCode on every item in the array.
  2811. * This is the naive implementation, which generate A LOT of intermediate string.
  2812. * This should be used when everything else fail.
  2813. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2814. * @return {String} the result.
  2815. */
  2816. stringifyByChar: function(array){
  2817. var resultStr = "";
  2818. for(var i = 0; i < array.length; i++) {
  2819. resultStr += String.fromCharCode(array[i]);
  2820. }
  2821. return resultStr;
  2822. },
  2823. applyCanBeUsed : {
  2824. /**
  2825. * true if the browser accepts to use String.fromCharCode on Uint8Array
  2826. */
  2827. uint8array : (function () {
  2828. try {
  2829. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  2830. } catch (e) {
  2831. return false;
  2832. }
  2833. })(),
  2834. /**
  2835. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  2836. */
  2837. nodebuffer : (function () {
  2838. try {
  2839. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  2840. } catch (e) {
  2841. return false;
  2842. }
  2843. })()
  2844. }
  2845. };
  2846. /**
  2847. * Transform an array-like object to a string.
  2848. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2849. * @return {String} the result.
  2850. */
  2851. function arrayLikeToString(array) {
  2852. // Performances notes :
  2853. // --------------------
  2854. // String.fromCharCode.apply(null, array) is the fastest, see
  2855. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  2856. // but the stack is limited (and we can get huge arrays !).
  2857. //
  2858. // result += String.fromCharCode(array[i]); generate too many strings !
  2859. //
  2860. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  2861. // TODO : we now have workers that split the work. Do we still need that ?
  2862. var chunk = 65536,
  2863. type = exports.getTypeOf(array),
  2864. canUseApply = true;
  2865. if (type === "uint8array") {
  2866. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  2867. } else if (type === "nodebuffer") {
  2868. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  2869. }
  2870. if (canUseApply) {
  2871. while (chunk > 1) {
  2872. try {
  2873. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  2874. } catch (e) {
  2875. chunk = Math.floor(chunk / 2);
  2876. }
  2877. }
  2878. }
  2879. // no apply or chunk error : slow and painful algorithm
  2880. // default browser on android 4.*
  2881. return arrayToStringHelper.stringifyByChar(array);
  2882. }
  2883. exports.applyFromCharCode = arrayLikeToString;
  2884. /**
  2885. * Copy the data from an array-like to an other array-like.
  2886. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  2887. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  2888. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  2889. */
  2890. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  2891. for (var i = 0; i < arrayFrom.length; i++) {
  2892. arrayTo[i] = arrayFrom[i];
  2893. }
  2894. return arrayTo;
  2895. }
  2896. // a matrix containing functions to transform everything into everything.
  2897. var transform = {};
  2898. // string to ?
  2899. transform["string"] = {
  2900. "string": identity,
  2901. "array": function(input) {
  2902. return stringToArrayLike(input, new Array(input.length));
  2903. },
  2904. "arraybuffer": function(input) {
  2905. return transform["string"]["uint8array"](input).buffer;
  2906. },
  2907. "uint8array": function(input) {
  2908. return stringToArrayLike(input, new Uint8Array(input.length));
  2909. },
  2910. "nodebuffer": function(input) {
  2911. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  2912. }
  2913. };
  2914. // array to ?
  2915. transform["array"] = {
  2916. "string": arrayLikeToString,
  2917. "array": identity,
  2918. "arraybuffer": function(input) {
  2919. return (new Uint8Array(input)).buffer;
  2920. },
  2921. "uint8array": function(input) {
  2922. return new Uint8Array(input);
  2923. },
  2924. "nodebuffer": function(input) {
  2925. return nodejsUtils.newBufferFrom(input);
  2926. }
  2927. };
  2928. // arraybuffer to ?
  2929. transform["arraybuffer"] = {
  2930. "string": function(input) {
  2931. return arrayLikeToString(new Uint8Array(input));
  2932. },
  2933. "array": function(input) {
  2934. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  2935. },
  2936. "arraybuffer": identity,
  2937. "uint8array": function(input) {
  2938. return new Uint8Array(input);
  2939. },
  2940. "nodebuffer": function(input) {
  2941. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  2942. }
  2943. };
  2944. // uint8array to ?
  2945. transform["uint8array"] = {
  2946. "string": arrayLikeToString,
  2947. "array": function(input) {
  2948. return arrayLikeToArrayLike(input, new Array(input.length));
  2949. },
  2950. "arraybuffer": function(input) {
  2951. return input.buffer;
  2952. },
  2953. "uint8array": identity,
  2954. "nodebuffer": function(input) {
  2955. return nodejsUtils.newBufferFrom(input);
  2956. }
  2957. };
  2958. // nodebuffer to ?
  2959. transform["nodebuffer"] = {
  2960. "string": arrayLikeToString,
  2961. "array": function(input) {
  2962. return arrayLikeToArrayLike(input, new Array(input.length));
  2963. },
  2964. "arraybuffer": function(input) {
  2965. return transform["nodebuffer"]["uint8array"](input).buffer;
  2966. },
  2967. "uint8array": function(input) {
  2968. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  2969. },
  2970. "nodebuffer": identity
  2971. };
  2972. /**
  2973. * Transform an input into any type.
  2974. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  2975. * If no output type is specified, the unmodified input will be returned.
  2976. * @param {String} outputType the output type.
  2977. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  2978. * @throws {Error} an Error if the browser doesn't support the requested output type.
  2979. */
  2980. exports.transformTo = function(outputType, input) {
  2981. if (!input) {
  2982. // undefined, null, etc
  2983. // an empty string won't harm.
  2984. input = "";
  2985. }
  2986. if (!outputType) {
  2987. return input;
  2988. }
  2989. exports.checkSupport(outputType);
  2990. var inputType = exports.getTypeOf(input);
  2991. var result = transform[inputType][outputType](input);
  2992. return result;
  2993. };
  2994. /**
  2995. * Return the type of the input.
  2996. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  2997. * @param {Object} input the input to identify.
  2998. * @return {String} the (lowercase) type of the input.
  2999. */
  3000. exports.getTypeOf = function(input) {
  3001. if (typeof input === "string") {
  3002. return "string";
  3003. }
  3004. if (Object.prototype.toString.call(input) === "[object Array]") {
  3005. return "array";
  3006. }
  3007. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3008. return "nodebuffer";
  3009. }
  3010. if (support.uint8array && input instanceof Uint8Array) {
  3011. return "uint8array";
  3012. }
  3013. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3014. return "arraybuffer";
  3015. }
  3016. };
  3017. /**
  3018. * Throw an exception if the type is not supported.
  3019. * @param {String} type the type to check.
  3020. * @throws {Error} an Error if the browser doesn't support the requested type.
  3021. */
  3022. exports.checkSupport = function(type) {
  3023. var supported = support[type.toLowerCase()];
  3024. if (!supported) {
  3025. throw new Error(type + " is not supported by this platform");
  3026. }
  3027. };
  3028. exports.MAX_VALUE_16BITS = 65535;
  3029. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3030. /**
  3031. * Prettify a string read as binary.
  3032. * @param {string} str the string to prettify.
  3033. * @return {string} a pretty string.
  3034. */
  3035. exports.pretty = function(str) {
  3036. var res = '',
  3037. code, i;
  3038. for (i = 0; i < (str || "").length; i++) {
  3039. code = str.charCodeAt(i);
  3040. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3041. }
  3042. return res;
  3043. };
  3044. /**
  3045. * Defer the call of a function.
  3046. * @param {Function} callback the function to call asynchronously.
  3047. * @param {Array} args the arguments to give to the callback.
  3048. */
  3049. exports.delay = function(callback, args, self) {
  3050. setImmediate(function () {
  3051. callback.apply(self || null, args || []);
  3052. });
  3053. };
  3054. /**
  3055. * Extends a prototype with an other, without calling a constructor with
  3056. * side effects. Inspired by nodejs' `utils.inherits`
  3057. * @param {Function} ctor the constructor to augment
  3058. * @param {Function} superCtor the parent constructor to use
  3059. */
  3060. exports.inherits = function (ctor, superCtor) {
  3061. var Obj = function() {};
  3062. Obj.prototype = superCtor.prototype;
  3063. ctor.prototype = new Obj();
  3064. };
  3065. /**
  3066. * Merge the objects passed as parameters into a new one.
  3067. * @private
  3068. * @param {...Object} var_args All objects to merge.
  3069. * @return {Object} a new object with the data of the others.
  3070. */
  3071. exports.extend = function() {
  3072. var result = {}, i, attr;
  3073. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3074. for (attr in arguments[i]) {
  3075. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3076. result[attr] = arguments[i][attr];
  3077. }
  3078. }
  3079. }
  3080. return result;
  3081. };
  3082. /**
  3083. * Transform arbitrary content into a Promise.
  3084. * @param {String} name a name for the content being processed.
  3085. * @param {Object} inputData the content to process.
  3086. * @param {Boolean} isBinary true if the content is not an unicode string
  3087. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3088. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3089. * @return {Promise} a promise in a format usable by JSZip.
  3090. */
  3091. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3092. // if inputData is already a promise, this flatten it.
  3093. var promise = external.Promise.resolve(inputData).then(function(data) {
  3094. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3095. if (isBlob && typeof FileReader !== "undefined") {
  3096. return new external.Promise(function (resolve, reject) {
  3097. var reader = new FileReader();
  3098. reader.onload = function(e) {
  3099. resolve(e.target.result);
  3100. };
  3101. reader.onerror = function(e) {
  3102. reject(e.target.error);
  3103. };
  3104. reader.readAsArrayBuffer(data);
  3105. });
  3106. } else {
  3107. return data;
  3108. }
  3109. });
  3110. return promise.then(function(data) {
  3111. var dataType = exports.getTypeOf(data);
  3112. if (!dataType) {
  3113. return external.Promise.reject(
  3114. new Error("Can't read the data of '" + name + "'. Is it " +
  3115. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  3116. );
  3117. }
  3118. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3119. if (dataType === "arraybuffer") {
  3120. data = exports.transformTo("uint8array", data);
  3121. } else if (dataType === "string") {
  3122. if (isBase64) {
  3123. data = base64.decode(data);
  3124. }
  3125. else if (isBinary) {
  3126. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3127. if (isOptimizedBinaryString !== true) {
  3128. // this is a string, not in a base64 format.
  3129. // Be sure that this is a correct "binary string"
  3130. data = string2binary(data);
  3131. }
  3132. }
  3133. }
  3134. return data;
  3135. });
  3136. };
  3137. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"set-immediate-shim":54}],33:[function(require,module,exports){
  3138. 'use strict';
  3139. var readerFor = require('./reader/readerFor');
  3140. var utils = require('./utils');
  3141. var sig = require('./signature');
  3142. var ZipEntry = require('./zipEntry');
  3143. var utf8 = require('./utf8');
  3144. var support = require('./support');
  3145. // class ZipEntries {{{
  3146. /**
  3147. * All the entries in the zip file.
  3148. * @constructor
  3149. * @param {Object} loadOptions Options for loading the stream.
  3150. */
  3151. function ZipEntries(loadOptions) {
  3152. this.files = [];
  3153. this.loadOptions = loadOptions;
  3154. }
  3155. ZipEntries.prototype = {
  3156. /**
  3157. * Check that the reader is on the specified signature.
  3158. * @param {string} expectedSignature the expected signature.
  3159. * @throws {Error} if it is an other signature.
  3160. */
  3161. checkSignature: function(expectedSignature) {
  3162. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3163. this.reader.index -= 4;
  3164. var signature = this.reader.readString(4);
  3165. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3166. }
  3167. },
  3168. /**
  3169. * Check if the given signature is at the given index.
  3170. * @param {number} askedIndex the index to check.
  3171. * @param {string} expectedSignature the signature to expect.
  3172. * @return {boolean} true if the signature is here, false otherwise.
  3173. */
  3174. isSignature: function(askedIndex, expectedSignature) {
  3175. var currentIndex = this.reader.index;
  3176. this.reader.setIndex(askedIndex);
  3177. var signature = this.reader.readString(4);
  3178. var result = signature === expectedSignature;
  3179. this.reader.setIndex(currentIndex);
  3180. return result;
  3181. },
  3182. /**
  3183. * Read the end of the central directory.
  3184. */
  3185. readBlockEndOfCentral: function() {
  3186. this.diskNumber = this.reader.readInt(2);
  3187. this.diskWithCentralDirStart = this.reader.readInt(2);
  3188. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3189. this.centralDirRecords = this.reader.readInt(2);
  3190. this.centralDirSize = this.reader.readInt(4);
  3191. this.centralDirOffset = this.reader.readInt(4);
  3192. this.zipCommentLength = this.reader.readInt(2);
  3193. // warning : the encoding depends of the system locale
  3194. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3195. // On a windows machine, this field is encoded with the localized windows code page.
  3196. var zipComment = this.reader.readData(this.zipCommentLength);
  3197. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3198. // To get consistent behavior with the generation part, we will assume that
  3199. // this is utf8 encoded unless specified otherwise.
  3200. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3201. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3202. },
  3203. /**
  3204. * Read the end of the Zip 64 central directory.
  3205. * Not merged with the method readEndOfCentral :
  3206. * The end of central can coexist with its Zip64 brother,
  3207. * I don't want to read the wrong number of bytes !
  3208. */
  3209. readBlockZip64EndOfCentral: function() {
  3210. this.zip64EndOfCentralSize = this.reader.readInt(8);
  3211. this.reader.skip(4);
  3212. // this.versionMadeBy = this.reader.readString(2);
  3213. // this.versionNeeded = this.reader.readInt(2);
  3214. this.diskNumber = this.reader.readInt(4);
  3215. this.diskWithCentralDirStart = this.reader.readInt(4);
  3216. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3217. this.centralDirRecords = this.reader.readInt(8);
  3218. this.centralDirSize = this.reader.readInt(8);
  3219. this.centralDirOffset = this.reader.readInt(8);
  3220. this.zip64ExtensibleData = {};
  3221. var extraDataSize = this.zip64EndOfCentralSize - 44,
  3222. index = 0,
  3223. extraFieldId,
  3224. extraFieldLength,
  3225. extraFieldValue;
  3226. while (index < extraDataSize) {
  3227. extraFieldId = this.reader.readInt(2);
  3228. extraFieldLength = this.reader.readInt(4);
  3229. extraFieldValue = this.reader.readData(extraFieldLength);
  3230. this.zip64ExtensibleData[extraFieldId] = {
  3231. id: extraFieldId,
  3232. length: extraFieldLength,
  3233. value: extraFieldValue
  3234. };
  3235. }
  3236. },
  3237. /**
  3238. * Read the end of the Zip 64 central directory locator.
  3239. */
  3240. readBlockZip64EndOfCentralLocator: function() {
  3241. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3242. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3243. this.disksCount = this.reader.readInt(4);
  3244. if (this.disksCount > 1) {
  3245. throw new Error("Multi-volumes zip are not supported");
  3246. }
  3247. },
  3248. /**
  3249. * Read the local files, based on the offset read in the central part.
  3250. */
  3251. readLocalFiles: function() {
  3252. var i, file;
  3253. for (i = 0; i < this.files.length; i++) {
  3254. file = this.files[i];
  3255. this.reader.setIndex(file.localHeaderOffset);
  3256. this.checkSignature(sig.LOCAL_FILE_HEADER);
  3257. file.readLocalPart(this.reader);
  3258. file.handleUTF8();
  3259. file.processAttributes();
  3260. }
  3261. },
  3262. /**
  3263. * Read the central directory.
  3264. */
  3265. readCentralDir: function() {
  3266. var file;
  3267. this.reader.setIndex(this.centralDirOffset);
  3268. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3269. file = new ZipEntry({
  3270. zip64: this.zip64
  3271. }, this.loadOptions);
  3272. file.readCentralPart(this.reader);
  3273. this.files.push(file);
  3274. }
  3275. if (this.centralDirRecords !== this.files.length) {
  3276. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3277. // We expected some records but couldn't find ANY.
  3278. // This is really suspicious, as if something went wrong.
  3279. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3280. } else {
  3281. // We found some records but not all.
  3282. // Something is wrong but we got something for the user: no error here.
  3283. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3284. }
  3285. }
  3286. },
  3287. /**
  3288. * Read the end of central directory.
  3289. */
  3290. readEndOfCentral: function() {
  3291. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3292. if (offset < 0) {
  3293. // Check if the content is a truncated zip or complete garbage.
  3294. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3295. // extractible zip for example) but it can give a good hint.
  3296. // If an ajax request was used without responseType, we will also
  3297. // get unreadable data.
  3298. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3299. if (isGarbage) {
  3300. throw new Error("Can't find end of central directory : is this a zip file ? " +
  3301. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3302. } else {
  3303. throw new Error("Corrupted zip: can't find end of central directory");
  3304. }
  3305. }
  3306. this.reader.setIndex(offset);
  3307. var endOfCentralDirOffset = offset;
  3308. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3309. this.readBlockEndOfCentral();
  3310. /* extract from the zip spec :
  3311. 4) If one of the fields in the end of central directory
  3312. record is too small to hold required data, the field
  3313. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3314. ZIP64 format record should be created.
  3315. 5) The end of central directory record and the
  3316. Zip64 end of central directory locator record must
  3317. reside on the same disk when splitting or spanning
  3318. an archive.
  3319. */
  3320. if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
  3321. this.zip64 = true;
  3322. /*
  3323. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3324. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  3325. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3326. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3327. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3328. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3329. */
  3330. // should look for a zip64 EOCD locator
  3331. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3332. if (offset < 0) {
  3333. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  3334. }
  3335. this.reader.setIndex(offset);
  3336. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3337. this.readBlockZip64EndOfCentralLocator();
  3338. // now the zip64 EOCD record
  3339. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3340. // console.warn("ZIP64 end of central directory not where expected.");
  3341. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3342. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3343. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  3344. }
  3345. }
  3346. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3347. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3348. this.readBlockZip64EndOfCentral();
  3349. }
  3350. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3351. if (this.zip64) {
  3352. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3353. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3354. }
  3355. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3356. if (extraBytes > 0) {
  3357. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3358. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3359. // The offsets seem wrong, but we have something at the specified offset.
  3360. // So… we keep it.
  3361. } else {
  3362. // the offset is wrong, update the "zero" of the reader
  3363. // this happens if data has been prepended (crx files for example)
  3364. this.reader.zero = extraBytes;
  3365. }
  3366. } else if (extraBytes < 0) {
  3367. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3368. }
  3369. },
  3370. prepareReader: function(data) {
  3371. this.reader = readerFor(data);
  3372. },
  3373. /**
  3374. * Read a zip file and create ZipEntries.
  3375. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3376. */
  3377. load: function(data) {
  3378. this.prepareReader(data);
  3379. this.readEndOfCentral();
  3380. this.readCentralDir();
  3381. this.readLocalFiles();
  3382. }
  3383. };
  3384. // }}} end of ZipEntries
  3385. module.exports = ZipEntries;
  3386. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3387. 'use strict';
  3388. var readerFor = require('./reader/readerFor');
  3389. var utils = require('./utils');
  3390. var CompressedObject = require('./compressedObject');
  3391. var crc32fn = require('./crc32');
  3392. var utf8 = require('./utf8');
  3393. var compressions = require('./compressions');
  3394. var support = require('./support');
  3395. var MADE_BY_DOS = 0x00;
  3396. var MADE_BY_UNIX = 0x03;
  3397. /**
  3398. * Find a compression registered in JSZip.
  3399. * @param {string} compressionMethod the method magic to find.
  3400. * @return {Object|null} the JSZip compression object, null if none found.
  3401. */
  3402. var findCompression = function(compressionMethod) {
  3403. for (var method in compressions) {
  3404. if (!compressions.hasOwnProperty(method)) {
  3405. continue;
  3406. }
  3407. if (compressions[method].magic === compressionMethod) {
  3408. return compressions[method];
  3409. }
  3410. }
  3411. return null;
  3412. };
  3413. // class ZipEntry {{{
  3414. /**
  3415. * An entry in the zip file.
  3416. * @constructor
  3417. * @param {Object} options Options of the current file.
  3418. * @param {Object} loadOptions Options for loading the stream.
  3419. */
  3420. function ZipEntry(options, loadOptions) {
  3421. this.options = options;
  3422. this.loadOptions = loadOptions;
  3423. }
  3424. ZipEntry.prototype = {
  3425. /**
  3426. * say if the file is encrypted.
  3427. * @return {boolean} true if the file is encrypted, false otherwise.
  3428. */
  3429. isEncrypted: function() {
  3430. // bit 1 is set
  3431. return (this.bitFlag & 0x0001) === 0x0001;
  3432. },
  3433. /**
  3434. * say if the file has utf-8 filename/comment.
  3435. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3436. */
  3437. useUTF8: function() {
  3438. // bit 11 is set
  3439. return (this.bitFlag & 0x0800) === 0x0800;
  3440. },
  3441. /**
  3442. * Read the local part of a zip file and add the info in this object.
  3443. * @param {DataReader} reader the reader to use.
  3444. */
  3445. readLocalPart: function(reader) {
  3446. var compression, localExtraFieldsLength;
  3447. // we already know everything from the central dir !
  3448. // If the central dir data are false, we are doomed.
  3449. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  3450. // The less data we get here, the more reliable this should be.
  3451. // Let's skip the whole header and dash to the data !
  3452. reader.skip(22);
  3453. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3454. // Strangely, the filename here is OK.
  3455. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3456. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3457. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3458. // the internet.
  3459. //
  3460. // I think I see the logic here : the central directory is used to display
  3461. // content and the local directory is used to extract the files. Mixing / and \
  3462. // may be used to display \ to windows users and use / when extracting the files.
  3463. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3464. this.fileNameLength = reader.readInt(2);
  3465. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3466. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3467. this.fileName = reader.readData(this.fileNameLength);
  3468. reader.skip(localExtraFieldsLength);
  3469. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3470. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3471. }
  3472. compression = findCompression(this.compressionMethod);
  3473. if (compression === null) { // no compression found
  3474. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3475. }
  3476. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3477. },
  3478. /**
  3479. * Read the central part of a zip file and add the info in this object.
  3480. * @param {DataReader} reader the reader to use.
  3481. */
  3482. readCentralPart: function(reader) {
  3483. this.versionMadeBy = reader.readInt(2);
  3484. reader.skip(2);
  3485. // this.versionNeeded = reader.readInt(2);
  3486. this.bitFlag = reader.readInt(2);
  3487. this.compressionMethod = reader.readString(2);
  3488. this.date = reader.readDate();
  3489. this.crc32 = reader.readInt(4);
  3490. this.compressedSize = reader.readInt(4);
  3491. this.uncompressedSize = reader.readInt(4);
  3492. var fileNameLength = reader.readInt(2);
  3493. this.extraFieldsLength = reader.readInt(2);
  3494. this.fileCommentLength = reader.readInt(2);
  3495. this.diskNumberStart = reader.readInt(2);
  3496. this.internalFileAttributes = reader.readInt(2);
  3497. this.externalFileAttributes = reader.readInt(4);
  3498. this.localHeaderOffset = reader.readInt(4);
  3499. if (this.isEncrypted()) {
  3500. throw new Error("Encrypted zip are not supported");
  3501. }
  3502. // will be read in the local part, see the comments there
  3503. reader.skip(fileNameLength);
  3504. this.readExtraFields(reader);
  3505. this.parseZIP64ExtraField(reader);
  3506. this.fileComment = reader.readData(this.fileCommentLength);
  3507. },
  3508. /**
  3509. * Parse the external file attributes and get the unix/dos permissions.
  3510. */
  3511. processAttributes: function () {
  3512. this.unixPermissions = null;
  3513. this.dosPermissions = null;
  3514. var madeBy = this.versionMadeBy >> 8;
  3515. // Check if we have the DOS directory flag set.
  3516. // We look for it in the DOS and UNIX permissions
  3517. // but some unknown platform could set it as a compatibility flag.
  3518. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3519. if(madeBy === MADE_BY_DOS) {
  3520. // first 6 bits (0 to 5)
  3521. this.dosPermissions = this.externalFileAttributes & 0x3F;
  3522. }
  3523. if(madeBy === MADE_BY_UNIX) {
  3524. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  3525. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  3526. }
  3527. // fail safe : if the name ends with a / it probably means a folder
  3528. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  3529. this.dir = true;
  3530. }
  3531. },
  3532. /**
  3533. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  3534. * @param {DataReader} reader the reader to use.
  3535. */
  3536. parseZIP64ExtraField: function(reader) {
  3537. if (!this.extraFields[0x0001]) {
  3538. return;
  3539. }
  3540. // should be something, preparing the extra reader
  3541. var extraReader = readerFor(this.extraFields[0x0001].value);
  3542. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  3543. // won't let us have more.
  3544. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  3545. this.uncompressedSize = extraReader.readInt(8);
  3546. }
  3547. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  3548. this.compressedSize = extraReader.readInt(8);
  3549. }
  3550. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  3551. this.localHeaderOffset = extraReader.readInt(8);
  3552. }
  3553. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  3554. this.diskNumberStart = extraReader.readInt(4);
  3555. }
  3556. },
  3557. /**
  3558. * Read the central part of a zip file and add the info in this object.
  3559. * @param {DataReader} reader the reader to use.
  3560. */
  3561. readExtraFields: function(reader) {
  3562. var end = reader.index + this.extraFieldsLength,
  3563. extraFieldId,
  3564. extraFieldLength,
  3565. extraFieldValue;
  3566. if (!this.extraFields) {
  3567. this.extraFields = {};
  3568. }
  3569. while (reader.index < end) {
  3570. extraFieldId = reader.readInt(2);
  3571. extraFieldLength = reader.readInt(2);
  3572. extraFieldValue = reader.readData(extraFieldLength);
  3573. this.extraFields[extraFieldId] = {
  3574. id: extraFieldId,
  3575. length: extraFieldLength,
  3576. value: extraFieldValue
  3577. };
  3578. }
  3579. },
  3580. /**
  3581. * Apply an UTF8 transformation if needed.
  3582. */
  3583. handleUTF8: function() {
  3584. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3585. if (this.useUTF8()) {
  3586. this.fileNameStr = utf8.utf8decode(this.fileName);
  3587. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  3588. } else {
  3589. var upath = this.findExtraFieldUnicodePath();
  3590. if (upath !== null) {
  3591. this.fileNameStr = upath;
  3592. } else {
  3593. // ASCII text or unsupported code page
  3594. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  3595. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  3596. }
  3597. var ucomment = this.findExtraFieldUnicodeComment();
  3598. if (ucomment !== null) {
  3599. this.fileCommentStr = ucomment;
  3600. } else {
  3601. // ASCII text or unsupported code page
  3602. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  3603. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  3604. }
  3605. }
  3606. },
  3607. /**
  3608. * Find the unicode path declared in the extra field, if any.
  3609. * @return {String} the unicode path, null otherwise.
  3610. */
  3611. findExtraFieldUnicodePath: function() {
  3612. var upathField = this.extraFields[0x7075];
  3613. if (upathField) {
  3614. var extraReader = readerFor(upathField.value);
  3615. // wrong version
  3616. if (extraReader.readInt(1) !== 1) {
  3617. return null;
  3618. }
  3619. // the crc of the filename changed, this field is out of date.
  3620. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  3621. return null;
  3622. }
  3623. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  3624. }
  3625. return null;
  3626. },
  3627. /**
  3628. * Find the unicode comment declared in the extra field, if any.
  3629. * @return {String} the unicode comment, null otherwise.
  3630. */
  3631. findExtraFieldUnicodeComment: function() {
  3632. var ucommentField = this.extraFields[0x6375];
  3633. if (ucommentField) {
  3634. var extraReader = readerFor(ucommentField.value);
  3635. // wrong version
  3636. if (extraReader.readInt(1) !== 1) {
  3637. return null;
  3638. }
  3639. // the crc of the comment changed, this field is out of date.
  3640. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  3641. return null;
  3642. }
  3643. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  3644. }
  3645. return null;
  3646. }
  3647. };
  3648. module.exports = ZipEntry;
  3649. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  3650. 'use strict';
  3651. var StreamHelper = require('./stream/StreamHelper');
  3652. var DataWorker = require('./stream/DataWorker');
  3653. var utf8 = require('./utf8');
  3654. var CompressedObject = require('./compressedObject');
  3655. var GenericWorker = require('./stream/GenericWorker');
  3656. /**
  3657. * A simple object representing a file in the zip file.
  3658. * @constructor
  3659. * @param {string} name the name of the file
  3660. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  3661. * @param {Object} options the options of the file
  3662. */
  3663. var ZipObject = function(name, data, options) {
  3664. this.name = name;
  3665. this.dir = options.dir;
  3666. this.date = options.date;
  3667. this.comment = options.comment;
  3668. this.unixPermissions = options.unixPermissions;
  3669. this.dosPermissions = options.dosPermissions;
  3670. this._data = data;
  3671. this._dataBinary = options.binary;
  3672. // keep only the compression
  3673. this.options = {
  3674. compression : options.compression,
  3675. compressionOptions : options.compressionOptions
  3676. };
  3677. };
  3678. ZipObject.prototype = {
  3679. /**
  3680. * Create an internal stream for the content of this object.
  3681. * @param {String} type the type of each chunk.
  3682. * @return StreamHelper the stream.
  3683. */
  3684. internalStream: function (type) {
  3685. var result = null, outputType = "string";
  3686. try {
  3687. if (!type) {
  3688. throw new Error("No output type specified.");
  3689. }
  3690. outputType = type.toLowerCase();
  3691. var askUnicodeString = outputType === "string" || outputType === "text";
  3692. if (outputType === "binarystring" || outputType === "text") {
  3693. outputType = "string";
  3694. }
  3695. result = this._decompressWorker();
  3696. var isUnicodeString = !this._dataBinary;
  3697. if (isUnicodeString && !askUnicodeString) {
  3698. result = result.pipe(new utf8.Utf8EncodeWorker());
  3699. }
  3700. if (!isUnicodeString && askUnicodeString) {
  3701. result = result.pipe(new utf8.Utf8DecodeWorker());
  3702. }
  3703. } catch (e) {
  3704. result = new GenericWorker("error");
  3705. result.error(e);
  3706. }
  3707. return new StreamHelper(result, outputType, "");
  3708. },
  3709. /**
  3710. * Prepare the content in the asked type.
  3711. * @param {String} type the type of the result.
  3712. * @param {Function} onUpdate a function to call on each internal update.
  3713. * @return Promise the promise of the result.
  3714. */
  3715. async: function (type, onUpdate) {
  3716. return this.internalStream(type).accumulate(onUpdate);
  3717. },
  3718. /**
  3719. * Prepare the content as a nodejs stream.
  3720. * @param {String} type the type of each chunk.
  3721. * @param {Function} onUpdate a function to call on each internal update.
  3722. * @return Stream the stream.
  3723. */
  3724. nodeStream: function (type, onUpdate) {
  3725. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  3726. },
  3727. /**
  3728. * Return a worker for the compressed content.
  3729. * @private
  3730. * @param {Object} compression the compression object to use.
  3731. * @param {Object} compressionOptions the options to use when compressing.
  3732. * @return Worker the worker.
  3733. */
  3734. _compressWorker: function (compression, compressionOptions) {
  3735. if (
  3736. this._data instanceof CompressedObject &&
  3737. this._data.compression.magic === compression.magic
  3738. ) {
  3739. return this._data.getCompressedWorker();
  3740. } else {
  3741. var result = this._decompressWorker();
  3742. if(!this._dataBinary) {
  3743. result = result.pipe(new utf8.Utf8EncodeWorker());
  3744. }
  3745. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  3746. }
  3747. },
  3748. /**
  3749. * Return a worker for the decompressed content.
  3750. * @private
  3751. * @return Worker the worker.
  3752. */
  3753. _decompressWorker : function () {
  3754. if (this._data instanceof CompressedObject) {
  3755. return this._data.getContentWorker();
  3756. } else if (this._data instanceof GenericWorker) {
  3757. return this._data;
  3758. } else {
  3759. return new DataWorker(this._data);
  3760. }
  3761. }
  3762. };
  3763. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  3764. var removedFn = function () {
  3765. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3766. };
  3767. for(var i = 0; i < removedMethods.length; i++) {
  3768. ZipObject.prototype[removedMethods[i]] = removedFn;
  3769. }
  3770. module.exports = ZipObject;
  3771. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  3772. (function (global){
  3773. 'use strict';
  3774. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  3775. var scheduleDrain;
  3776. {
  3777. if (Mutation) {
  3778. var called = 0;
  3779. var observer = new Mutation(nextTick);
  3780. var element = global.document.createTextNode('');
  3781. observer.observe(element, {
  3782. characterData: true
  3783. });
  3784. scheduleDrain = function () {
  3785. element.data = (called = ++called % 2);
  3786. };
  3787. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  3788. var channel = new global.MessageChannel();
  3789. channel.port1.onmessage = nextTick;
  3790. scheduleDrain = function () {
  3791. channel.port2.postMessage(0);
  3792. };
  3793. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  3794. scheduleDrain = function () {
  3795. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  3796. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  3797. var scriptEl = global.document.createElement('script');
  3798. scriptEl.onreadystatechange = function () {
  3799. nextTick();
  3800. scriptEl.onreadystatechange = null;
  3801. scriptEl.parentNode.removeChild(scriptEl);
  3802. scriptEl = null;
  3803. };
  3804. global.document.documentElement.appendChild(scriptEl);
  3805. };
  3806. } else {
  3807. scheduleDrain = function () {
  3808. setTimeout(nextTick, 0);
  3809. };
  3810. }
  3811. }
  3812. var draining;
  3813. var queue = [];
  3814. //named nextTick for less confusing stack traces
  3815. function nextTick() {
  3816. draining = true;
  3817. var i, oldQueue;
  3818. var len = queue.length;
  3819. while (len) {
  3820. oldQueue = queue;
  3821. queue = [];
  3822. i = -1;
  3823. while (++i < len) {
  3824. oldQueue[i]();
  3825. }
  3826. len = queue.length;
  3827. }
  3828. draining = false;
  3829. }
  3830. module.exports = immediate;
  3831. function immediate(task) {
  3832. if (queue.push(task) === 1 && !draining) {
  3833. scheduleDrain();
  3834. }
  3835. }
  3836. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3837. },{}],37:[function(require,module,exports){
  3838. 'use strict';
  3839. var immediate = require('immediate');
  3840. /* istanbul ignore next */
  3841. function INTERNAL() {}
  3842. var handlers = {};
  3843. var REJECTED = ['REJECTED'];
  3844. var FULFILLED = ['FULFILLED'];
  3845. var PENDING = ['PENDING'];
  3846. module.exports = Promise;
  3847. function Promise(resolver) {
  3848. if (typeof resolver !== 'function') {
  3849. throw new TypeError('resolver must be a function');
  3850. }
  3851. this.state = PENDING;
  3852. this.queue = [];
  3853. this.outcome = void 0;
  3854. if (resolver !== INTERNAL) {
  3855. safelyResolveThenable(this, resolver);
  3856. }
  3857. }
  3858. Promise.prototype["finally"] = function (callback) {
  3859. if (typeof callback !== 'function') {
  3860. return this;
  3861. }
  3862. var p = this.constructor;
  3863. return this.then(resolve, reject);
  3864. function resolve(value) {
  3865. function yes () {
  3866. return value;
  3867. }
  3868. return p.resolve(callback()).then(yes);
  3869. }
  3870. function reject(reason) {
  3871. function no () {
  3872. throw reason;
  3873. }
  3874. return p.resolve(callback()).then(no);
  3875. }
  3876. };
  3877. Promise.prototype["catch"] = function (onRejected) {
  3878. return this.then(null, onRejected);
  3879. };
  3880. Promise.prototype.then = function (onFulfilled, onRejected) {
  3881. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  3882. typeof onRejected !== 'function' && this.state === REJECTED) {
  3883. return this;
  3884. }
  3885. var promise = new this.constructor(INTERNAL);
  3886. if (this.state !== PENDING) {
  3887. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  3888. unwrap(promise, resolver, this.outcome);
  3889. } else {
  3890. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  3891. }
  3892. return promise;
  3893. };
  3894. function QueueItem(promise, onFulfilled, onRejected) {
  3895. this.promise = promise;
  3896. if (typeof onFulfilled === 'function') {
  3897. this.onFulfilled = onFulfilled;
  3898. this.callFulfilled = this.otherCallFulfilled;
  3899. }
  3900. if (typeof onRejected === 'function') {
  3901. this.onRejected = onRejected;
  3902. this.callRejected = this.otherCallRejected;
  3903. }
  3904. }
  3905. QueueItem.prototype.callFulfilled = function (value) {
  3906. handlers.resolve(this.promise, value);
  3907. };
  3908. QueueItem.prototype.otherCallFulfilled = function (value) {
  3909. unwrap(this.promise, this.onFulfilled, value);
  3910. };
  3911. QueueItem.prototype.callRejected = function (value) {
  3912. handlers.reject(this.promise, value);
  3913. };
  3914. QueueItem.prototype.otherCallRejected = function (value) {
  3915. unwrap(this.promise, this.onRejected, value);
  3916. };
  3917. function unwrap(promise, func, value) {
  3918. immediate(function () {
  3919. var returnValue;
  3920. try {
  3921. returnValue = func(value);
  3922. } catch (e) {
  3923. return handlers.reject(promise, e);
  3924. }
  3925. if (returnValue === promise) {
  3926. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  3927. } else {
  3928. handlers.resolve(promise, returnValue);
  3929. }
  3930. });
  3931. }
  3932. handlers.resolve = function (self, value) {
  3933. var result = tryCatch(getThen, value);
  3934. if (result.status === 'error') {
  3935. return handlers.reject(self, result.value);
  3936. }
  3937. var thenable = result.value;
  3938. if (thenable) {
  3939. safelyResolveThenable(self, thenable);
  3940. } else {
  3941. self.state = FULFILLED;
  3942. self.outcome = value;
  3943. var i = -1;
  3944. var len = self.queue.length;
  3945. while (++i < len) {
  3946. self.queue[i].callFulfilled(value);
  3947. }
  3948. }
  3949. return self;
  3950. };
  3951. handlers.reject = function (self, error) {
  3952. self.state = REJECTED;
  3953. self.outcome = error;
  3954. var i = -1;
  3955. var len = self.queue.length;
  3956. while (++i < len) {
  3957. self.queue[i].callRejected(error);
  3958. }
  3959. return self;
  3960. };
  3961. function getThen(obj) {
  3962. // Make sure we only access the accessor once as required by the spec
  3963. var then = obj && obj.then;
  3964. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  3965. return function appyThen() {
  3966. then.apply(obj, arguments);
  3967. };
  3968. }
  3969. }
  3970. function safelyResolveThenable(self, thenable) {
  3971. // Either fulfill, reject or reject with error
  3972. var called = false;
  3973. function onError(value) {
  3974. if (called) {
  3975. return;
  3976. }
  3977. called = true;
  3978. handlers.reject(self, value);
  3979. }
  3980. function onSuccess(value) {
  3981. if (called) {
  3982. return;
  3983. }
  3984. called = true;
  3985. handlers.resolve(self, value);
  3986. }
  3987. function tryToUnwrap() {
  3988. thenable(onSuccess, onError);
  3989. }
  3990. var result = tryCatch(tryToUnwrap);
  3991. if (result.status === 'error') {
  3992. onError(result.value);
  3993. }
  3994. }
  3995. function tryCatch(func, value) {
  3996. var out = {};
  3997. try {
  3998. out.value = func(value);
  3999. out.status = 'success';
  4000. } catch (e) {
  4001. out.status = 'error';
  4002. out.value = e;
  4003. }
  4004. return out;
  4005. }
  4006. Promise.resolve = resolve;
  4007. function resolve(value) {
  4008. if (value instanceof this) {
  4009. return value;
  4010. }
  4011. return handlers.resolve(new this(INTERNAL), value);
  4012. }
  4013. Promise.reject = reject;
  4014. function reject(reason) {
  4015. var promise = new this(INTERNAL);
  4016. return handlers.reject(promise, reason);
  4017. }
  4018. Promise.all = all;
  4019. function all(iterable) {
  4020. var self = this;
  4021. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4022. return this.reject(new TypeError('must be an array'));
  4023. }
  4024. var len = iterable.length;
  4025. var called = false;
  4026. if (!len) {
  4027. return this.resolve([]);
  4028. }
  4029. var values = new Array(len);
  4030. var resolved = 0;
  4031. var i = -1;
  4032. var promise = new this(INTERNAL);
  4033. while (++i < len) {
  4034. allResolver(iterable[i], i);
  4035. }
  4036. return promise;
  4037. function allResolver(value, i) {
  4038. self.resolve(value).then(resolveFromAll, function (error) {
  4039. if (!called) {
  4040. called = true;
  4041. handlers.reject(promise, error);
  4042. }
  4043. });
  4044. function resolveFromAll(outValue) {
  4045. values[i] = outValue;
  4046. if (++resolved === len && !called) {
  4047. called = true;
  4048. handlers.resolve(promise, values);
  4049. }
  4050. }
  4051. }
  4052. }
  4053. Promise.race = race;
  4054. function race(iterable) {
  4055. var self = this;
  4056. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4057. return this.reject(new TypeError('must be an array'));
  4058. }
  4059. var len = iterable.length;
  4060. var called = false;
  4061. if (!len) {
  4062. return this.resolve([]);
  4063. }
  4064. var i = -1;
  4065. var promise = new this(INTERNAL);
  4066. while (++i < len) {
  4067. resolver(iterable[i]);
  4068. }
  4069. return promise;
  4070. function resolver(value) {
  4071. self.resolve(value).then(function (response) {
  4072. if (!called) {
  4073. called = true;
  4074. handlers.resolve(promise, response);
  4075. }
  4076. }, function (error) {
  4077. if (!called) {
  4078. called = true;
  4079. handlers.reject(promise, error);
  4080. }
  4081. });
  4082. }
  4083. }
  4084. },{"immediate":36}],38:[function(require,module,exports){
  4085. // Top level file is just a mixin of submodules & constants
  4086. 'use strict';
  4087. var assign = require('./lib/utils/common').assign;
  4088. var deflate = require('./lib/deflate');
  4089. var inflate = require('./lib/inflate');
  4090. var constants = require('./lib/zlib/constants');
  4091. var pako = {};
  4092. assign(pako, deflate, inflate, constants);
  4093. module.exports = pako;
  4094. },{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
  4095. 'use strict';
  4096. var zlib_deflate = require('./zlib/deflate');
  4097. var utils = require('./utils/common');
  4098. var strings = require('./utils/strings');
  4099. var msg = require('./zlib/messages');
  4100. var ZStream = require('./zlib/zstream');
  4101. var toString = Object.prototype.toString;
  4102. /* Public constants ==========================================================*/
  4103. /* ===========================================================================*/
  4104. var Z_NO_FLUSH = 0;
  4105. var Z_FINISH = 4;
  4106. var Z_OK = 0;
  4107. var Z_STREAM_END = 1;
  4108. var Z_SYNC_FLUSH = 2;
  4109. var Z_DEFAULT_COMPRESSION = -1;
  4110. var Z_DEFAULT_STRATEGY = 0;
  4111. var Z_DEFLATED = 8;
  4112. /* ===========================================================================*/
  4113. /**
  4114. * class Deflate
  4115. *
  4116. * Generic JS-style wrapper for zlib calls. If you don't need
  4117. * streaming behaviour - use more simple functions: [[deflate]],
  4118. * [[deflateRaw]] and [[gzip]].
  4119. **/
  4120. /* internal
  4121. * Deflate.chunks -> Array
  4122. *
  4123. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4124. **/
  4125. /**
  4126. * Deflate.result -> Uint8Array|Array
  4127. *
  4128. * Compressed result, generated by default [[Deflate#onData]]
  4129. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4130. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4131. * push a chunk with explicit flush (call [[Deflate#push]] with
  4132. * `Z_SYNC_FLUSH` param).
  4133. **/
  4134. /**
  4135. * Deflate.err -> Number
  4136. *
  4137. * Error code after deflate finished. 0 (Z_OK) on success.
  4138. * You will not need it in real life, because deflate errors
  4139. * are possible only on wrong options or bad `onData` / `onEnd`
  4140. * custom handlers.
  4141. **/
  4142. /**
  4143. * Deflate.msg -> String
  4144. *
  4145. * Error message, if [[Deflate.err]] != 0
  4146. **/
  4147. /**
  4148. * new Deflate(options)
  4149. * - options (Object): zlib deflate options.
  4150. *
  4151. * Creates new deflator instance with specified params. Throws exception
  4152. * on bad params. Supported options:
  4153. *
  4154. * - `level`
  4155. * - `windowBits`
  4156. * - `memLevel`
  4157. * - `strategy`
  4158. * - `dictionary`
  4159. *
  4160. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4161. * for more information on these.
  4162. *
  4163. * Additional options, for internal needs:
  4164. *
  4165. * - `chunkSize` - size of generated data chunks (16K by default)
  4166. * - `raw` (Boolean) - do raw deflate
  4167. * - `gzip` (Boolean) - create gzip wrapper
  4168. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4169. * (each char code [0..255])
  4170. * - `header` (Object) - custom header for gzip
  4171. * - `text` (Boolean) - true if compressed data believed to be text
  4172. * - `time` (Number) - modification time, unix timestamp
  4173. * - `os` (Number) - operation system code
  4174. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4175. * - `name` (String) - file name (binary string)
  4176. * - `comment` (String) - comment (binary string)
  4177. * - `hcrc` (Boolean) - true if header crc should be added
  4178. *
  4179. * ##### Example:
  4180. *
  4181. * ```javascript
  4182. * var pako = require('pako')
  4183. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4184. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4185. *
  4186. * var deflate = new pako.Deflate({ level: 3});
  4187. *
  4188. * deflate.push(chunk1, false);
  4189. * deflate.push(chunk2, true); // true -> last chunk
  4190. *
  4191. * if (deflate.err) { throw new Error(deflate.err); }
  4192. *
  4193. * console.log(deflate.result);
  4194. * ```
  4195. **/
  4196. function Deflate(options) {
  4197. if (!(this instanceof Deflate)) return new Deflate(options);
  4198. this.options = utils.assign({
  4199. level: Z_DEFAULT_COMPRESSION,
  4200. method: Z_DEFLATED,
  4201. chunkSize: 16384,
  4202. windowBits: 15,
  4203. memLevel: 8,
  4204. strategy: Z_DEFAULT_STRATEGY,
  4205. to: ''
  4206. }, options || {});
  4207. var opt = this.options;
  4208. if (opt.raw && (opt.windowBits > 0)) {
  4209. opt.windowBits = -opt.windowBits;
  4210. }
  4211. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  4212. opt.windowBits += 16;
  4213. }
  4214. this.err = 0; // error code, if happens (0 = Z_OK)
  4215. this.msg = ''; // error message
  4216. this.ended = false; // used to avoid multiple onEnd() calls
  4217. this.chunks = []; // chunks of compressed data
  4218. this.strm = new ZStream();
  4219. this.strm.avail_out = 0;
  4220. var status = zlib_deflate.deflateInit2(
  4221. this.strm,
  4222. opt.level,
  4223. opt.method,
  4224. opt.windowBits,
  4225. opt.memLevel,
  4226. opt.strategy
  4227. );
  4228. if (status !== Z_OK) {
  4229. throw new Error(msg[status]);
  4230. }
  4231. if (opt.header) {
  4232. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  4233. }
  4234. if (opt.dictionary) {
  4235. var dict;
  4236. // Convert data if needed
  4237. if (typeof opt.dictionary === 'string') {
  4238. // If we need to compress text, change encoding to utf8.
  4239. dict = strings.string2buf(opt.dictionary);
  4240. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  4241. dict = new Uint8Array(opt.dictionary);
  4242. } else {
  4243. dict = opt.dictionary;
  4244. }
  4245. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  4246. if (status !== Z_OK) {
  4247. throw new Error(msg[status]);
  4248. }
  4249. this._dict_set = true;
  4250. }
  4251. }
  4252. /**
  4253. * Deflate#push(data[, mode]) -> Boolean
  4254. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  4255. * converted to utf8 byte sequence.
  4256. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4257. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4258. *
  4259. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  4260. * new compressed chunks. Returns `true` on success. The last data block must have
  4261. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4262. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4263. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  4264. *
  4265. * On fail call [[Deflate#onEnd]] with error code and return false.
  4266. *
  4267. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4268. * array format is detected automatically). Also, don't skip last param and always
  4269. * use the same type in your code (boolean or number). That will improve JS speed.
  4270. *
  4271. * For regular `Array`-s make sure all elements are [0..255].
  4272. *
  4273. * ##### Example
  4274. *
  4275. * ```javascript
  4276. * push(chunk, false); // push one of data chunks
  4277. * ...
  4278. * push(chunk, true); // push last chunk
  4279. * ```
  4280. **/
  4281. Deflate.prototype.push = function (data, mode) {
  4282. var strm = this.strm;
  4283. var chunkSize = this.options.chunkSize;
  4284. var status, _mode;
  4285. if (this.ended) { return false; }
  4286. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  4287. // Convert data if needed
  4288. if (typeof data === 'string') {
  4289. // If we need to compress text, change encoding to utf8.
  4290. strm.input = strings.string2buf(data);
  4291. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4292. strm.input = new Uint8Array(data);
  4293. } else {
  4294. strm.input = data;
  4295. }
  4296. strm.next_in = 0;
  4297. strm.avail_in = strm.input.length;
  4298. do {
  4299. if (strm.avail_out === 0) {
  4300. strm.output = new utils.Buf8(chunkSize);
  4301. strm.next_out = 0;
  4302. strm.avail_out = chunkSize;
  4303. }
  4304. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  4305. if (status !== Z_STREAM_END && status !== Z_OK) {
  4306. this.onEnd(status);
  4307. this.ended = true;
  4308. return false;
  4309. }
  4310. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  4311. if (this.options.to === 'string') {
  4312. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  4313. } else {
  4314. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4315. }
  4316. }
  4317. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  4318. // Finalize on the last chunk.
  4319. if (_mode === Z_FINISH) {
  4320. status = zlib_deflate.deflateEnd(this.strm);
  4321. this.onEnd(status);
  4322. this.ended = true;
  4323. return status === Z_OK;
  4324. }
  4325. // callback interim results if Z_SYNC_FLUSH.
  4326. if (_mode === Z_SYNC_FLUSH) {
  4327. this.onEnd(Z_OK);
  4328. strm.avail_out = 0;
  4329. return true;
  4330. }
  4331. return true;
  4332. };
  4333. /**
  4334. * Deflate#onData(chunk) -> Void
  4335. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4336. * on js engine support. When string output requested, each chunk
  4337. * will be string.
  4338. *
  4339. * By default, stores data blocks in `chunks[]` property and glue
  4340. * those in `onEnd`. Override this handler, if you need another behaviour.
  4341. **/
  4342. Deflate.prototype.onData = function (chunk) {
  4343. this.chunks.push(chunk);
  4344. };
  4345. /**
  4346. * Deflate#onEnd(status) -> Void
  4347. * - status (Number): deflate status. 0 (Z_OK) on success,
  4348. * other if not.
  4349. *
  4350. * Called once after you tell deflate that the input stream is
  4351. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4352. * or if an error happened. By default - join collected chunks,
  4353. * free memory and fill `results` / `err` properties.
  4354. **/
  4355. Deflate.prototype.onEnd = function (status) {
  4356. // On success - join
  4357. if (status === Z_OK) {
  4358. if (this.options.to === 'string') {
  4359. this.result = this.chunks.join('');
  4360. } else {
  4361. this.result = utils.flattenChunks(this.chunks);
  4362. }
  4363. }
  4364. this.chunks = [];
  4365. this.err = status;
  4366. this.msg = this.strm.msg;
  4367. };
  4368. /**
  4369. * deflate(data[, options]) -> Uint8Array|Array|String
  4370. * - data (Uint8Array|Array|String): input data to compress.
  4371. * - options (Object): zlib deflate options.
  4372. *
  4373. * Compress `data` with deflate algorithm and `options`.
  4374. *
  4375. * Supported options are:
  4376. *
  4377. * - level
  4378. * - windowBits
  4379. * - memLevel
  4380. * - strategy
  4381. * - dictionary
  4382. *
  4383. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4384. * for more information on these.
  4385. *
  4386. * Sugar (options):
  4387. *
  4388. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4389. * negative windowBits implicitly.
  4390. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4391. * (each char code [0..255])
  4392. *
  4393. * ##### Example:
  4394. *
  4395. * ```javascript
  4396. * var pako = require('pako')
  4397. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  4398. *
  4399. * console.log(pako.deflate(data));
  4400. * ```
  4401. **/
  4402. function deflate(input, options) {
  4403. var deflator = new Deflate(options);
  4404. deflator.push(input, true);
  4405. // That will never happens, if you don't cheat with options :)
  4406. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  4407. return deflator.result;
  4408. }
  4409. /**
  4410. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  4411. * - data (Uint8Array|Array|String): input data to compress.
  4412. * - options (Object): zlib deflate options.
  4413. *
  4414. * The same as [[deflate]], but creates raw data, without wrapper
  4415. * (header and adler32 crc).
  4416. **/
  4417. function deflateRaw(input, options) {
  4418. options = options || {};
  4419. options.raw = true;
  4420. return deflate(input, options);
  4421. }
  4422. /**
  4423. * gzip(data[, options]) -> Uint8Array|Array|String
  4424. * - data (Uint8Array|Array|String): input data to compress.
  4425. * - options (Object): zlib deflate options.
  4426. *
  4427. * The same as [[deflate]], but create gzip wrapper instead of
  4428. * deflate one.
  4429. **/
  4430. function gzip(input, options) {
  4431. options = options || {};
  4432. options.gzip = true;
  4433. return deflate(input, options);
  4434. }
  4435. exports.Deflate = Deflate;
  4436. exports.deflate = deflate;
  4437. exports.deflateRaw = deflateRaw;
  4438. exports.gzip = gzip;
  4439. },{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
  4440. 'use strict';
  4441. var zlib_inflate = require('./zlib/inflate');
  4442. var utils = require('./utils/common');
  4443. var strings = require('./utils/strings');
  4444. var c = require('./zlib/constants');
  4445. var msg = require('./zlib/messages');
  4446. var ZStream = require('./zlib/zstream');
  4447. var GZheader = require('./zlib/gzheader');
  4448. var toString = Object.prototype.toString;
  4449. /**
  4450. * class Inflate
  4451. *
  4452. * Generic JS-style wrapper for zlib calls. If you don't need
  4453. * streaming behaviour - use more simple functions: [[inflate]]
  4454. * and [[inflateRaw]].
  4455. **/
  4456. /* internal
  4457. * inflate.chunks -> Array
  4458. *
  4459. * Chunks of output data, if [[Inflate#onData]] not overriden.
  4460. **/
  4461. /**
  4462. * Inflate.result -> Uint8Array|Array|String
  4463. *
  4464. * Uncompressed result, generated by default [[Inflate#onData]]
  4465. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  4466. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  4467. * push a chunk with explicit flush (call [[Inflate#push]] with
  4468. * `Z_SYNC_FLUSH` param).
  4469. **/
  4470. /**
  4471. * Inflate.err -> Number
  4472. *
  4473. * Error code after inflate finished. 0 (Z_OK) on success.
  4474. * Should be checked if broken data possible.
  4475. **/
  4476. /**
  4477. * Inflate.msg -> String
  4478. *
  4479. * Error message, if [[Inflate.err]] != 0
  4480. **/
  4481. /**
  4482. * new Inflate(options)
  4483. * - options (Object): zlib inflate options.
  4484. *
  4485. * Creates new inflator instance with specified params. Throws exception
  4486. * on bad params. Supported options:
  4487. *
  4488. * - `windowBits`
  4489. * - `dictionary`
  4490. *
  4491. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4492. * for more information on these.
  4493. *
  4494. * Additional options, for internal needs:
  4495. *
  4496. * - `chunkSize` - size of generated data chunks (16K by default)
  4497. * - `raw` (Boolean) - do raw inflate
  4498. * - `to` (String) - if equal to 'string', then result will be converted
  4499. * from utf8 to utf16 (javascript) string. When string output requested,
  4500. * chunk length can differ from `chunkSize`, depending on content.
  4501. *
  4502. * By default, when no options set, autodetect deflate/gzip data format via
  4503. * wrapper header.
  4504. *
  4505. * ##### Example:
  4506. *
  4507. * ```javascript
  4508. * var pako = require('pako')
  4509. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4510. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4511. *
  4512. * var inflate = new pako.Inflate({ level: 3});
  4513. *
  4514. * inflate.push(chunk1, false);
  4515. * inflate.push(chunk2, true); // true -> last chunk
  4516. *
  4517. * if (inflate.err) { throw new Error(inflate.err); }
  4518. *
  4519. * console.log(inflate.result);
  4520. * ```
  4521. **/
  4522. function Inflate(options) {
  4523. if (!(this instanceof Inflate)) return new Inflate(options);
  4524. this.options = utils.assign({
  4525. chunkSize: 16384,
  4526. windowBits: 0,
  4527. to: ''
  4528. }, options || {});
  4529. var opt = this.options;
  4530. // Force window size for `raw` data, if not set directly,
  4531. // because we have no header for autodetect.
  4532. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  4533. opt.windowBits = -opt.windowBits;
  4534. if (opt.windowBits === 0) { opt.windowBits = -15; }
  4535. }
  4536. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  4537. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  4538. !(options && options.windowBits)) {
  4539. opt.windowBits += 32;
  4540. }
  4541. // Gzip header has no info about windows size, we can do autodetect only
  4542. // for deflate. So, if window size not set, force it to max when gzip possible
  4543. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  4544. // bit 3 (16) -> gzipped data
  4545. // bit 4 (32) -> autodetect gzip/deflate
  4546. if ((opt.windowBits & 15) === 0) {
  4547. opt.windowBits |= 15;
  4548. }
  4549. }
  4550. this.err = 0; // error code, if happens (0 = Z_OK)
  4551. this.msg = ''; // error message
  4552. this.ended = false; // used to avoid multiple onEnd() calls
  4553. this.chunks = []; // chunks of compressed data
  4554. this.strm = new ZStream();
  4555. this.strm.avail_out = 0;
  4556. var status = zlib_inflate.inflateInit2(
  4557. this.strm,
  4558. opt.windowBits
  4559. );
  4560. if (status !== c.Z_OK) {
  4561. throw new Error(msg[status]);
  4562. }
  4563. this.header = new GZheader();
  4564. zlib_inflate.inflateGetHeader(this.strm, this.header);
  4565. }
  4566. /**
  4567. * Inflate#push(data[, mode]) -> Boolean
  4568. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  4569. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4570. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4571. *
  4572. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  4573. * new output chunks. Returns `true` on success. The last data block must have
  4574. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4575. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4576. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  4577. *
  4578. * On fail call [[Inflate#onEnd]] with error code and return false.
  4579. *
  4580. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4581. * format is detected automatically). Also, don't skip last param and always
  4582. * use the same type in your code (boolean or number). That will improve JS speed.
  4583. *
  4584. * For regular `Array`-s make sure all elements are [0..255].
  4585. *
  4586. * ##### Example
  4587. *
  4588. * ```javascript
  4589. * push(chunk, false); // push one of data chunks
  4590. * ...
  4591. * push(chunk, true); // push last chunk
  4592. * ```
  4593. **/
  4594. Inflate.prototype.push = function (data, mode) {
  4595. var strm = this.strm;
  4596. var chunkSize = this.options.chunkSize;
  4597. var dictionary = this.options.dictionary;
  4598. var status, _mode;
  4599. var next_out_utf8, tail, utf8str;
  4600. var dict;
  4601. // Flag to properly process Z_BUF_ERROR on testing inflate call
  4602. // when we check that all output data was flushed.
  4603. var allowBufError = false;
  4604. if (this.ended) { return false; }
  4605. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  4606. // Convert data if needed
  4607. if (typeof data === 'string') {
  4608. // Only binary strings can be decompressed on practice
  4609. strm.input = strings.binstring2buf(data);
  4610. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4611. strm.input = new Uint8Array(data);
  4612. } else {
  4613. strm.input = data;
  4614. }
  4615. strm.next_in = 0;
  4616. strm.avail_in = strm.input.length;
  4617. do {
  4618. if (strm.avail_out === 0) {
  4619. strm.output = new utils.Buf8(chunkSize);
  4620. strm.next_out = 0;
  4621. strm.avail_out = chunkSize;
  4622. }
  4623. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  4624. if (status === c.Z_NEED_DICT && dictionary) {
  4625. // Convert data if needed
  4626. if (typeof dictionary === 'string') {
  4627. dict = strings.string2buf(dictionary);
  4628. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  4629. dict = new Uint8Array(dictionary);
  4630. } else {
  4631. dict = dictionary;
  4632. }
  4633. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  4634. }
  4635. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  4636. status = c.Z_OK;
  4637. allowBufError = false;
  4638. }
  4639. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  4640. this.onEnd(status);
  4641. this.ended = true;
  4642. return false;
  4643. }
  4644. if (strm.next_out) {
  4645. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  4646. if (this.options.to === 'string') {
  4647. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  4648. tail = strm.next_out - next_out_utf8;
  4649. utf8str = strings.buf2string(strm.output, next_out_utf8);
  4650. // move tail
  4651. strm.next_out = tail;
  4652. strm.avail_out = chunkSize - tail;
  4653. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  4654. this.onData(utf8str);
  4655. } else {
  4656. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4657. }
  4658. }
  4659. }
  4660. // When no more input data, we should check that internal inflate buffers
  4661. // are flushed. The only way to do it when avail_out = 0 - run one more
  4662. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  4663. // Here we set flag to process this error properly.
  4664. //
  4665. // NOTE. Deflate does not return error in this case and does not needs such
  4666. // logic.
  4667. if (strm.avail_in === 0 && strm.avail_out === 0) {
  4668. allowBufError = true;
  4669. }
  4670. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  4671. if (status === c.Z_STREAM_END) {
  4672. _mode = c.Z_FINISH;
  4673. }
  4674. // Finalize on the last chunk.
  4675. if (_mode === c.Z_FINISH) {
  4676. status = zlib_inflate.inflateEnd(this.strm);
  4677. this.onEnd(status);
  4678. this.ended = true;
  4679. return status === c.Z_OK;
  4680. }
  4681. // callback interim results if Z_SYNC_FLUSH.
  4682. if (_mode === c.Z_SYNC_FLUSH) {
  4683. this.onEnd(c.Z_OK);
  4684. strm.avail_out = 0;
  4685. return true;
  4686. }
  4687. return true;
  4688. };
  4689. /**
  4690. * Inflate#onData(chunk) -> Void
  4691. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4692. * on js engine support. When string output requested, each chunk
  4693. * will be string.
  4694. *
  4695. * By default, stores data blocks in `chunks[]` property and glue
  4696. * those in `onEnd`. Override this handler, if you need another behaviour.
  4697. **/
  4698. Inflate.prototype.onData = function (chunk) {
  4699. this.chunks.push(chunk);
  4700. };
  4701. /**
  4702. * Inflate#onEnd(status) -> Void
  4703. * - status (Number): inflate status. 0 (Z_OK) on success,
  4704. * other if not.
  4705. *
  4706. * Called either after you tell inflate that the input stream is
  4707. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4708. * or if an error happened. By default - join collected chunks,
  4709. * free memory and fill `results` / `err` properties.
  4710. **/
  4711. Inflate.prototype.onEnd = function (status) {
  4712. // On success - join
  4713. if (status === c.Z_OK) {
  4714. if (this.options.to === 'string') {
  4715. // Glue & convert here, until we teach pako to send
  4716. // utf8 alligned strings to onData
  4717. this.result = this.chunks.join('');
  4718. } else {
  4719. this.result = utils.flattenChunks(this.chunks);
  4720. }
  4721. }
  4722. this.chunks = [];
  4723. this.err = status;
  4724. this.msg = this.strm.msg;
  4725. };
  4726. /**
  4727. * inflate(data[, options]) -> Uint8Array|Array|String
  4728. * - data (Uint8Array|Array|String): input data to decompress.
  4729. * - options (Object): zlib inflate options.
  4730. *
  4731. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  4732. * format via wrapper header by default. That's why we don't provide
  4733. * separate `ungzip` method.
  4734. *
  4735. * Supported options are:
  4736. *
  4737. * - windowBits
  4738. *
  4739. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4740. * for more information.
  4741. *
  4742. * Sugar (options):
  4743. *
  4744. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4745. * negative windowBits implicitly.
  4746. * - `to` (String) - if equal to 'string', then result will be converted
  4747. * from utf8 to utf16 (javascript) string. When string output requested,
  4748. * chunk length can differ from `chunkSize`, depending on content.
  4749. *
  4750. *
  4751. * ##### Example:
  4752. *
  4753. * ```javascript
  4754. * var pako = require('pako')
  4755. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  4756. * , output;
  4757. *
  4758. * try {
  4759. * output = pako.inflate(input);
  4760. * } catch (err)
  4761. * console.log(err);
  4762. * }
  4763. * ```
  4764. **/
  4765. function inflate(input, options) {
  4766. var inflator = new Inflate(options);
  4767. inflator.push(input, true);
  4768. // That will never happens, if you don't cheat with options :)
  4769. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  4770. return inflator.result;
  4771. }
  4772. /**
  4773. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  4774. * - data (Uint8Array|Array|String): input data to decompress.
  4775. * - options (Object): zlib inflate options.
  4776. *
  4777. * The same as [[inflate]], but creates raw data, without wrapper
  4778. * (header and adler32 crc).
  4779. **/
  4780. function inflateRaw(input, options) {
  4781. options = options || {};
  4782. options.raw = true;
  4783. return inflate(input, options);
  4784. }
  4785. /**
  4786. * ungzip(data[, options]) -> Uint8Array|Array|String
  4787. * - data (Uint8Array|Array|String): input data to decompress.
  4788. * - options (Object): zlib inflate options.
  4789. *
  4790. * Just shortcut to [[inflate]], because it autodetects format
  4791. * by header.content. Done for convenience.
  4792. **/
  4793. exports.Inflate = Inflate;
  4794. exports.inflate = inflate;
  4795. exports.inflateRaw = inflateRaw;
  4796. exports.ungzip = inflate;
  4797. },{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(require,module,exports){
  4798. 'use strict';
  4799. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  4800. (typeof Uint16Array !== 'undefined') &&
  4801. (typeof Int32Array !== 'undefined');
  4802. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  4803. var sources = Array.prototype.slice.call(arguments, 1);
  4804. while (sources.length) {
  4805. var source = sources.shift();
  4806. if (!source) { continue; }
  4807. if (typeof source !== 'object') {
  4808. throw new TypeError(source + 'must be non-object');
  4809. }
  4810. for (var p in source) {
  4811. if (source.hasOwnProperty(p)) {
  4812. obj[p] = source[p];
  4813. }
  4814. }
  4815. }
  4816. return obj;
  4817. };
  4818. // reduce buffer size, avoiding mem copy
  4819. exports.shrinkBuf = function (buf, size) {
  4820. if (buf.length === size) { return buf; }
  4821. if (buf.subarray) { return buf.subarray(0, size); }
  4822. buf.length = size;
  4823. return buf;
  4824. };
  4825. var fnTyped = {
  4826. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4827. if (src.subarray && dest.subarray) {
  4828. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  4829. return;
  4830. }
  4831. // Fallback to ordinary array
  4832. for (var i = 0; i < len; i++) {
  4833. dest[dest_offs + i] = src[src_offs + i];
  4834. }
  4835. },
  4836. // Join array of chunks to single array.
  4837. flattenChunks: function (chunks) {
  4838. var i, l, len, pos, chunk, result;
  4839. // calculate data length
  4840. len = 0;
  4841. for (i = 0, l = chunks.length; i < l; i++) {
  4842. len += chunks[i].length;
  4843. }
  4844. // join chunks
  4845. result = new Uint8Array(len);
  4846. pos = 0;
  4847. for (i = 0, l = chunks.length; i < l; i++) {
  4848. chunk = chunks[i];
  4849. result.set(chunk, pos);
  4850. pos += chunk.length;
  4851. }
  4852. return result;
  4853. }
  4854. };
  4855. var fnUntyped = {
  4856. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4857. for (var i = 0; i < len; i++) {
  4858. dest[dest_offs + i] = src[src_offs + i];
  4859. }
  4860. },
  4861. // Join array of chunks to single array.
  4862. flattenChunks: function (chunks) {
  4863. return [].concat.apply([], chunks);
  4864. }
  4865. };
  4866. // Enable/Disable typed arrays use, for testing
  4867. //
  4868. exports.setTyped = function (on) {
  4869. if (on) {
  4870. exports.Buf8 = Uint8Array;
  4871. exports.Buf16 = Uint16Array;
  4872. exports.Buf32 = Int32Array;
  4873. exports.assign(exports, fnTyped);
  4874. } else {
  4875. exports.Buf8 = Array;
  4876. exports.Buf16 = Array;
  4877. exports.Buf32 = Array;
  4878. exports.assign(exports, fnUntyped);
  4879. }
  4880. };
  4881. exports.setTyped(TYPED_OK);
  4882. },{}],42:[function(require,module,exports){
  4883. // String encode/decode helpers
  4884. 'use strict';
  4885. var utils = require('./common');
  4886. // Quick check if we can use fast array to bin string conversion
  4887. //
  4888. // - apply(Array) can fail on Android 2.2
  4889. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  4890. //
  4891. var STR_APPLY_OK = true;
  4892. var STR_APPLY_UIA_OK = true;
  4893. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  4894. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  4895. // Table with utf8 lengths (calculated by first byte of sequence)
  4896. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4897. // because max possible codepoint is 0x10ffff
  4898. var _utf8len = new utils.Buf8(256);
  4899. for (var q = 0; q < 256; q++) {
  4900. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  4901. }
  4902. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  4903. // convert string to array (typed, when possible)
  4904. exports.string2buf = function (str) {
  4905. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4906. // count binary size
  4907. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4908. c = str.charCodeAt(m_pos);
  4909. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4910. c2 = str.charCodeAt(m_pos + 1);
  4911. if ((c2 & 0xfc00) === 0xdc00) {
  4912. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4913. m_pos++;
  4914. }
  4915. }
  4916. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4917. }
  4918. // allocate buffer
  4919. buf = new utils.Buf8(buf_len);
  4920. // convert
  4921. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  4922. c = str.charCodeAt(m_pos);
  4923. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4924. c2 = str.charCodeAt(m_pos + 1);
  4925. if ((c2 & 0xfc00) === 0xdc00) {
  4926. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4927. m_pos++;
  4928. }
  4929. }
  4930. if (c < 0x80) {
  4931. /* one byte */
  4932. buf[i++] = c;
  4933. } else if (c < 0x800) {
  4934. /* two bytes */
  4935. buf[i++] = 0xC0 | (c >>> 6);
  4936. buf[i++] = 0x80 | (c & 0x3f);
  4937. } else if (c < 0x10000) {
  4938. /* three bytes */
  4939. buf[i++] = 0xE0 | (c >>> 12);
  4940. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4941. buf[i++] = 0x80 | (c & 0x3f);
  4942. } else {
  4943. /* four bytes */
  4944. buf[i++] = 0xf0 | (c >>> 18);
  4945. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  4946. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4947. buf[i++] = 0x80 | (c & 0x3f);
  4948. }
  4949. }
  4950. return buf;
  4951. };
  4952. // Helper (used in 2 places)
  4953. function buf2binstring(buf, len) {
  4954. // use fallback for big arrays to avoid stack overflow
  4955. if (len < 65537) {
  4956. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  4957. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  4958. }
  4959. }
  4960. var result = '';
  4961. for (var i = 0; i < len; i++) {
  4962. result += String.fromCharCode(buf[i]);
  4963. }
  4964. return result;
  4965. }
  4966. // Convert byte array to binary string
  4967. exports.buf2binstring = function (buf) {
  4968. return buf2binstring(buf, buf.length);
  4969. };
  4970. // Convert binary string (typed, when possible)
  4971. exports.binstring2buf = function (str) {
  4972. var buf = new utils.Buf8(str.length);
  4973. for (var i = 0, len = buf.length; i < len; i++) {
  4974. buf[i] = str.charCodeAt(i);
  4975. }
  4976. return buf;
  4977. };
  4978. // convert array to string
  4979. exports.buf2string = function (buf, max) {
  4980. var i, out, c, c_len;
  4981. var len = max || buf.length;
  4982. // Reserve max possible length (2 words per char)
  4983. // NB: by unknown reasons, Array is significantly faster for
  4984. // String.fromCharCode.apply than Uint16Array.
  4985. var utf16buf = new Array(len * 2);
  4986. for (out = 0, i = 0; i < len;) {
  4987. c = buf[i++];
  4988. // quick process ascii
  4989. if (c < 0x80) { utf16buf[out++] = c; continue; }
  4990. c_len = _utf8len[c];
  4991. // skip 5 & 6 byte codes
  4992. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  4993. // apply mask on first byte
  4994. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  4995. // join the rest
  4996. while (c_len > 1 && i < len) {
  4997. c = (c << 6) | (buf[i++] & 0x3f);
  4998. c_len--;
  4999. }
  5000. // terminated by end of string?
  5001. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5002. if (c < 0x10000) {
  5003. utf16buf[out++] = c;
  5004. } else {
  5005. c -= 0x10000;
  5006. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5007. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5008. }
  5009. }
  5010. return buf2binstring(utf16buf, out);
  5011. };
  5012. // Calculate max possible position in utf8 buffer,
  5013. // that will not break sequence. If that's not possible
  5014. // - (very small limits) return max size as is.
  5015. //
  5016. // buf[] - utf8 bytes array
  5017. // max - length limit (mandatory);
  5018. exports.utf8border = function (buf, max) {
  5019. var pos;
  5020. max = max || buf.length;
  5021. if (max > buf.length) { max = buf.length; }
  5022. // go back from last position, until start of sequence found
  5023. pos = max - 1;
  5024. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5025. // Fuckup - very small and broken sequence,
  5026. // return max, because we should return something anyway.
  5027. if (pos < 0) { return max; }
  5028. // If we came to start of buffer - that means vuffer is too small,
  5029. // return max too.
  5030. if (pos === 0) { return max; }
  5031. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5032. };
  5033. },{"./common":41}],43:[function(require,module,exports){
  5034. 'use strict';
  5035. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5036. // It doesn't worth to make additional optimizationa as in original.
  5037. // Small size is preferable.
  5038. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5039. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5040. //
  5041. // This software is provided 'as-is', without any express or implied
  5042. // warranty. In no event will the authors be held liable for any damages
  5043. // arising from the use of this software.
  5044. //
  5045. // Permission is granted to anyone to use this software for any purpose,
  5046. // including commercial applications, and to alter it and redistribute it
  5047. // freely, subject to the following restrictions:
  5048. //
  5049. // 1. The origin of this software must not be misrepresented; you must not
  5050. // claim that you wrote the original software. If you use this software
  5051. // in a product, an acknowledgment in the product documentation would be
  5052. // appreciated but is not required.
  5053. // 2. Altered source versions must be plainly marked as such, and must not be
  5054. // misrepresented as being the original software.
  5055. // 3. This notice may not be removed or altered from any source distribution.
  5056. function adler32(adler, buf, len, pos) {
  5057. var s1 = (adler & 0xffff) |0,
  5058. s2 = ((adler >>> 16) & 0xffff) |0,
  5059. n = 0;
  5060. while (len !== 0) {
  5061. // Set limit ~ twice less than 5552, to keep
  5062. // s2 in 31-bits, because we force signed ints.
  5063. // in other case %= will fail.
  5064. n = len > 2000 ? 2000 : len;
  5065. len -= n;
  5066. do {
  5067. s1 = (s1 + buf[pos++]) |0;
  5068. s2 = (s2 + s1) |0;
  5069. } while (--n);
  5070. s1 %= 65521;
  5071. s2 %= 65521;
  5072. }
  5073. return (s1 | (s2 << 16)) |0;
  5074. }
  5075. module.exports = adler32;
  5076. },{}],44:[function(require,module,exports){
  5077. 'use strict';
  5078. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5079. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5080. //
  5081. // This software is provided 'as-is', without any express or implied
  5082. // warranty. In no event will the authors be held liable for any damages
  5083. // arising from the use of this software.
  5084. //
  5085. // Permission is granted to anyone to use this software for any purpose,
  5086. // including commercial applications, and to alter it and redistribute it
  5087. // freely, subject to the following restrictions:
  5088. //
  5089. // 1. The origin of this software must not be misrepresented; you must not
  5090. // claim that you wrote the original software. If you use this software
  5091. // in a product, an acknowledgment in the product documentation would be
  5092. // appreciated but is not required.
  5093. // 2. Altered source versions must be plainly marked as such, and must not be
  5094. // misrepresented as being the original software.
  5095. // 3. This notice may not be removed or altered from any source distribution.
  5096. module.exports = {
  5097. /* Allowed flush values; see deflate() and inflate() below for details */
  5098. Z_NO_FLUSH: 0,
  5099. Z_PARTIAL_FLUSH: 1,
  5100. Z_SYNC_FLUSH: 2,
  5101. Z_FULL_FLUSH: 3,
  5102. Z_FINISH: 4,
  5103. Z_BLOCK: 5,
  5104. Z_TREES: 6,
  5105. /* Return codes for the compression/decompression functions. Negative values
  5106. * are errors, positive values are used for special but normal events.
  5107. */
  5108. Z_OK: 0,
  5109. Z_STREAM_END: 1,
  5110. Z_NEED_DICT: 2,
  5111. Z_ERRNO: -1,
  5112. Z_STREAM_ERROR: -2,
  5113. Z_DATA_ERROR: -3,
  5114. //Z_MEM_ERROR: -4,
  5115. Z_BUF_ERROR: -5,
  5116. //Z_VERSION_ERROR: -6,
  5117. /* compression levels */
  5118. Z_NO_COMPRESSION: 0,
  5119. Z_BEST_SPEED: 1,
  5120. Z_BEST_COMPRESSION: 9,
  5121. Z_DEFAULT_COMPRESSION: -1,
  5122. Z_FILTERED: 1,
  5123. Z_HUFFMAN_ONLY: 2,
  5124. Z_RLE: 3,
  5125. Z_FIXED: 4,
  5126. Z_DEFAULT_STRATEGY: 0,
  5127. /* Possible values of the data_type field (though see inflate()) */
  5128. Z_BINARY: 0,
  5129. Z_TEXT: 1,
  5130. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5131. Z_UNKNOWN: 2,
  5132. /* The deflate compression method */
  5133. Z_DEFLATED: 8
  5134. //Z_NULL: null // Use -1 or null inline, depending on var type
  5135. };
  5136. },{}],45:[function(require,module,exports){
  5137. 'use strict';
  5138. // Note: we can't get significant speed boost here.
  5139. // So write code to minimize size - no pregenerated tables
  5140. // and array tools dependencies.
  5141. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5142. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5143. //
  5144. // This software is provided 'as-is', without any express or implied
  5145. // warranty. In no event will the authors be held liable for any damages
  5146. // arising from the use of this software.
  5147. //
  5148. // Permission is granted to anyone to use this software for any purpose,
  5149. // including commercial applications, and to alter it and redistribute it
  5150. // freely, subject to the following restrictions:
  5151. //
  5152. // 1. The origin of this software must not be misrepresented; you must not
  5153. // claim that you wrote the original software. If you use this software
  5154. // in a product, an acknowledgment in the product documentation would be
  5155. // appreciated but is not required.
  5156. // 2. Altered source versions must be plainly marked as such, and must not be
  5157. // misrepresented as being the original software.
  5158. // 3. This notice may not be removed or altered from any source distribution.
  5159. // Use ordinary array, since untyped makes no boost here
  5160. function makeTable() {
  5161. var c, table = [];
  5162. for (var n = 0; n < 256; n++) {
  5163. c = n;
  5164. for (var k = 0; k < 8; k++) {
  5165. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5166. }
  5167. table[n] = c;
  5168. }
  5169. return table;
  5170. }
  5171. // Create table on load. Just 255 signed longs. Not a problem.
  5172. var crcTable = makeTable();
  5173. function crc32(crc, buf, len, pos) {
  5174. var t = crcTable,
  5175. end = pos + len;
  5176. crc ^= -1;
  5177. for (var i = pos; i < end; i++) {
  5178. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5179. }
  5180. return (crc ^ (-1)); // >>> 0;
  5181. }
  5182. module.exports = crc32;
  5183. },{}],46:[function(require,module,exports){
  5184. 'use strict';
  5185. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5186. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5187. //
  5188. // This software is provided 'as-is', without any express or implied
  5189. // warranty. In no event will the authors be held liable for any damages
  5190. // arising from the use of this software.
  5191. //
  5192. // Permission is granted to anyone to use this software for any purpose,
  5193. // including commercial applications, and to alter it and redistribute it
  5194. // freely, subject to the following restrictions:
  5195. //
  5196. // 1. The origin of this software must not be misrepresented; you must not
  5197. // claim that you wrote the original software. If you use this software
  5198. // in a product, an acknowledgment in the product documentation would be
  5199. // appreciated but is not required.
  5200. // 2. Altered source versions must be plainly marked as such, and must not be
  5201. // misrepresented as being the original software.
  5202. // 3. This notice may not be removed or altered from any source distribution.
  5203. var utils = require('../utils/common');
  5204. var trees = require('./trees');
  5205. var adler32 = require('./adler32');
  5206. var crc32 = require('./crc32');
  5207. var msg = require('./messages');
  5208. /* Public constants ==========================================================*/
  5209. /* ===========================================================================*/
  5210. /* Allowed flush values; see deflate() and inflate() below for details */
  5211. var Z_NO_FLUSH = 0;
  5212. var Z_PARTIAL_FLUSH = 1;
  5213. //var Z_SYNC_FLUSH = 2;
  5214. var Z_FULL_FLUSH = 3;
  5215. var Z_FINISH = 4;
  5216. var Z_BLOCK = 5;
  5217. //var Z_TREES = 6;
  5218. /* Return codes for the compression/decompression functions. Negative values
  5219. * are errors, positive values are used for special but normal events.
  5220. */
  5221. var Z_OK = 0;
  5222. var Z_STREAM_END = 1;
  5223. //var Z_NEED_DICT = 2;
  5224. //var Z_ERRNO = -1;
  5225. var Z_STREAM_ERROR = -2;
  5226. var Z_DATA_ERROR = -3;
  5227. //var Z_MEM_ERROR = -4;
  5228. var Z_BUF_ERROR = -5;
  5229. //var Z_VERSION_ERROR = -6;
  5230. /* compression levels */
  5231. //var Z_NO_COMPRESSION = 0;
  5232. //var Z_BEST_SPEED = 1;
  5233. //var Z_BEST_COMPRESSION = 9;
  5234. var Z_DEFAULT_COMPRESSION = -1;
  5235. var Z_FILTERED = 1;
  5236. var Z_HUFFMAN_ONLY = 2;
  5237. var Z_RLE = 3;
  5238. var Z_FIXED = 4;
  5239. var Z_DEFAULT_STRATEGY = 0;
  5240. /* Possible values of the data_type field (though see inflate()) */
  5241. //var Z_BINARY = 0;
  5242. //var Z_TEXT = 1;
  5243. //var Z_ASCII = 1; // = Z_TEXT
  5244. var Z_UNKNOWN = 2;
  5245. /* The deflate compression method */
  5246. var Z_DEFLATED = 8;
  5247. /*============================================================================*/
  5248. var MAX_MEM_LEVEL = 9;
  5249. /* Maximum value for memLevel in deflateInit2 */
  5250. var MAX_WBITS = 15;
  5251. /* 32K LZ77 window */
  5252. var DEF_MEM_LEVEL = 8;
  5253. var LENGTH_CODES = 29;
  5254. /* number of length codes, not counting the special END_BLOCK code */
  5255. var LITERALS = 256;
  5256. /* number of literal bytes 0..255 */
  5257. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  5258. /* number of Literal or Length codes, including the END_BLOCK code */
  5259. var D_CODES = 30;
  5260. /* number of distance codes */
  5261. var BL_CODES = 19;
  5262. /* number of codes used to transfer the bit lengths */
  5263. var HEAP_SIZE = 2 * L_CODES + 1;
  5264. /* maximum heap size */
  5265. var MAX_BITS = 15;
  5266. /* All codes must not exceed MAX_BITS bits */
  5267. var MIN_MATCH = 3;
  5268. var MAX_MATCH = 258;
  5269. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  5270. var PRESET_DICT = 0x20;
  5271. var INIT_STATE = 42;
  5272. var EXTRA_STATE = 69;
  5273. var NAME_STATE = 73;
  5274. var COMMENT_STATE = 91;
  5275. var HCRC_STATE = 103;
  5276. var BUSY_STATE = 113;
  5277. var FINISH_STATE = 666;
  5278. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  5279. var BS_BLOCK_DONE = 2; /* block flush performed */
  5280. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  5281. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  5282. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  5283. function err(strm, errorCode) {
  5284. strm.msg = msg[errorCode];
  5285. return errorCode;
  5286. }
  5287. function rank(f) {
  5288. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  5289. }
  5290. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  5291. /* =========================================================================
  5292. * Flush as much pending output as possible. All deflate() output goes
  5293. * through this function so some applications may wish to modify it
  5294. * to avoid allocating a large strm->output buffer and copying into it.
  5295. * (See also read_buf()).
  5296. */
  5297. function flush_pending(strm) {
  5298. var s = strm.state;
  5299. //_tr_flush_bits(s);
  5300. var len = s.pending;
  5301. if (len > strm.avail_out) {
  5302. len = strm.avail_out;
  5303. }
  5304. if (len === 0) { return; }
  5305. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  5306. strm.next_out += len;
  5307. s.pending_out += len;
  5308. strm.total_out += len;
  5309. strm.avail_out -= len;
  5310. s.pending -= len;
  5311. if (s.pending === 0) {
  5312. s.pending_out = 0;
  5313. }
  5314. }
  5315. function flush_block_only(s, last) {
  5316. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  5317. s.block_start = s.strstart;
  5318. flush_pending(s.strm);
  5319. }
  5320. function put_byte(s, b) {
  5321. s.pending_buf[s.pending++] = b;
  5322. }
  5323. /* =========================================================================
  5324. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  5325. * IN assertion: the stream state is correct and there is enough room in
  5326. * pending_buf.
  5327. */
  5328. function putShortMSB(s, b) {
  5329. // put_byte(s, (Byte)(b >> 8));
  5330. // put_byte(s, (Byte)(b & 0xff));
  5331. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  5332. s.pending_buf[s.pending++] = b & 0xff;
  5333. }
  5334. /* ===========================================================================
  5335. * Read a new buffer from the current input stream, update the adler32
  5336. * and total number of bytes read. All deflate() input goes through
  5337. * this function so some applications may wish to modify it to avoid
  5338. * allocating a large strm->input buffer and copying from it.
  5339. * (See also flush_pending()).
  5340. */
  5341. function read_buf(strm, buf, start, size) {
  5342. var len = strm.avail_in;
  5343. if (len > size) { len = size; }
  5344. if (len === 0) { return 0; }
  5345. strm.avail_in -= len;
  5346. // zmemcpy(buf, strm->next_in, len);
  5347. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  5348. if (strm.state.wrap === 1) {
  5349. strm.adler = adler32(strm.adler, buf, len, start);
  5350. }
  5351. else if (strm.state.wrap === 2) {
  5352. strm.adler = crc32(strm.adler, buf, len, start);
  5353. }
  5354. strm.next_in += len;
  5355. strm.total_in += len;
  5356. return len;
  5357. }
  5358. /* ===========================================================================
  5359. * Set match_start to the longest match starting at the given string and
  5360. * return its length. Matches shorter or equal to prev_length are discarded,
  5361. * in which case the result is equal to prev_length and match_start is
  5362. * garbage.
  5363. * IN assertions: cur_match is the head of the hash chain for the current
  5364. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  5365. * OUT assertion: the match length is not greater than s->lookahead.
  5366. */
  5367. function longest_match(s, cur_match) {
  5368. var chain_length = s.max_chain_length; /* max hash chain length */
  5369. var scan = s.strstart; /* current string */
  5370. var match; /* matched string */
  5371. var len; /* length of current match */
  5372. var best_len = s.prev_length; /* best match length so far */
  5373. var nice_match = s.nice_match; /* stop if match long enough */
  5374. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  5375. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  5376. var _win = s.window; // shortcut
  5377. var wmask = s.w_mask;
  5378. var prev = s.prev;
  5379. /* Stop when cur_match becomes <= limit. To simplify the code,
  5380. * we prevent matches with the string of window index 0.
  5381. */
  5382. var strend = s.strstart + MAX_MATCH;
  5383. var scan_end1 = _win[scan + best_len - 1];
  5384. var scan_end = _win[scan + best_len];
  5385. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  5386. * It is easy to get rid of this optimization if necessary.
  5387. */
  5388. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  5389. /* Do not waste too much time if we already have a good match: */
  5390. if (s.prev_length >= s.good_match) {
  5391. chain_length >>= 2;
  5392. }
  5393. /* Do not look for matches beyond the end of the input. This is necessary
  5394. * to make deflate deterministic.
  5395. */
  5396. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  5397. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  5398. do {
  5399. // Assert(cur_match < s->strstart, "no future");
  5400. match = cur_match;
  5401. /* Skip to next match if the match length cannot increase
  5402. * or if the match length is less than 2. Note that the checks below
  5403. * for insufficient lookahead only occur occasionally for performance
  5404. * reasons. Therefore uninitialized memory will be accessed, and
  5405. * conditional jumps will be made that depend on those values.
  5406. * However the length of the match is limited to the lookahead, so
  5407. * the output of deflate is not affected by the uninitialized values.
  5408. */
  5409. if (_win[match + best_len] !== scan_end ||
  5410. _win[match + best_len - 1] !== scan_end1 ||
  5411. _win[match] !== _win[scan] ||
  5412. _win[++match] !== _win[scan + 1]) {
  5413. continue;
  5414. }
  5415. /* The check at best_len-1 can be removed because it will be made
  5416. * again later. (This heuristic is not always a win.)
  5417. * It is not necessary to compare scan[2] and match[2] since they
  5418. * are always equal when the other bytes match, given that
  5419. * the hash keys are equal and that HASH_BITS >= 8.
  5420. */
  5421. scan += 2;
  5422. match++;
  5423. // Assert(*scan == *match, "match[2]?");
  5424. /* We check for insufficient lookahead only every 8th comparison;
  5425. * the 256th check will be made at strstart+258.
  5426. */
  5427. do {
  5428. /*jshint noempty:false*/
  5429. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5430. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5431. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5432. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5433. scan < strend);
  5434. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  5435. len = MAX_MATCH - (strend - scan);
  5436. scan = strend - MAX_MATCH;
  5437. if (len > best_len) {
  5438. s.match_start = cur_match;
  5439. best_len = len;
  5440. if (len >= nice_match) {
  5441. break;
  5442. }
  5443. scan_end1 = _win[scan + best_len - 1];
  5444. scan_end = _win[scan + best_len];
  5445. }
  5446. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  5447. if (best_len <= s.lookahead) {
  5448. return best_len;
  5449. }
  5450. return s.lookahead;
  5451. }
  5452. /* ===========================================================================
  5453. * Fill the window when the lookahead becomes insufficient.
  5454. * Updates strstart and lookahead.
  5455. *
  5456. * IN assertion: lookahead < MIN_LOOKAHEAD
  5457. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  5458. * At least one byte has been read, or avail_in == 0; reads are
  5459. * performed for at least two bytes (required for the zip translate_eol
  5460. * option -- not supported here).
  5461. */
  5462. function fill_window(s) {
  5463. var _w_size = s.w_size;
  5464. var p, n, m, more, str;
  5465. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  5466. do {
  5467. more = s.window_size - s.lookahead - s.strstart;
  5468. // JS ints have 32 bit, block below not needed
  5469. /* Deal with !@#$% 64K limit: */
  5470. //if (sizeof(int) <= 2) {
  5471. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  5472. // more = wsize;
  5473. //
  5474. // } else if (more == (unsigned)(-1)) {
  5475. // /* Very unlikely, but possible on 16 bit machine if
  5476. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  5477. // */
  5478. // more--;
  5479. // }
  5480. //}
  5481. /* If the window is almost full and there is insufficient lookahead,
  5482. * move the upper half to the lower one to make room in the upper half.
  5483. */
  5484. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  5485. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  5486. s.match_start -= _w_size;
  5487. s.strstart -= _w_size;
  5488. /* we now have strstart >= MAX_DIST */
  5489. s.block_start -= _w_size;
  5490. /* Slide the hash table (could be avoided with 32 bit values
  5491. at the expense of memory usage). We slide even when level == 0
  5492. to keep the hash table consistent if we switch back to level > 0
  5493. later. (Using level 0 permanently is not an optimal usage of
  5494. zlib, so we don't care about this pathological case.)
  5495. */
  5496. n = s.hash_size;
  5497. p = n;
  5498. do {
  5499. m = s.head[--p];
  5500. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  5501. } while (--n);
  5502. n = _w_size;
  5503. p = n;
  5504. do {
  5505. m = s.prev[--p];
  5506. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  5507. /* If n is not on any hash chain, prev[n] is garbage but
  5508. * its value will never be used.
  5509. */
  5510. } while (--n);
  5511. more += _w_size;
  5512. }
  5513. if (s.strm.avail_in === 0) {
  5514. break;
  5515. }
  5516. /* If there was no sliding:
  5517. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  5518. * more == window_size - lookahead - strstart
  5519. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  5520. * => more >= window_size - 2*WSIZE + 2
  5521. * In the BIG_MEM or MMAP case (not yet supported),
  5522. * window_size == input_size + MIN_LOOKAHEAD &&
  5523. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  5524. * Otherwise, window_size == 2*WSIZE so more >= 2.
  5525. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  5526. */
  5527. //Assert(more >= 2, "more < 2");
  5528. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  5529. s.lookahead += n;
  5530. /* Initialize the hash value now that we have some input: */
  5531. if (s.lookahead + s.insert >= MIN_MATCH) {
  5532. str = s.strstart - s.insert;
  5533. s.ins_h = s.window[str];
  5534. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  5535. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  5536. //#if MIN_MATCH != 3
  5537. // Call update_hash() MIN_MATCH-3 more times
  5538. //#endif
  5539. while (s.insert) {
  5540. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  5541. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  5542. s.prev[str & s.w_mask] = s.head[s.ins_h];
  5543. s.head[s.ins_h] = str;
  5544. str++;
  5545. s.insert--;
  5546. if (s.lookahead + s.insert < MIN_MATCH) {
  5547. break;
  5548. }
  5549. }
  5550. }
  5551. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  5552. * but this is not important since only literal bytes will be emitted.
  5553. */
  5554. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  5555. /* If the WIN_INIT bytes after the end of the current data have never been
  5556. * written, then zero those bytes in order to avoid memory check reports of
  5557. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  5558. * the longest match routines. Update the high water mark for the next
  5559. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  5560. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  5561. */
  5562. // if (s.high_water < s.window_size) {
  5563. // var curr = s.strstart + s.lookahead;
  5564. // var init = 0;
  5565. //
  5566. // if (s.high_water < curr) {
  5567. // /* Previous high water mark below current data -- zero WIN_INIT
  5568. // * bytes or up to end of window, whichever is less.
  5569. // */
  5570. // init = s.window_size - curr;
  5571. // if (init > WIN_INIT)
  5572. // init = WIN_INIT;
  5573. // zmemzero(s->window + curr, (unsigned)init);
  5574. // s->high_water = curr + init;
  5575. // }
  5576. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  5577. // /* High water mark at or above current data, but below current data
  5578. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  5579. // * to end of window, whichever is less.
  5580. // */
  5581. // init = (ulg)curr + WIN_INIT - s->high_water;
  5582. // if (init > s->window_size - s->high_water)
  5583. // init = s->window_size - s->high_water;
  5584. // zmemzero(s->window + s->high_water, (unsigned)init);
  5585. // s->high_water += init;
  5586. // }
  5587. // }
  5588. //
  5589. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  5590. // "not enough room for search");
  5591. }
  5592. /* ===========================================================================
  5593. * Copy without compression as much as possible from the input stream, return
  5594. * the current block state.
  5595. * This function does not insert new strings in the dictionary since
  5596. * uncompressible data is probably not useful. This function is used
  5597. * only for the level=0 compression option.
  5598. * NOTE: this function should be optimized to avoid extra copying from
  5599. * window to pending_buf.
  5600. */
  5601. function deflate_stored(s, flush) {
  5602. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  5603. * to pending_buf_size, and each stored block has a 5 byte header:
  5604. */
  5605. var max_block_size = 0xffff;
  5606. if (max_block_size > s.pending_buf_size - 5) {
  5607. max_block_size = s.pending_buf_size - 5;
  5608. }
  5609. /* Copy as much as possible from input to output: */
  5610. for (;;) {
  5611. /* Fill the window as much as possible: */
  5612. if (s.lookahead <= 1) {
  5613. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  5614. // s->block_start >= (long)s->w_size, "slide too late");
  5615. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  5616. // s.block_start >= s.w_size)) {
  5617. // throw new Error("slide too late");
  5618. // }
  5619. fill_window(s);
  5620. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  5621. return BS_NEED_MORE;
  5622. }
  5623. if (s.lookahead === 0) {
  5624. break;
  5625. }
  5626. /* flush the current block */
  5627. }
  5628. //Assert(s->block_start >= 0L, "block gone");
  5629. // if (s.block_start < 0) throw new Error("block gone");
  5630. s.strstart += s.lookahead;
  5631. s.lookahead = 0;
  5632. /* Emit a stored block if pending_buf will be full: */
  5633. var max_start = s.block_start + max_block_size;
  5634. if (s.strstart === 0 || s.strstart >= max_start) {
  5635. /* strstart == 0 is possible when wraparound on 16-bit machine */
  5636. s.lookahead = s.strstart - max_start;
  5637. s.strstart = max_start;
  5638. /*** FLUSH_BLOCK(s, 0); ***/
  5639. flush_block_only(s, false);
  5640. if (s.strm.avail_out === 0) {
  5641. return BS_NEED_MORE;
  5642. }
  5643. /***/
  5644. }
  5645. /* Flush if we may have to slide, otherwise block_start may become
  5646. * negative and the data will be gone:
  5647. */
  5648. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  5649. /*** FLUSH_BLOCK(s, 0); ***/
  5650. flush_block_only(s, false);
  5651. if (s.strm.avail_out === 0) {
  5652. return BS_NEED_MORE;
  5653. }
  5654. /***/
  5655. }
  5656. }
  5657. s.insert = 0;
  5658. if (flush === Z_FINISH) {
  5659. /*** FLUSH_BLOCK(s, 1); ***/
  5660. flush_block_only(s, true);
  5661. if (s.strm.avail_out === 0) {
  5662. return BS_FINISH_STARTED;
  5663. }
  5664. /***/
  5665. return BS_FINISH_DONE;
  5666. }
  5667. if (s.strstart > s.block_start) {
  5668. /*** FLUSH_BLOCK(s, 0); ***/
  5669. flush_block_only(s, false);
  5670. if (s.strm.avail_out === 0) {
  5671. return BS_NEED_MORE;
  5672. }
  5673. /***/
  5674. }
  5675. return BS_NEED_MORE;
  5676. }
  5677. /* ===========================================================================
  5678. * Compress as much as possible from the input stream, return the current
  5679. * block state.
  5680. * This function does not perform lazy evaluation of matches and inserts
  5681. * new strings in the dictionary only for unmatched strings or for short
  5682. * matches. It is used only for the fast compression options.
  5683. */
  5684. function deflate_fast(s, flush) {
  5685. var hash_head; /* head of the hash chain */
  5686. var bflush; /* set if current block must be flushed */
  5687. for (;;) {
  5688. /* Make sure that we always have enough lookahead, except
  5689. * at the end of the input file. We need MAX_MATCH bytes
  5690. * for the next match, plus MIN_MATCH bytes to insert the
  5691. * string following the next match.
  5692. */
  5693. if (s.lookahead < MIN_LOOKAHEAD) {
  5694. fill_window(s);
  5695. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  5696. return BS_NEED_MORE;
  5697. }
  5698. if (s.lookahead === 0) {
  5699. break; /* flush the current block */
  5700. }
  5701. }
  5702. /* Insert the string window[strstart .. strstart+2] in the
  5703. * dictionary, and set hash_head to the head of the hash chain:
  5704. */
  5705. hash_head = 0/*NIL*/;
  5706. if (s.lookahead >= MIN_MATCH) {
  5707. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5708. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5709. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5710. s.head[s.ins_h] = s.strstart;
  5711. /***/
  5712. }
  5713. /* Find the longest match, discarding those <= prev_length.
  5714. * At this point we have always match_length < MIN_MATCH
  5715. */
  5716. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  5717. /* To simplify the code, we prevent matches with the string
  5718. * of window index 0 (in particular we have to avoid a match
  5719. * of the string with itself at the start of the input file).
  5720. */
  5721. s.match_length = longest_match(s, hash_head);
  5722. /* longest_match() sets match_start */
  5723. }
  5724. if (s.match_length >= MIN_MATCH) {
  5725. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  5726. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  5727. s.match_length - MIN_MATCH, bflush); ***/
  5728. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  5729. s.lookahead -= s.match_length;
  5730. /* Insert new strings in the hash table only if the match length
  5731. * is not too large. This saves time but degrades compression.
  5732. */
  5733. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  5734. s.match_length--; /* string at strstart already in table */
  5735. do {
  5736. s.strstart++;
  5737. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5738. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5739. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5740. s.head[s.ins_h] = s.strstart;
  5741. /***/
  5742. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  5743. * always MIN_MATCH bytes ahead.
  5744. */
  5745. } while (--s.match_length !== 0);
  5746. s.strstart++;
  5747. } else
  5748. {
  5749. s.strstart += s.match_length;
  5750. s.match_length = 0;
  5751. s.ins_h = s.window[s.strstart];
  5752. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  5753. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  5754. //#if MIN_MATCH != 3
  5755. // Call UPDATE_HASH() MIN_MATCH-3 more times
  5756. //#endif
  5757. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  5758. * matter since it will be recomputed at next deflate call.
  5759. */
  5760. }
  5761. } else {
  5762. /* No match, output a literal byte */
  5763. //Tracevv((stderr,"%c", s.window[s.strstart]));
  5764. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  5765. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  5766. s.lookahead--;
  5767. s.strstart++;
  5768. }
  5769. if (bflush) {
  5770. /*** FLUSH_BLOCK(s, 0); ***/
  5771. flush_block_only(s, false);
  5772. if (s.strm.avail_out === 0) {
  5773. return BS_NEED_MORE;
  5774. }
  5775. /***/
  5776. }
  5777. }
  5778. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  5779. if (flush === Z_FINISH) {
  5780. /*** FLUSH_BLOCK(s, 1); ***/
  5781. flush_block_only(s, true);
  5782. if (s.strm.avail_out === 0) {
  5783. return BS_FINISH_STARTED;
  5784. }
  5785. /***/
  5786. return BS_FINISH_DONE;
  5787. }
  5788. if (s.last_lit) {
  5789. /*** FLUSH_BLOCK(s, 0); ***/
  5790. flush_block_only(s, false);
  5791. if (s.strm.avail_out === 0) {
  5792. return BS_NEED_MORE;
  5793. }
  5794. /***/
  5795. }
  5796. return BS_BLOCK_DONE;
  5797. }
  5798. /* ===========================================================================
  5799. * Same as above, but achieves better compression. We use a lazy
  5800. * evaluation for matches: a match is finally adopted only if there is
  5801. * no better match at the next window position.
  5802. */
  5803. function deflate_slow(s, flush) {
  5804. var hash_head; /* head of hash chain */
  5805. var bflush; /* set if current block must be flushed */
  5806. var max_insert;
  5807. /* Process the input block. */
  5808. for (;;) {
  5809. /* Make sure that we always have enough lookahead, except
  5810. * at the end of the input file. We need MAX_MATCH bytes
  5811. * for the next match, plus MIN_MATCH bytes to insert the
  5812. * string following the next match.
  5813. */
  5814. if (s.lookahead < MIN_LOOKAHEAD) {
  5815. fill_window(s);
  5816. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  5817. return BS_NEED_MORE;
  5818. }
  5819. if (s.lookahead === 0) { break; } /* flush the current block */
  5820. }
  5821. /* Insert the string window[strstart .. strstart+2] in the
  5822. * dictionary, and set hash_head to the head of the hash chain:
  5823. */
  5824. hash_head = 0/*NIL*/;
  5825. if (s.lookahead >= MIN_MATCH) {
  5826. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5827. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5828. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5829. s.head[s.ins_h] = s.strstart;
  5830. /***/
  5831. }
  5832. /* Find the longest match, discarding those <= prev_length.
  5833. */
  5834. s.prev_length = s.match_length;
  5835. s.prev_match = s.match_start;
  5836. s.match_length = MIN_MATCH - 1;
  5837. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  5838. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  5839. /* To simplify the code, we prevent matches with the string
  5840. * of window index 0 (in particular we have to avoid a match
  5841. * of the string with itself at the start of the input file).
  5842. */
  5843. s.match_length = longest_match(s, hash_head);
  5844. /* longest_match() sets match_start */
  5845. if (s.match_length <= 5 &&
  5846. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  5847. /* If prev_match is also MIN_MATCH, match_start is garbage
  5848. * but we will ignore the current match anyway.
  5849. */
  5850. s.match_length = MIN_MATCH - 1;
  5851. }
  5852. }
  5853. /* If there was a match at the previous step and the current
  5854. * match is not better, output the previous match:
  5855. */
  5856. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  5857. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  5858. /* Do not insert strings in hash table beyond this. */
  5859. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  5860. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  5861. s.prev_length - MIN_MATCH, bflush);***/
  5862. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  5863. /* Insert in hash table all strings up to the end of the match.
  5864. * strstart-1 and strstart are already inserted. If there is not
  5865. * enough lookahead, the last two strings are not inserted in
  5866. * the hash table.
  5867. */
  5868. s.lookahead -= s.prev_length - 1;
  5869. s.prev_length -= 2;
  5870. do {
  5871. if (++s.strstart <= max_insert) {
  5872. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5873. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5874. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5875. s.head[s.ins_h] = s.strstart;
  5876. /***/
  5877. }
  5878. } while (--s.prev_length !== 0);
  5879. s.match_available = 0;
  5880. s.match_length = MIN_MATCH - 1;
  5881. s.strstart++;
  5882. if (bflush) {
  5883. /*** FLUSH_BLOCK(s, 0); ***/
  5884. flush_block_only(s, false);
  5885. if (s.strm.avail_out === 0) {
  5886. return BS_NEED_MORE;
  5887. }
  5888. /***/
  5889. }
  5890. } else if (s.match_available) {
  5891. /* If there was no match at the previous position, output a
  5892. * single literal. If there was a match but the current match
  5893. * is longer, truncate the previous match to a single literal.
  5894. */
  5895. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  5896. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  5897. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  5898. if (bflush) {
  5899. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  5900. flush_block_only(s, false);
  5901. /***/
  5902. }
  5903. s.strstart++;
  5904. s.lookahead--;
  5905. if (s.strm.avail_out === 0) {
  5906. return BS_NEED_MORE;
  5907. }
  5908. } else {
  5909. /* There is no previous match to compare with, wait for
  5910. * the next step to decide.
  5911. */
  5912. s.match_available = 1;
  5913. s.strstart++;
  5914. s.lookahead--;
  5915. }
  5916. }
  5917. //Assert (flush != Z_NO_FLUSH, "no flush?");
  5918. if (s.match_available) {
  5919. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  5920. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  5921. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  5922. s.match_available = 0;
  5923. }
  5924. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  5925. if (flush === Z_FINISH) {
  5926. /*** FLUSH_BLOCK(s, 1); ***/
  5927. flush_block_only(s, true);
  5928. if (s.strm.avail_out === 0) {
  5929. return BS_FINISH_STARTED;
  5930. }
  5931. /***/
  5932. return BS_FINISH_DONE;
  5933. }
  5934. if (s.last_lit) {
  5935. /*** FLUSH_BLOCK(s, 0); ***/
  5936. flush_block_only(s, false);
  5937. if (s.strm.avail_out === 0) {
  5938. return BS_NEED_MORE;
  5939. }
  5940. /***/
  5941. }
  5942. return BS_BLOCK_DONE;
  5943. }
  5944. /* ===========================================================================
  5945. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  5946. * one. Do not maintain a hash table. (It will be regenerated if this run of
  5947. * deflate switches away from Z_RLE.)
  5948. */
  5949. function deflate_rle(s, flush) {
  5950. var bflush; /* set if current block must be flushed */
  5951. var prev; /* byte at distance one to match */
  5952. var scan, strend; /* scan goes up to strend for length of run */
  5953. var _win = s.window;
  5954. for (;;) {
  5955. /* Make sure that we always have enough lookahead, except
  5956. * at the end of the input file. We need MAX_MATCH bytes
  5957. * for the longest run, plus one for the unrolled loop.
  5958. */
  5959. if (s.lookahead <= MAX_MATCH) {
  5960. fill_window(s);
  5961. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  5962. return BS_NEED_MORE;
  5963. }
  5964. if (s.lookahead === 0) { break; } /* flush the current block */
  5965. }
  5966. /* See how many times the previous byte repeats */
  5967. s.match_length = 0;
  5968. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  5969. scan = s.strstart - 1;
  5970. prev = _win[scan];
  5971. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  5972. strend = s.strstart + MAX_MATCH;
  5973. do {
  5974. /*jshint noempty:false*/
  5975. } while (prev === _win[++scan] && prev === _win[++scan] &&
  5976. prev === _win[++scan] && prev === _win[++scan] &&
  5977. prev === _win[++scan] && prev === _win[++scan] &&
  5978. prev === _win[++scan] && prev === _win[++scan] &&
  5979. scan < strend);
  5980. s.match_length = MAX_MATCH - (strend - scan);
  5981. if (s.match_length > s.lookahead) {
  5982. s.match_length = s.lookahead;
  5983. }
  5984. }
  5985. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  5986. }
  5987. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  5988. if (s.match_length >= MIN_MATCH) {
  5989. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  5990. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  5991. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  5992. s.lookahead -= s.match_length;
  5993. s.strstart += s.match_length;
  5994. s.match_length = 0;
  5995. } else {
  5996. /* No match, output a literal byte */
  5997. //Tracevv((stderr,"%c", s->window[s->strstart]));
  5998. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  5999. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6000. s.lookahead--;
  6001. s.strstart++;
  6002. }
  6003. if (bflush) {
  6004. /*** FLUSH_BLOCK(s, 0); ***/
  6005. flush_block_only(s, false);
  6006. if (s.strm.avail_out === 0) {
  6007. return BS_NEED_MORE;
  6008. }
  6009. /***/
  6010. }
  6011. }
  6012. s.insert = 0;
  6013. if (flush === Z_FINISH) {
  6014. /*** FLUSH_BLOCK(s, 1); ***/
  6015. flush_block_only(s, true);
  6016. if (s.strm.avail_out === 0) {
  6017. return BS_FINISH_STARTED;
  6018. }
  6019. /***/
  6020. return BS_FINISH_DONE;
  6021. }
  6022. if (s.last_lit) {
  6023. /*** FLUSH_BLOCK(s, 0); ***/
  6024. flush_block_only(s, false);
  6025. if (s.strm.avail_out === 0) {
  6026. return BS_NEED_MORE;
  6027. }
  6028. /***/
  6029. }
  6030. return BS_BLOCK_DONE;
  6031. }
  6032. /* ===========================================================================
  6033. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6034. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6035. */
  6036. function deflate_huff(s, flush) {
  6037. var bflush; /* set if current block must be flushed */
  6038. for (;;) {
  6039. /* Make sure that we have a literal to write. */
  6040. if (s.lookahead === 0) {
  6041. fill_window(s);
  6042. if (s.lookahead === 0) {
  6043. if (flush === Z_NO_FLUSH) {
  6044. return BS_NEED_MORE;
  6045. }
  6046. break; /* flush the current block */
  6047. }
  6048. }
  6049. /* Output a literal byte */
  6050. s.match_length = 0;
  6051. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6052. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6053. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6054. s.lookahead--;
  6055. s.strstart++;
  6056. if (bflush) {
  6057. /*** FLUSH_BLOCK(s, 0); ***/
  6058. flush_block_only(s, false);
  6059. if (s.strm.avail_out === 0) {
  6060. return BS_NEED_MORE;
  6061. }
  6062. /***/
  6063. }
  6064. }
  6065. s.insert = 0;
  6066. if (flush === Z_FINISH) {
  6067. /*** FLUSH_BLOCK(s, 1); ***/
  6068. flush_block_only(s, true);
  6069. if (s.strm.avail_out === 0) {
  6070. return BS_FINISH_STARTED;
  6071. }
  6072. /***/
  6073. return BS_FINISH_DONE;
  6074. }
  6075. if (s.last_lit) {
  6076. /*** FLUSH_BLOCK(s, 0); ***/
  6077. flush_block_only(s, false);
  6078. if (s.strm.avail_out === 0) {
  6079. return BS_NEED_MORE;
  6080. }
  6081. /***/
  6082. }
  6083. return BS_BLOCK_DONE;
  6084. }
  6085. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6086. * the desired pack level (0..9). The values given below have been tuned to
  6087. * exclude worst case performance for pathological files. Better values may be
  6088. * found for specific files.
  6089. */
  6090. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  6091. this.good_length = good_length;
  6092. this.max_lazy = max_lazy;
  6093. this.nice_length = nice_length;
  6094. this.max_chain = max_chain;
  6095. this.func = func;
  6096. }
  6097. var configuration_table;
  6098. configuration_table = [
  6099. /* good lazy nice chain */
  6100. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6101. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6102. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6103. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6104. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6105. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6106. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6107. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6108. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6109. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6110. ];
  6111. /* ===========================================================================
  6112. * Initialize the "longest match" routines for a new zlib stream
  6113. */
  6114. function lm_init(s) {
  6115. s.window_size = 2 * s.w_size;
  6116. /*** CLEAR_HASH(s); ***/
  6117. zero(s.head); // Fill with NIL (= 0);
  6118. /* Set the default configuration parameters:
  6119. */
  6120. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6121. s.good_match = configuration_table[s.level].good_length;
  6122. s.nice_match = configuration_table[s.level].nice_length;
  6123. s.max_chain_length = configuration_table[s.level].max_chain;
  6124. s.strstart = 0;
  6125. s.block_start = 0;
  6126. s.lookahead = 0;
  6127. s.insert = 0;
  6128. s.match_length = s.prev_length = MIN_MATCH - 1;
  6129. s.match_available = 0;
  6130. s.ins_h = 0;
  6131. }
  6132. function DeflateState() {
  6133. this.strm = null; /* pointer back to this zlib stream */
  6134. this.status = 0; /* as the name implies */
  6135. this.pending_buf = null; /* output still pending */
  6136. this.pending_buf_size = 0; /* size of pending_buf */
  6137. this.pending_out = 0; /* next pending byte to output to the stream */
  6138. this.pending = 0; /* nb of bytes in the pending buffer */
  6139. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6140. this.gzhead = null; /* gzip header information to write */
  6141. this.gzindex = 0; /* where in extra, name, or comment */
  6142. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6143. this.last_flush = -1; /* value of flush param for previous deflate call */
  6144. this.w_size = 0; /* LZ77 window size (32K by default) */
  6145. this.w_bits = 0; /* log2(w_size) (8..16) */
  6146. this.w_mask = 0; /* w_size - 1 */
  6147. this.window = null;
  6148. /* Sliding window. Input bytes are read into the second half of the window,
  6149. * and move to the first half later to keep a dictionary of at least wSize
  6150. * bytes. With this organization, matches are limited to a distance of
  6151. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6152. * performed with a length multiple of the block size.
  6153. */
  6154. this.window_size = 0;
  6155. /* Actual size of window: 2*wSize, except when the user input buffer
  6156. * is directly used as sliding window.
  6157. */
  6158. this.prev = null;
  6159. /* Link to older string with same hash index. To limit the size of this
  6160. * array to 64K, this link is maintained only for the last 32K strings.
  6161. * An index in this array is thus a window index modulo 32K.
  6162. */
  6163. this.head = null; /* Heads of the hash chains or NIL. */
  6164. this.ins_h = 0; /* hash index of string to be inserted */
  6165. this.hash_size = 0; /* number of elements in hash table */
  6166. this.hash_bits = 0; /* log2(hash_size) */
  6167. this.hash_mask = 0; /* hash_size-1 */
  6168. this.hash_shift = 0;
  6169. /* Number of bits by which ins_h must be shifted at each input
  6170. * step. It must be such that after MIN_MATCH steps, the oldest
  6171. * byte no longer takes part in the hash key, that is:
  6172. * hash_shift * MIN_MATCH >= hash_bits
  6173. */
  6174. this.block_start = 0;
  6175. /* Window position at the beginning of the current output block. Gets
  6176. * negative when the window is moved backwards.
  6177. */
  6178. this.match_length = 0; /* length of best match */
  6179. this.prev_match = 0; /* previous match */
  6180. this.match_available = 0; /* set if previous match exists */
  6181. this.strstart = 0; /* start of string to insert */
  6182. this.match_start = 0; /* start of matching string */
  6183. this.lookahead = 0; /* number of valid bytes ahead in window */
  6184. this.prev_length = 0;
  6185. /* Length of the best match at previous step. Matches not greater than this
  6186. * are discarded. This is used in the lazy match evaluation.
  6187. */
  6188. this.max_chain_length = 0;
  6189. /* To speed up deflation, hash chains are never searched beyond this
  6190. * length. A higher limit improves compression ratio but degrades the
  6191. * speed.
  6192. */
  6193. this.max_lazy_match = 0;
  6194. /* Attempt to find a better match only when the current match is strictly
  6195. * smaller than this value. This mechanism is used only for compression
  6196. * levels >= 4.
  6197. */
  6198. // That's alias to max_lazy_match, don't use directly
  6199. //this.max_insert_length = 0;
  6200. /* Insert new strings in the hash table only if the match length is not
  6201. * greater than this length. This saves time but degrades compression.
  6202. * max_insert_length is used only for compression levels <= 3.
  6203. */
  6204. this.level = 0; /* compression level (1..9) */
  6205. this.strategy = 0; /* favor or force Huffman coding*/
  6206. this.good_match = 0;
  6207. /* Use a faster search when the previous match is longer than this */
  6208. this.nice_match = 0; /* Stop searching when current match exceeds this */
  6209. /* used by trees.c: */
  6210. /* Didn't use ct_data typedef below to suppress compiler warning */
  6211. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  6212. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  6213. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  6214. // Use flat array of DOUBLE size, with interleaved fata,
  6215. // because JS does not support effective
  6216. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  6217. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  6218. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  6219. zero(this.dyn_ltree);
  6220. zero(this.dyn_dtree);
  6221. zero(this.bl_tree);
  6222. this.l_desc = null; /* desc. for literal tree */
  6223. this.d_desc = null; /* desc. for distance tree */
  6224. this.bl_desc = null; /* desc. for bit length tree */
  6225. //ush bl_count[MAX_BITS+1];
  6226. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  6227. /* number of codes at each bit length for an optimal tree */
  6228. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  6229. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  6230. zero(this.heap);
  6231. this.heap_len = 0; /* number of elements in the heap */
  6232. this.heap_max = 0; /* element of largest frequency */
  6233. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  6234. * The same heap array is used to build all trees.
  6235. */
  6236. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  6237. zero(this.depth);
  6238. /* Depth of each subtree used as tie breaker for trees of equal frequency
  6239. */
  6240. this.l_buf = 0; /* buffer index for literals or lengths */
  6241. this.lit_bufsize = 0;
  6242. /* Size of match buffer for literals/lengths. There are 4 reasons for
  6243. * limiting lit_bufsize to 64K:
  6244. * - frequencies can be kept in 16 bit counters
  6245. * - if compression is not successful for the first block, all input
  6246. * data is still in the window so we can still emit a stored block even
  6247. * when input comes from standard input. (This can also be done for
  6248. * all blocks if lit_bufsize is not greater than 32K.)
  6249. * - if compression is not successful for a file smaller than 64K, we can
  6250. * even emit a stored file instead of a stored block (saving 5 bytes).
  6251. * This is applicable only for zip (not gzip or zlib).
  6252. * - creating new Huffman trees less frequently may not provide fast
  6253. * adaptation to changes in the input data statistics. (Take for
  6254. * example a binary file with poorly compressible code followed by
  6255. * a highly compressible string table.) Smaller buffer sizes give
  6256. * fast adaptation but have of course the overhead of transmitting
  6257. * trees more frequently.
  6258. * - I can't count above 4
  6259. */
  6260. this.last_lit = 0; /* running index in l_buf */
  6261. this.d_buf = 0;
  6262. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  6263. * the same number of elements. To use different lengths, an extra flag
  6264. * array would be necessary.
  6265. */
  6266. this.opt_len = 0; /* bit length of current block with optimal trees */
  6267. this.static_len = 0; /* bit length of current block with static trees */
  6268. this.matches = 0; /* number of string matches in current block */
  6269. this.insert = 0; /* bytes at end of window left to insert */
  6270. this.bi_buf = 0;
  6271. /* Output buffer. bits are inserted starting at the bottom (least
  6272. * significant bits).
  6273. */
  6274. this.bi_valid = 0;
  6275. /* Number of valid bits in bi_buf. All bits above the last valid bit
  6276. * are always zero.
  6277. */
  6278. // Used for window memory init. We safely ignore it for JS. That makes
  6279. // sense only for pointers and memory check tools.
  6280. //this.high_water = 0;
  6281. /* High water mark offset in window for initialized bytes -- bytes above
  6282. * this are set to zero in order to avoid memory check warnings when
  6283. * longest match routines access bytes past the input. This is then
  6284. * updated to the new high water mark.
  6285. */
  6286. }
  6287. function deflateResetKeep(strm) {
  6288. var s;
  6289. if (!strm || !strm.state) {
  6290. return err(strm, Z_STREAM_ERROR);
  6291. }
  6292. strm.total_in = strm.total_out = 0;
  6293. strm.data_type = Z_UNKNOWN;
  6294. s = strm.state;
  6295. s.pending = 0;
  6296. s.pending_out = 0;
  6297. if (s.wrap < 0) {
  6298. s.wrap = -s.wrap;
  6299. /* was made negative by deflate(..., Z_FINISH); */
  6300. }
  6301. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  6302. strm.adler = (s.wrap === 2) ?
  6303. 0 // crc32(0, Z_NULL, 0)
  6304. :
  6305. 1; // adler32(0, Z_NULL, 0)
  6306. s.last_flush = Z_NO_FLUSH;
  6307. trees._tr_init(s);
  6308. return Z_OK;
  6309. }
  6310. function deflateReset(strm) {
  6311. var ret = deflateResetKeep(strm);
  6312. if (ret === Z_OK) {
  6313. lm_init(strm.state);
  6314. }
  6315. return ret;
  6316. }
  6317. function deflateSetHeader(strm, head) {
  6318. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6319. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  6320. strm.state.gzhead = head;
  6321. return Z_OK;
  6322. }
  6323. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  6324. if (!strm) { // === Z_NULL
  6325. return Z_STREAM_ERROR;
  6326. }
  6327. var wrap = 1;
  6328. if (level === Z_DEFAULT_COMPRESSION) {
  6329. level = 6;
  6330. }
  6331. if (windowBits < 0) { /* suppress zlib wrapper */
  6332. wrap = 0;
  6333. windowBits = -windowBits;
  6334. }
  6335. else if (windowBits > 15) {
  6336. wrap = 2; /* write gzip wrapper instead */
  6337. windowBits -= 16;
  6338. }
  6339. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  6340. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  6341. strategy < 0 || strategy > Z_FIXED) {
  6342. return err(strm, Z_STREAM_ERROR);
  6343. }
  6344. if (windowBits === 8) {
  6345. windowBits = 9;
  6346. }
  6347. /* until 256-byte window bug fixed */
  6348. var s = new DeflateState();
  6349. strm.state = s;
  6350. s.strm = strm;
  6351. s.wrap = wrap;
  6352. s.gzhead = null;
  6353. s.w_bits = windowBits;
  6354. s.w_size = 1 << s.w_bits;
  6355. s.w_mask = s.w_size - 1;
  6356. s.hash_bits = memLevel + 7;
  6357. s.hash_size = 1 << s.hash_bits;
  6358. s.hash_mask = s.hash_size - 1;
  6359. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  6360. s.window = new utils.Buf8(s.w_size * 2);
  6361. s.head = new utils.Buf16(s.hash_size);
  6362. s.prev = new utils.Buf16(s.w_size);
  6363. // Don't need mem init magic for JS.
  6364. //s.high_water = 0; /* nothing written to s->window yet */
  6365. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  6366. s.pending_buf_size = s.lit_bufsize * 4;
  6367. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  6368. //s->pending_buf = (uchf *) overlay;
  6369. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  6370. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  6371. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  6372. s.d_buf = 1 * s.lit_bufsize;
  6373. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  6374. s.l_buf = (1 + 2) * s.lit_bufsize;
  6375. s.level = level;
  6376. s.strategy = strategy;
  6377. s.method = method;
  6378. return deflateReset(strm);
  6379. }
  6380. function deflateInit(strm, level) {
  6381. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  6382. }
  6383. function deflate(strm, flush) {
  6384. var old_flush, s;
  6385. var beg, val; // for gzip header write only
  6386. if (!strm || !strm.state ||
  6387. flush > Z_BLOCK || flush < 0) {
  6388. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  6389. }
  6390. s = strm.state;
  6391. if (!strm.output ||
  6392. (!strm.input && strm.avail_in !== 0) ||
  6393. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  6394. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  6395. }
  6396. s.strm = strm; /* just in case */
  6397. old_flush = s.last_flush;
  6398. s.last_flush = flush;
  6399. /* Write the header */
  6400. if (s.status === INIT_STATE) {
  6401. if (s.wrap === 2) { // GZIP header
  6402. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  6403. put_byte(s, 31);
  6404. put_byte(s, 139);
  6405. put_byte(s, 8);
  6406. if (!s.gzhead) { // s->gzhead == Z_NULL
  6407. put_byte(s, 0);
  6408. put_byte(s, 0);
  6409. put_byte(s, 0);
  6410. put_byte(s, 0);
  6411. put_byte(s, 0);
  6412. put_byte(s, s.level === 9 ? 2 :
  6413. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  6414. 4 : 0));
  6415. put_byte(s, OS_CODE);
  6416. s.status = BUSY_STATE;
  6417. }
  6418. else {
  6419. put_byte(s, (s.gzhead.text ? 1 : 0) +
  6420. (s.gzhead.hcrc ? 2 : 0) +
  6421. (!s.gzhead.extra ? 0 : 4) +
  6422. (!s.gzhead.name ? 0 : 8) +
  6423. (!s.gzhead.comment ? 0 : 16)
  6424. );
  6425. put_byte(s, s.gzhead.time & 0xff);
  6426. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  6427. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  6428. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  6429. put_byte(s, s.level === 9 ? 2 :
  6430. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  6431. 4 : 0));
  6432. put_byte(s, s.gzhead.os & 0xff);
  6433. if (s.gzhead.extra && s.gzhead.extra.length) {
  6434. put_byte(s, s.gzhead.extra.length & 0xff);
  6435. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  6436. }
  6437. if (s.gzhead.hcrc) {
  6438. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  6439. }
  6440. s.gzindex = 0;
  6441. s.status = EXTRA_STATE;
  6442. }
  6443. }
  6444. else // DEFLATE header
  6445. {
  6446. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  6447. var level_flags = -1;
  6448. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  6449. level_flags = 0;
  6450. } else if (s.level < 6) {
  6451. level_flags = 1;
  6452. } else if (s.level === 6) {
  6453. level_flags = 2;
  6454. } else {
  6455. level_flags = 3;
  6456. }
  6457. header |= (level_flags << 6);
  6458. if (s.strstart !== 0) { header |= PRESET_DICT; }
  6459. header += 31 - (header % 31);
  6460. s.status = BUSY_STATE;
  6461. putShortMSB(s, header);
  6462. /* Save the adler32 of the preset dictionary: */
  6463. if (s.strstart !== 0) {
  6464. putShortMSB(s, strm.adler >>> 16);
  6465. putShortMSB(s, strm.adler & 0xffff);
  6466. }
  6467. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  6468. }
  6469. }
  6470. //#ifdef GZIP
  6471. if (s.status === EXTRA_STATE) {
  6472. if (s.gzhead.extra/* != Z_NULL*/) {
  6473. beg = s.pending; /* start of bytes to update crc */
  6474. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  6475. if (s.pending === s.pending_buf_size) {
  6476. if (s.gzhead.hcrc && s.pending > beg) {
  6477. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6478. }
  6479. flush_pending(strm);
  6480. beg = s.pending;
  6481. if (s.pending === s.pending_buf_size) {
  6482. break;
  6483. }
  6484. }
  6485. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  6486. s.gzindex++;
  6487. }
  6488. if (s.gzhead.hcrc && s.pending > beg) {
  6489. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6490. }
  6491. if (s.gzindex === s.gzhead.extra.length) {
  6492. s.gzindex = 0;
  6493. s.status = NAME_STATE;
  6494. }
  6495. }
  6496. else {
  6497. s.status = NAME_STATE;
  6498. }
  6499. }
  6500. if (s.status === NAME_STATE) {
  6501. if (s.gzhead.name/* != Z_NULL*/) {
  6502. beg = s.pending; /* start of bytes to update crc */
  6503. //int val;
  6504. do {
  6505. if (s.pending === s.pending_buf_size) {
  6506. if (s.gzhead.hcrc && s.pending > beg) {
  6507. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6508. }
  6509. flush_pending(strm);
  6510. beg = s.pending;
  6511. if (s.pending === s.pending_buf_size) {
  6512. val = 1;
  6513. break;
  6514. }
  6515. }
  6516. // JS specific: little magic to add zero terminator to end of string
  6517. if (s.gzindex < s.gzhead.name.length) {
  6518. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  6519. } else {
  6520. val = 0;
  6521. }
  6522. put_byte(s, val);
  6523. } while (val !== 0);
  6524. if (s.gzhead.hcrc && s.pending > beg) {
  6525. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6526. }
  6527. if (val === 0) {
  6528. s.gzindex = 0;
  6529. s.status = COMMENT_STATE;
  6530. }
  6531. }
  6532. else {
  6533. s.status = COMMENT_STATE;
  6534. }
  6535. }
  6536. if (s.status === COMMENT_STATE) {
  6537. if (s.gzhead.comment/* != Z_NULL*/) {
  6538. beg = s.pending; /* start of bytes to update crc */
  6539. //int val;
  6540. do {
  6541. if (s.pending === s.pending_buf_size) {
  6542. if (s.gzhead.hcrc && s.pending > beg) {
  6543. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6544. }
  6545. flush_pending(strm);
  6546. beg = s.pending;
  6547. if (s.pending === s.pending_buf_size) {
  6548. val = 1;
  6549. break;
  6550. }
  6551. }
  6552. // JS specific: little magic to add zero terminator to end of string
  6553. if (s.gzindex < s.gzhead.comment.length) {
  6554. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  6555. } else {
  6556. val = 0;
  6557. }
  6558. put_byte(s, val);
  6559. } while (val !== 0);
  6560. if (s.gzhead.hcrc && s.pending > beg) {
  6561. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6562. }
  6563. if (val === 0) {
  6564. s.status = HCRC_STATE;
  6565. }
  6566. }
  6567. else {
  6568. s.status = HCRC_STATE;
  6569. }
  6570. }
  6571. if (s.status === HCRC_STATE) {
  6572. if (s.gzhead.hcrc) {
  6573. if (s.pending + 2 > s.pending_buf_size) {
  6574. flush_pending(strm);
  6575. }
  6576. if (s.pending + 2 <= s.pending_buf_size) {
  6577. put_byte(s, strm.adler & 0xff);
  6578. put_byte(s, (strm.adler >> 8) & 0xff);
  6579. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  6580. s.status = BUSY_STATE;
  6581. }
  6582. }
  6583. else {
  6584. s.status = BUSY_STATE;
  6585. }
  6586. }
  6587. //#endif
  6588. /* Flush as much pending output as possible */
  6589. if (s.pending !== 0) {
  6590. flush_pending(strm);
  6591. if (strm.avail_out === 0) {
  6592. /* Since avail_out is 0, deflate will be called again with
  6593. * more output space, but possibly with both pending and
  6594. * avail_in equal to zero. There won't be anything to do,
  6595. * but this is not an error situation so make sure we
  6596. * return OK instead of BUF_ERROR at next call of deflate:
  6597. */
  6598. s.last_flush = -1;
  6599. return Z_OK;
  6600. }
  6601. /* Make sure there is something to do and avoid duplicate consecutive
  6602. * flushes. For repeated and useless calls with Z_FINISH, we keep
  6603. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  6604. */
  6605. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  6606. flush !== Z_FINISH) {
  6607. return err(strm, Z_BUF_ERROR);
  6608. }
  6609. /* User must not provide more input after the first FINISH: */
  6610. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  6611. return err(strm, Z_BUF_ERROR);
  6612. }
  6613. /* Start a new block or continue the current one.
  6614. */
  6615. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  6616. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  6617. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  6618. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  6619. configuration_table[s.level].func(s, flush));
  6620. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  6621. s.status = FINISH_STATE;
  6622. }
  6623. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  6624. if (strm.avail_out === 0) {
  6625. s.last_flush = -1;
  6626. /* avoid BUF_ERROR next call, see above */
  6627. }
  6628. return Z_OK;
  6629. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  6630. * of deflate should use the same flush parameter to make sure
  6631. * that the flush is complete. So we don't have to output an
  6632. * empty block here, this will be done at next call. This also
  6633. * ensures that for a very small output buffer, we emit at most
  6634. * one empty block.
  6635. */
  6636. }
  6637. if (bstate === BS_BLOCK_DONE) {
  6638. if (flush === Z_PARTIAL_FLUSH) {
  6639. trees._tr_align(s);
  6640. }
  6641. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  6642. trees._tr_stored_block(s, 0, 0, false);
  6643. /* For a full flush, this empty block will be recognized
  6644. * as a special marker by inflate_sync().
  6645. */
  6646. if (flush === Z_FULL_FLUSH) {
  6647. /*** CLEAR_HASH(s); ***/ /* forget history */
  6648. zero(s.head); // Fill with NIL (= 0);
  6649. if (s.lookahead === 0) {
  6650. s.strstart = 0;
  6651. s.block_start = 0;
  6652. s.insert = 0;
  6653. }
  6654. }
  6655. }
  6656. flush_pending(strm);
  6657. if (strm.avail_out === 0) {
  6658. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  6659. return Z_OK;
  6660. }
  6661. }
  6662. }
  6663. //Assert(strm->avail_out > 0, "bug2");
  6664. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  6665. if (flush !== Z_FINISH) { return Z_OK; }
  6666. if (s.wrap <= 0) { return Z_STREAM_END; }
  6667. /* Write the trailer */
  6668. if (s.wrap === 2) {
  6669. put_byte(s, strm.adler & 0xff);
  6670. put_byte(s, (strm.adler >> 8) & 0xff);
  6671. put_byte(s, (strm.adler >> 16) & 0xff);
  6672. put_byte(s, (strm.adler >> 24) & 0xff);
  6673. put_byte(s, strm.total_in & 0xff);
  6674. put_byte(s, (strm.total_in >> 8) & 0xff);
  6675. put_byte(s, (strm.total_in >> 16) & 0xff);
  6676. put_byte(s, (strm.total_in >> 24) & 0xff);
  6677. }
  6678. else
  6679. {
  6680. putShortMSB(s, strm.adler >>> 16);
  6681. putShortMSB(s, strm.adler & 0xffff);
  6682. }
  6683. flush_pending(strm);
  6684. /* If avail_out is zero, the application will call deflate again
  6685. * to flush the rest.
  6686. */
  6687. if (s.wrap > 0) { s.wrap = -s.wrap; }
  6688. /* write the trailer only once! */
  6689. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  6690. }
  6691. function deflateEnd(strm) {
  6692. var status;
  6693. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  6694. return Z_STREAM_ERROR;
  6695. }
  6696. status = strm.state.status;
  6697. if (status !== INIT_STATE &&
  6698. status !== EXTRA_STATE &&
  6699. status !== NAME_STATE &&
  6700. status !== COMMENT_STATE &&
  6701. status !== HCRC_STATE &&
  6702. status !== BUSY_STATE &&
  6703. status !== FINISH_STATE
  6704. ) {
  6705. return err(strm, Z_STREAM_ERROR);
  6706. }
  6707. strm.state = null;
  6708. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  6709. }
  6710. /* =========================================================================
  6711. * Initializes the compression dictionary from the given byte
  6712. * sequence without producing any compressed output.
  6713. */
  6714. function deflateSetDictionary(strm, dictionary) {
  6715. var dictLength = dictionary.length;
  6716. var s;
  6717. var str, n;
  6718. var wrap;
  6719. var avail;
  6720. var next;
  6721. var input;
  6722. var tmpDict;
  6723. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  6724. return Z_STREAM_ERROR;
  6725. }
  6726. s = strm.state;
  6727. wrap = s.wrap;
  6728. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  6729. return Z_STREAM_ERROR;
  6730. }
  6731. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  6732. if (wrap === 1) {
  6733. /* adler32(strm->adler, dictionary, dictLength); */
  6734. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  6735. }
  6736. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  6737. /* if dictionary would fill window, just replace the history */
  6738. if (dictLength >= s.w_size) {
  6739. if (wrap === 0) { /* already empty otherwise */
  6740. /*** CLEAR_HASH(s); ***/
  6741. zero(s.head); // Fill with NIL (= 0);
  6742. s.strstart = 0;
  6743. s.block_start = 0;
  6744. s.insert = 0;
  6745. }
  6746. /* use the tail */
  6747. // dictionary = dictionary.slice(dictLength - s.w_size);
  6748. tmpDict = new utils.Buf8(s.w_size);
  6749. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  6750. dictionary = tmpDict;
  6751. dictLength = s.w_size;
  6752. }
  6753. /* insert dictionary into window and hash */
  6754. avail = strm.avail_in;
  6755. next = strm.next_in;
  6756. input = strm.input;
  6757. strm.avail_in = dictLength;
  6758. strm.next_in = 0;
  6759. strm.input = dictionary;
  6760. fill_window(s);
  6761. while (s.lookahead >= MIN_MATCH) {
  6762. str = s.strstart;
  6763. n = s.lookahead - (MIN_MATCH - 1);
  6764. do {
  6765. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6766. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6767. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6768. s.head[s.ins_h] = str;
  6769. str++;
  6770. } while (--n);
  6771. s.strstart = str;
  6772. s.lookahead = MIN_MATCH - 1;
  6773. fill_window(s);
  6774. }
  6775. s.strstart += s.lookahead;
  6776. s.block_start = s.strstart;
  6777. s.insert = s.lookahead;
  6778. s.lookahead = 0;
  6779. s.match_length = s.prev_length = MIN_MATCH - 1;
  6780. s.match_available = 0;
  6781. strm.next_in = next;
  6782. strm.input = input;
  6783. strm.avail_in = avail;
  6784. s.wrap = wrap;
  6785. return Z_OK;
  6786. }
  6787. exports.deflateInit = deflateInit;
  6788. exports.deflateInit2 = deflateInit2;
  6789. exports.deflateReset = deflateReset;
  6790. exports.deflateResetKeep = deflateResetKeep;
  6791. exports.deflateSetHeader = deflateSetHeader;
  6792. exports.deflate = deflate;
  6793. exports.deflateEnd = deflateEnd;
  6794. exports.deflateSetDictionary = deflateSetDictionary;
  6795. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  6796. /* Not implemented
  6797. exports.deflateBound = deflateBound;
  6798. exports.deflateCopy = deflateCopy;
  6799. exports.deflateParams = deflateParams;
  6800. exports.deflatePending = deflatePending;
  6801. exports.deflatePrime = deflatePrime;
  6802. exports.deflateTune = deflateTune;
  6803. */
  6804. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
  6805. 'use strict';
  6806. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6807. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6808. //
  6809. // This software is provided 'as-is', without any express or implied
  6810. // warranty. In no event will the authors be held liable for any damages
  6811. // arising from the use of this software.
  6812. //
  6813. // Permission is granted to anyone to use this software for any purpose,
  6814. // including commercial applications, and to alter it and redistribute it
  6815. // freely, subject to the following restrictions:
  6816. //
  6817. // 1. The origin of this software must not be misrepresented; you must not
  6818. // claim that you wrote the original software. If you use this software
  6819. // in a product, an acknowledgment in the product documentation would be
  6820. // appreciated but is not required.
  6821. // 2. Altered source versions must be plainly marked as such, and must not be
  6822. // misrepresented as being the original software.
  6823. // 3. This notice may not be removed or altered from any source distribution.
  6824. function GZheader() {
  6825. /* true if compressed data believed to be text */
  6826. this.text = 0;
  6827. /* modification time */
  6828. this.time = 0;
  6829. /* extra flags (not used when writing a gzip file) */
  6830. this.xflags = 0;
  6831. /* operating system */
  6832. this.os = 0;
  6833. /* pointer to extra field or Z_NULL if none */
  6834. this.extra = null;
  6835. /* extra field length (valid if extra != Z_NULL) */
  6836. this.extra_len = 0; // Actually, we don't need it in JS,
  6837. // but leave for few code modifications
  6838. //
  6839. // Setup limits is not necessary because in js we should not preallocate memory
  6840. // for inflate use constant limit in 65536 bytes
  6841. //
  6842. /* space at extra (only when reading header) */
  6843. // this.extra_max = 0;
  6844. /* pointer to zero-terminated file name or Z_NULL */
  6845. this.name = '';
  6846. /* space at name (only when reading header) */
  6847. // this.name_max = 0;
  6848. /* pointer to zero-terminated comment or Z_NULL */
  6849. this.comment = '';
  6850. /* space at comment (only when reading header) */
  6851. // this.comm_max = 0;
  6852. /* true if there was or will be a header crc */
  6853. this.hcrc = 0;
  6854. /* true when done reading gzip header (not used when writing a gzip file) */
  6855. this.done = false;
  6856. }
  6857. module.exports = GZheader;
  6858. },{}],48:[function(require,module,exports){
  6859. 'use strict';
  6860. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6861. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6862. //
  6863. // This software is provided 'as-is', without any express or implied
  6864. // warranty. In no event will the authors be held liable for any damages
  6865. // arising from the use of this software.
  6866. //
  6867. // Permission is granted to anyone to use this software for any purpose,
  6868. // including commercial applications, and to alter it and redistribute it
  6869. // freely, subject to the following restrictions:
  6870. //
  6871. // 1. The origin of this software must not be misrepresented; you must not
  6872. // claim that you wrote the original software. If you use this software
  6873. // in a product, an acknowledgment in the product documentation would be
  6874. // appreciated but is not required.
  6875. // 2. Altered source versions must be plainly marked as such, and must not be
  6876. // misrepresented as being the original software.
  6877. // 3. This notice may not be removed or altered from any source distribution.
  6878. // See state defs from inflate.js
  6879. var BAD = 30; /* got a data error -- remain here until reset */
  6880. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  6881. /*
  6882. Decode literal, length, and distance codes and write out the resulting
  6883. literal and match bytes until either not enough input or output is
  6884. available, an end-of-block is encountered, or a data error is encountered.
  6885. When large enough input and output buffers are supplied to inflate(), for
  6886. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  6887. inflate execution time is spent in this routine.
  6888. Entry assumptions:
  6889. state.mode === LEN
  6890. strm.avail_in >= 6
  6891. strm.avail_out >= 258
  6892. start >= strm.avail_out
  6893. state.bits < 8
  6894. On return, state.mode is one of:
  6895. LEN -- ran out of enough output space or enough available input
  6896. TYPE -- reached end of block code, inflate() to interpret next block
  6897. BAD -- error in block data
  6898. Notes:
  6899. - The maximum input bits used by a length/distance pair is 15 bits for the
  6900. length code, 5 bits for the length extra, 15 bits for the distance code,
  6901. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  6902. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  6903. checking for available input while decoding.
  6904. - The maximum bytes that a single length/distance pair can output is 258
  6905. bytes, which is the maximum length that can be coded. inflate_fast()
  6906. requires strm.avail_out >= 258 for each loop to avoid checking for
  6907. output space.
  6908. */
  6909. module.exports = function inflate_fast(strm, start) {
  6910. var state;
  6911. var _in; /* local strm.input */
  6912. var last; /* have enough input while in < last */
  6913. var _out; /* local strm.output */
  6914. var beg; /* inflate()'s initial strm.output */
  6915. var end; /* while out < end, enough space available */
  6916. //#ifdef INFLATE_STRICT
  6917. var dmax; /* maximum distance from zlib header */
  6918. //#endif
  6919. var wsize; /* window size or zero if not using window */
  6920. var whave; /* valid bytes in the window */
  6921. var wnext; /* window write index */
  6922. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  6923. var s_window; /* allocated sliding window, if wsize != 0 */
  6924. var hold; /* local strm.hold */
  6925. var bits; /* local strm.bits */
  6926. var lcode; /* local strm.lencode */
  6927. var dcode; /* local strm.distcode */
  6928. var lmask; /* mask for first level of length codes */
  6929. var dmask; /* mask for first level of distance codes */
  6930. var here; /* retrieved table entry */
  6931. var op; /* code bits, operation, extra bits, or */
  6932. /* window position, window bytes to copy */
  6933. var len; /* match length, unused bytes */
  6934. var dist; /* match distance */
  6935. var from; /* where to copy match from */
  6936. var from_source;
  6937. var input, output; // JS specific, because we have no pointers
  6938. /* copy state to local variables */
  6939. state = strm.state;
  6940. //here = state.here;
  6941. _in = strm.next_in;
  6942. input = strm.input;
  6943. last = _in + (strm.avail_in - 5);
  6944. _out = strm.next_out;
  6945. output = strm.output;
  6946. beg = _out - (start - strm.avail_out);
  6947. end = _out + (strm.avail_out - 257);
  6948. //#ifdef INFLATE_STRICT
  6949. dmax = state.dmax;
  6950. //#endif
  6951. wsize = state.wsize;
  6952. whave = state.whave;
  6953. wnext = state.wnext;
  6954. s_window = state.window;
  6955. hold = state.hold;
  6956. bits = state.bits;
  6957. lcode = state.lencode;
  6958. dcode = state.distcode;
  6959. lmask = (1 << state.lenbits) - 1;
  6960. dmask = (1 << state.distbits) - 1;
  6961. /* decode literals and length/distances until end-of-block or not enough
  6962. input data or output space */
  6963. top:
  6964. do {
  6965. if (bits < 15) {
  6966. hold += input[_in++] << bits;
  6967. bits += 8;
  6968. hold += input[_in++] << bits;
  6969. bits += 8;
  6970. }
  6971. here = lcode[hold & lmask];
  6972. dolen:
  6973. for (;;) { // Goto emulation
  6974. op = here >>> 24/*here.bits*/;
  6975. hold >>>= op;
  6976. bits -= op;
  6977. op = (here >>> 16) & 0xff/*here.op*/;
  6978. if (op === 0) { /* literal */
  6979. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6980. // "inflate: literal '%c'\n" :
  6981. // "inflate: literal 0x%02x\n", here.val));
  6982. output[_out++] = here & 0xffff/*here.val*/;
  6983. }
  6984. else if (op & 16) { /* length base */
  6985. len = here & 0xffff/*here.val*/;
  6986. op &= 15; /* number of extra bits */
  6987. if (op) {
  6988. if (bits < op) {
  6989. hold += input[_in++] << bits;
  6990. bits += 8;
  6991. }
  6992. len += hold & ((1 << op) - 1);
  6993. hold >>>= op;
  6994. bits -= op;
  6995. }
  6996. //Tracevv((stderr, "inflate: length %u\n", len));
  6997. if (bits < 15) {
  6998. hold += input[_in++] << bits;
  6999. bits += 8;
  7000. hold += input[_in++] << bits;
  7001. bits += 8;
  7002. }
  7003. here = dcode[hold & dmask];
  7004. dodist:
  7005. for (;;) { // goto emulation
  7006. op = here >>> 24/*here.bits*/;
  7007. hold >>>= op;
  7008. bits -= op;
  7009. op = (here >>> 16) & 0xff/*here.op*/;
  7010. if (op & 16) { /* distance base */
  7011. dist = here & 0xffff/*here.val*/;
  7012. op &= 15; /* number of extra bits */
  7013. if (bits < op) {
  7014. hold += input[_in++] << bits;
  7015. bits += 8;
  7016. if (bits < op) {
  7017. hold += input[_in++] << bits;
  7018. bits += 8;
  7019. }
  7020. }
  7021. dist += hold & ((1 << op) - 1);
  7022. //#ifdef INFLATE_STRICT
  7023. if (dist > dmax) {
  7024. strm.msg = 'invalid distance too far back';
  7025. state.mode = BAD;
  7026. break top;
  7027. }
  7028. //#endif
  7029. hold >>>= op;
  7030. bits -= op;
  7031. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7032. op = _out - beg; /* max distance in output */
  7033. if (dist > op) { /* see if copy from window */
  7034. op = dist - op; /* distance back in window */
  7035. if (op > whave) {
  7036. if (state.sane) {
  7037. strm.msg = 'invalid distance too far back';
  7038. state.mode = BAD;
  7039. break top;
  7040. }
  7041. // (!) This block is disabled in zlib defailts,
  7042. // don't enable it for binary compatibility
  7043. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7044. // if (len <= op - whave) {
  7045. // do {
  7046. // output[_out++] = 0;
  7047. // } while (--len);
  7048. // continue top;
  7049. // }
  7050. // len -= op - whave;
  7051. // do {
  7052. // output[_out++] = 0;
  7053. // } while (--op > whave);
  7054. // if (op === 0) {
  7055. // from = _out - dist;
  7056. // do {
  7057. // output[_out++] = output[from++];
  7058. // } while (--len);
  7059. // continue top;
  7060. // }
  7061. //#endif
  7062. }
  7063. from = 0; // window index
  7064. from_source = s_window;
  7065. if (wnext === 0) { /* very common case */
  7066. from += wsize - op;
  7067. if (op < len) { /* some from window */
  7068. len -= op;
  7069. do {
  7070. output[_out++] = s_window[from++];
  7071. } while (--op);
  7072. from = _out - dist; /* rest from output */
  7073. from_source = output;
  7074. }
  7075. }
  7076. else if (wnext < op) { /* wrap around window */
  7077. from += wsize + wnext - op;
  7078. op -= wnext;
  7079. if (op < len) { /* some from end of window */
  7080. len -= op;
  7081. do {
  7082. output[_out++] = s_window[from++];
  7083. } while (--op);
  7084. from = 0;
  7085. if (wnext < len) { /* some from start of window */
  7086. op = wnext;
  7087. len -= op;
  7088. do {
  7089. output[_out++] = s_window[from++];
  7090. } while (--op);
  7091. from = _out - dist; /* rest from output */
  7092. from_source = output;
  7093. }
  7094. }
  7095. }
  7096. else { /* contiguous in window */
  7097. from += wnext - op;
  7098. if (op < len) { /* some from window */
  7099. len -= op;
  7100. do {
  7101. output[_out++] = s_window[from++];
  7102. } while (--op);
  7103. from = _out - dist; /* rest from output */
  7104. from_source = output;
  7105. }
  7106. }
  7107. while (len > 2) {
  7108. output[_out++] = from_source[from++];
  7109. output[_out++] = from_source[from++];
  7110. output[_out++] = from_source[from++];
  7111. len -= 3;
  7112. }
  7113. if (len) {
  7114. output[_out++] = from_source[from++];
  7115. if (len > 1) {
  7116. output[_out++] = from_source[from++];
  7117. }
  7118. }
  7119. }
  7120. else {
  7121. from = _out - dist; /* copy direct from output */
  7122. do { /* minimum length is three */
  7123. output[_out++] = output[from++];
  7124. output[_out++] = output[from++];
  7125. output[_out++] = output[from++];
  7126. len -= 3;
  7127. } while (len > 2);
  7128. if (len) {
  7129. output[_out++] = output[from++];
  7130. if (len > 1) {
  7131. output[_out++] = output[from++];
  7132. }
  7133. }
  7134. }
  7135. }
  7136. else if ((op & 64) === 0) { /* 2nd level distance code */
  7137. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7138. continue dodist;
  7139. }
  7140. else {
  7141. strm.msg = 'invalid distance code';
  7142. state.mode = BAD;
  7143. break top;
  7144. }
  7145. break; // need to emulate goto via "continue"
  7146. }
  7147. }
  7148. else if ((op & 64) === 0) { /* 2nd level length code */
  7149. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7150. continue dolen;
  7151. }
  7152. else if (op & 32) { /* end-of-block */
  7153. //Tracevv((stderr, "inflate: end of block\n"));
  7154. state.mode = TYPE;
  7155. break top;
  7156. }
  7157. else {
  7158. strm.msg = 'invalid literal/length code';
  7159. state.mode = BAD;
  7160. break top;
  7161. }
  7162. break; // need to emulate goto via "continue"
  7163. }
  7164. } while (_in < last && _out < end);
  7165. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  7166. len = bits >> 3;
  7167. _in -= len;
  7168. bits -= len << 3;
  7169. hold &= (1 << bits) - 1;
  7170. /* update state and return */
  7171. strm.next_in = _in;
  7172. strm.next_out = _out;
  7173. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  7174. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  7175. state.hold = hold;
  7176. state.bits = bits;
  7177. return;
  7178. };
  7179. },{}],49:[function(require,module,exports){
  7180. 'use strict';
  7181. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7182. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7183. //
  7184. // This software is provided 'as-is', without any express or implied
  7185. // warranty. In no event will the authors be held liable for any damages
  7186. // arising from the use of this software.
  7187. //
  7188. // Permission is granted to anyone to use this software for any purpose,
  7189. // including commercial applications, and to alter it and redistribute it
  7190. // freely, subject to the following restrictions:
  7191. //
  7192. // 1. The origin of this software must not be misrepresented; you must not
  7193. // claim that you wrote the original software. If you use this software
  7194. // in a product, an acknowledgment in the product documentation would be
  7195. // appreciated but is not required.
  7196. // 2. Altered source versions must be plainly marked as such, and must not be
  7197. // misrepresented as being the original software.
  7198. // 3. This notice may not be removed or altered from any source distribution.
  7199. var utils = require('../utils/common');
  7200. var adler32 = require('./adler32');
  7201. var crc32 = require('./crc32');
  7202. var inflate_fast = require('./inffast');
  7203. var inflate_table = require('./inftrees');
  7204. var CODES = 0;
  7205. var LENS = 1;
  7206. var DISTS = 2;
  7207. /* Public constants ==========================================================*/
  7208. /* ===========================================================================*/
  7209. /* Allowed flush values; see deflate() and inflate() below for details */
  7210. //var Z_NO_FLUSH = 0;
  7211. //var Z_PARTIAL_FLUSH = 1;
  7212. //var Z_SYNC_FLUSH = 2;
  7213. //var Z_FULL_FLUSH = 3;
  7214. var Z_FINISH = 4;
  7215. var Z_BLOCK = 5;
  7216. var Z_TREES = 6;
  7217. /* Return codes for the compression/decompression functions. Negative values
  7218. * are errors, positive values are used for special but normal events.
  7219. */
  7220. var Z_OK = 0;
  7221. var Z_STREAM_END = 1;
  7222. var Z_NEED_DICT = 2;
  7223. //var Z_ERRNO = -1;
  7224. var Z_STREAM_ERROR = -2;
  7225. var Z_DATA_ERROR = -3;
  7226. var Z_MEM_ERROR = -4;
  7227. var Z_BUF_ERROR = -5;
  7228. //var Z_VERSION_ERROR = -6;
  7229. /* The deflate compression method */
  7230. var Z_DEFLATED = 8;
  7231. /* STATES ====================================================================*/
  7232. /* ===========================================================================*/
  7233. var HEAD = 1; /* i: waiting for magic header */
  7234. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  7235. var TIME = 3; /* i: waiting for modification time (gzip) */
  7236. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  7237. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  7238. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  7239. var NAME = 7; /* i: waiting for end of file name (gzip) */
  7240. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  7241. var HCRC = 9; /* i: waiting for header crc (gzip) */
  7242. var DICTID = 10; /* i: waiting for dictionary check value */
  7243. var DICT = 11; /* waiting for inflateSetDictionary() call */
  7244. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7245. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  7246. var STORED = 14; /* i: waiting for stored size (length and complement) */
  7247. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  7248. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  7249. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  7250. var LENLENS = 18; /* i: waiting for code length code lengths */
  7251. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  7252. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  7253. var LEN = 21; /* i: waiting for length/lit/eob code */
  7254. var LENEXT = 22; /* i: waiting for length extra bits */
  7255. var DIST = 23; /* i: waiting for distance code */
  7256. var DISTEXT = 24; /* i: waiting for distance extra bits */
  7257. var MATCH = 25; /* o: waiting for output space to copy string */
  7258. var LIT = 26; /* o: waiting for output space to write literal */
  7259. var CHECK = 27; /* i: waiting for 32-bit check value */
  7260. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  7261. var DONE = 29; /* finished check, done -- remain here until reset */
  7262. var BAD = 30; /* got a data error -- remain here until reset */
  7263. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  7264. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  7265. /* ===========================================================================*/
  7266. var ENOUGH_LENS = 852;
  7267. var ENOUGH_DISTS = 592;
  7268. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7269. var MAX_WBITS = 15;
  7270. /* 32K LZ77 window */
  7271. var DEF_WBITS = MAX_WBITS;
  7272. function zswap32(q) {
  7273. return (((q >>> 24) & 0xff) +
  7274. ((q >>> 8) & 0xff00) +
  7275. ((q & 0xff00) << 8) +
  7276. ((q & 0xff) << 24));
  7277. }
  7278. function InflateState() {
  7279. this.mode = 0; /* current inflate mode */
  7280. this.last = false; /* true if processing last block */
  7281. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7282. this.havedict = false; /* true if dictionary provided */
  7283. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  7284. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  7285. this.check = 0; /* protected copy of check value */
  7286. this.total = 0; /* protected copy of output count */
  7287. // TODO: may be {}
  7288. this.head = null; /* where to save gzip header information */
  7289. /* sliding window */
  7290. this.wbits = 0; /* log base 2 of requested window size */
  7291. this.wsize = 0; /* window size or zero if not using window */
  7292. this.whave = 0; /* valid bytes in the window */
  7293. this.wnext = 0; /* window write index */
  7294. this.window = null; /* allocated sliding window, if needed */
  7295. /* bit accumulator */
  7296. this.hold = 0; /* input bit accumulator */
  7297. this.bits = 0; /* number of bits in "in" */
  7298. /* for string and stored block copying */
  7299. this.length = 0; /* literal or length of data to copy */
  7300. this.offset = 0; /* distance back to copy string from */
  7301. /* for table and code decoding */
  7302. this.extra = 0; /* extra bits needed */
  7303. /* fixed and dynamic code tables */
  7304. this.lencode = null; /* starting table for length/literal codes */
  7305. this.distcode = null; /* starting table for distance codes */
  7306. this.lenbits = 0; /* index bits for lencode */
  7307. this.distbits = 0; /* index bits for distcode */
  7308. /* dynamic table building */
  7309. this.ncode = 0; /* number of code length code lengths */
  7310. this.nlen = 0; /* number of length code lengths */
  7311. this.ndist = 0; /* number of distance code lengths */
  7312. this.have = 0; /* number of code lengths in lens[] */
  7313. this.next = null; /* next available space in codes[] */
  7314. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  7315. this.work = new utils.Buf16(288); /* work area for code table building */
  7316. /*
  7317. because we don't have pointers in js, we use lencode and distcode directly
  7318. as buffers so we don't need codes
  7319. */
  7320. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  7321. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  7322. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  7323. this.sane = 0; /* if false, allow invalid distance too far */
  7324. this.back = 0; /* bits back of last unprocessed length/lit */
  7325. this.was = 0; /* initial length of match */
  7326. }
  7327. function inflateResetKeep(strm) {
  7328. var state;
  7329. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7330. state = strm.state;
  7331. strm.total_in = strm.total_out = state.total = 0;
  7332. strm.msg = ''; /*Z_NULL*/
  7333. if (state.wrap) { /* to support ill-conceived Java test suite */
  7334. strm.adler = state.wrap & 1;
  7335. }
  7336. state.mode = HEAD;
  7337. state.last = 0;
  7338. state.havedict = 0;
  7339. state.dmax = 32768;
  7340. state.head = null/*Z_NULL*/;
  7341. state.hold = 0;
  7342. state.bits = 0;
  7343. //state.lencode = state.distcode = state.next = state.codes;
  7344. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  7345. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  7346. state.sane = 1;
  7347. state.back = -1;
  7348. //Tracev((stderr, "inflate: reset\n"));
  7349. return Z_OK;
  7350. }
  7351. function inflateReset(strm) {
  7352. var state;
  7353. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7354. state = strm.state;
  7355. state.wsize = 0;
  7356. state.whave = 0;
  7357. state.wnext = 0;
  7358. return inflateResetKeep(strm);
  7359. }
  7360. function inflateReset2(strm, windowBits) {
  7361. var wrap;
  7362. var state;
  7363. /* get the state */
  7364. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7365. state = strm.state;
  7366. /* extract wrap request from windowBits parameter */
  7367. if (windowBits < 0) {
  7368. wrap = 0;
  7369. windowBits = -windowBits;
  7370. }
  7371. else {
  7372. wrap = (windowBits >> 4) + 1;
  7373. if (windowBits < 48) {
  7374. windowBits &= 15;
  7375. }
  7376. }
  7377. /* set number of window bits, free window if different */
  7378. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  7379. return Z_STREAM_ERROR;
  7380. }
  7381. if (state.window !== null && state.wbits !== windowBits) {
  7382. state.window = null;
  7383. }
  7384. /* update state and reset the rest of it */
  7385. state.wrap = wrap;
  7386. state.wbits = windowBits;
  7387. return inflateReset(strm);
  7388. }
  7389. function inflateInit2(strm, windowBits) {
  7390. var ret;
  7391. var state;
  7392. if (!strm) { return Z_STREAM_ERROR; }
  7393. //strm.msg = Z_NULL; /* in case we return an error */
  7394. state = new InflateState();
  7395. //if (state === Z_NULL) return Z_MEM_ERROR;
  7396. //Tracev((stderr, "inflate: allocated\n"));
  7397. strm.state = state;
  7398. state.window = null/*Z_NULL*/;
  7399. ret = inflateReset2(strm, windowBits);
  7400. if (ret !== Z_OK) {
  7401. strm.state = null/*Z_NULL*/;
  7402. }
  7403. return ret;
  7404. }
  7405. function inflateInit(strm) {
  7406. return inflateInit2(strm, DEF_WBITS);
  7407. }
  7408. /*
  7409. Return state with length and distance decoding tables and index sizes set to
  7410. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  7411. If BUILDFIXED is defined, then instead this routine builds the tables the
  7412. first time it's called, and returns those tables the first time and
  7413. thereafter. This reduces the size of the code by about 2K bytes, in
  7414. exchange for a little execution time. However, BUILDFIXED should not be
  7415. used for threaded applications, since the rewriting of the tables and virgin
  7416. may not be thread-safe.
  7417. */
  7418. var virgin = true;
  7419. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  7420. function fixedtables(state) {
  7421. /* build fixed huffman tables if first call (may not be thread safe) */
  7422. if (virgin) {
  7423. var sym;
  7424. lenfix = new utils.Buf32(512);
  7425. distfix = new utils.Buf32(32);
  7426. /* literal/length table */
  7427. sym = 0;
  7428. while (sym < 144) { state.lens[sym++] = 8; }
  7429. while (sym < 256) { state.lens[sym++] = 9; }
  7430. while (sym < 280) { state.lens[sym++] = 7; }
  7431. while (sym < 288) { state.lens[sym++] = 8; }
  7432. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  7433. /* distance table */
  7434. sym = 0;
  7435. while (sym < 32) { state.lens[sym++] = 5; }
  7436. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  7437. /* do this just once */
  7438. virgin = false;
  7439. }
  7440. state.lencode = lenfix;
  7441. state.lenbits = 9;
  7442. state.distcode = distfix;
  7443. state.distbits = 5;
  7444. }
  7445. /*
  7446. Update the window with the last wsize (normally 32K) bytes written before
  7447. returning. If window does not exist yet, create it. This is only called
  7448. when a window is already in use, or when output has been written during this
  7449. inflate call, but the end of the deflate stream has not been reached yet.
  7450. It is also called to create a window for dictionary data when a dictionary
  7451. is loaded.
  7452. Providing output buffers larger than 32K to inflate() should provide a speed
  7453. advantage, since only the last 32K of output is copied to the sliding window
  7454. upon return from inflate(), and since all distances after the first 32K of
  7455. output will fall in the output data, making match copies simpler and faster.
  7456. The advantage may be dependent on the size of the processor's data caches.
  7457. */
  7458. function updatewindow(strm, src, end, copy) {
  7459. var dist;
  7460. var state = strm.state;
  7461. /* if it hasn't been done already, allocate space for the window */
  7462. if (state.window === null) {
  7463. state.wsize = 1 << state.wbits;
  7464. state.wnext = 0;
  7465. state.whave = 0;
  7466. state.window = new utils.Buf8(state.wsize);
  7467. }
  7468. /* copy state->wsize or less output bytes into the circular window */
  7469. if (copy >= state.wsize) {
  7470. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  7471. state.wnext = 0;
  7472. state.whave = state.wsize;
  7473. }
  7474. else {
  7475. dist = state.wsize - state.wnext;
  7476. if (dist > copy) {
  7477. dist = copy;
  7478. }
  7479. //zmemcpy(state->window + state->wnext, end - copy, dist);
  7480. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  7481. copy -= dist;
  7482. if (copy) {
  7483. //zmemcpy(state->window, end - copy, copy);
  7484. utils.arraySet(state.window, src, end - copy, copy, 0);
  7485. state.wnext = copy;
  7486. state.whave = state.wsize;
  7487. }
  7488. else {
  7489. state.wnext += dist;
  7490. if (state.wnext === state.wsize) { state.wnext = 0; }
  7491. if (state.whave < state.wsize) { state.whave += dist; }
  7492. }
  7493. }
  7494. return 0;
  7495. }
  7496. function inflate(strm, flush) {
  7497. var state;
  7498. var input, output; // input/output buffers
  7499. var next; /* next input INDEX */
  7500. var put; /* next output INDEX */
  7501. var have, left; /* available input and output */
  7502. var hold; /* bit buffer */
  7503. var bits; /* bits in bit buffer */
  7504. var _in, _out; /* save starting available input and output */
  7505. var copy; /* number of stored or match bytes to copy */
  7506. var from; /* where to copy match bytes from */
  7507. var from_source;
  7508. var here = 0; /* current decoding table entry */
  7509. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  7510. //var last; /* parent table entry */
  7511. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  7512. var len; /* length to copy for repeats, bits to drop */
  7513. var ret; /* return code */
  7514. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  7515. var opts;
  7516. var n; // temporary var for NEED_BITS
  7517. var order = /* permutation of code lengths */
  7518. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  7519. if (!strm || !strm.state || !strm.output ||
  7520. (!strm.input && strm.avail_in !== 0)) {
  7521. return Z_STREAM_ERROR;
  7522. }
  7523. state = strm.state;
  7524. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  7525. //--- LOAD() ---
  7526. put = strm.next_out;
  7527. output = strm.output;
  7528. left = strm.avail_out;
  7529. next = strm.next_in;
  7530. input = strm.input;
  7531. have = strm.avail_in;
  7532. hold = state.hold;
  7533. bits = state.bits;
  7534. //---
  7535. _in = have;
  7536. _out = left;
  7537. ret = Z_OK;
  7538. inf_leave: // goto emulation
  7539. for (;;) {
  7540. switch (state.mode) {
  7541. case HEAD:
  7542. if (state.wrap === 0) {
  7543. state.mode = TYPEDO;
  7544. break;
  7545. }
  7546. //=== NEEDBITS(16);
  7547. while (bits < 16) {
  7548. if (have === 0) { break inf_leave; }
  7549. have--;
  7550. hold += input[next++] << bits;
  7551. bits += 8;
  7552. }
  7553. //===//
  7554. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  7555. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  7556. //=== CRC2(state.check, hold);
  7557. hbuf[0] = hold & 0xff;
  7558. hbuf[1] = (hold >>> 8) & 0xff;
  7559. state.check = crc32(state.check, hbuf, 2, 0);
  7560. //===//
  7561. //=== INITBITS();
  7562. hold = 0;
  7563. bits = 0;
  7564. //===//
  7565. state.mode = FLAGS;
  7566. break;
  7567. }
  7568. state.flags = 0; /* expect zlib header */
  7569. if (state.head) {
  7570. state.head.done = false;
  7571. }
  7572. if (!(state.wrap & 1) || /* check if zlib header allowed */
  7573. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  7574. strm.msg = 'incorrect header check';
  7575. state.mode = BAD;
  7576. break;
  7577. }
  7578. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  7579. strm.msg = 'unknown compression method';
  7580. state.mode = BAD;
  7581. break;
  7582. }
  7583. //--- DROPBITS(4) ---//
  7584. hold >>>= 4;
  7585. bits -= 4;
  7586. //---//
  7587. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  7588. if (state.wbits === 0) {
  7589. state.wbits = len;
  7590. }
  7591. else if (len > state.wbits) {
  7592. strm.msg = 'invalid window size';
  7593. state.mode = BAD;
  7594. break;
  7595. }
  7596. state.dmax = 1 << len;
  7597. //Tracev((stderr, "inflate: zlib header ok\n"));
  7598. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  7599. state.mode = hold & 0x200 ? DICTID : TYPE;
  7600. //=== INITBITS();
  7601. hold = 0;
  7602. bits = 0;
  7603. //===//
  7604. break;
  7605. case FLAGS:
  7606. //=== NEEDBITS(16); */
  7607. while (bits < 16) {
  7608. if (have === 0) { break inf_leave; }
  7609. have--;
  7610. hold += input[next++] << bits;
  7611. bits += 8;
  7612. }
  7613. //===//
  7614. state.flags = hold;
  7615. if ((state.flags & 0xff) !== Z_DEFLATED) {
  7616. strm.msg = 'unknown compression method';
  7617. state.mode = BAD;
  7618. break;
  7619. }
  7620. if (state.flags & 0xe000) {
  7621. strm.msg = 'unknown header flags set';
  7622. state.mode = BAD;
  7623. break;
  7624. }
  7625. if (state.head) {
  7626. state.head.text = ((hold >> 8) & 1);
  7627. }
  7628. if (state.flags & 0x0200) {
  7629. //=== CRC2(state.check, hold);
  7630. hbuf[0] = hold & 0xff;
  7631. hbuf[1] = (hold >>> 8) & 0xff;
  7632. state.check = crc32(state.check, hbuf, 2, 0);
  7633. //===//
  7634. }
  7635. //=== INITBITS();
  7636. hold = 0;
  7637. bits = 0;
  7638. //===//
  7639. state.mode = TIME;
  7640. /* falls through */
  7641. case TIME:
  7642. //=== NEEDBITS(32); */
  7643. while (bits < 32) {
  7644. if (have === 0) { break inf_leave; }
  7645. have--;
  7646. hold += input[next++] << bits;
  7647. bits += 8;
  7648. }
  7649. //===//
  7650. if (state.head) {
  7651. state.head.time = hold;
  7652. }
  7653. if (state.flags & 0x0200) {
  7654. //=== CRC4(state.check, hold)
  7655. hbuf[0] = hold & 0xff;
  7656. hbuf[1] = (hold >>> 8) & 0xff;
  7657. hbuf[2] = (hold >>> 16) & 0xff;
  7658. hbuf[3] = (hold >>> 24) & 0xff;
  7659. state.check = crc32(state.check, hbuf, 4, 0);
  7660. //===
  7661. }
  7662. //=== INITBITS();
  7663. hold = 0;
  7664. bits = 0;
  7665. //===//
  7666. state.mode = OS;
  7667. /* falls through */
  7668. case OS:
  7669. //=== NEEDBITS(16); */
  7670. while (bits < 16) {
  7671. if (have === 0) { break inf_leave; }
  7672. have--;
  7673. hold += input[next++] << bits;
  7674. bits += 8;
  7675. }
  7676. //===//
  7677. if (state.head) {
  7678. state.head.xflags = (hold & 0xff);
  7679. state.head.os = (hold >> 8);
  7680. }
  7681. if (state.flags & 0x0200) {
  7682. //=== CRC2(state.check, hold);
  7683. hbuf[0] = hold & 0xff;
  7684. hbuf[1] = (hold >>> 8) & 0xff;
  7685. state.check = crc32(state.check, hbuf, 2, 0);
  7686. //===//
  7687. }
  7688. //=== INITBITS();
  7689. hold = 0;
  7690. bits = 0;
  7691. //===//
  7692. state.mode = EXLEN;
  7693. /* falls through */
  7694. case EXLEN:
  7695. if (state.flags & 0x0400) {
  7696. //=== NEEDBITS(16); */
  7697. while (bits < 16) {
  7698. if (have === 0) { break inf_leave; }
  7699. have--;
  7700. hold += input[next++] << bits;
  7701. bits += 8;
  7702. }
  7703. //===//
  7704. state.length = hold;
  7705. if (state.head) {
  7706. state.head.extra_len = hold;
  7707. }
  7708. if (state.flags & 0x0200) {
  7709. //=== CRC2(state.check, hold);
  7710. hbuf[0] = hold & 0xff;
  7711. hbuf[1] = (hold >>> 8) & 0xff;
  7712. state.check = crc32(state.check, hbuf, 2, 0);
  7713. //===//
  7714. }
  7715. //=== INITBITS();
  7716. hold = 0;
  7717. bits = 0;
  7718. //===//
  7719. }
  7720. else if (state.head) {
  7721. state.head.extra = null/*Z_NULL*/;
  7722. }
  7723. state.mode = EXTRA;
  7724. /* falls through */
  7725. case EXTRA:
  7726. if (state.flags & 0x0400) {
  7727. copy = state.length;
  7728. if (copy > have) { copy = have; }
  7729. if (copy) {
  7730. if (state.head) {
  7731. len = state.head.extra_len - state.length;
  7732. if (!state.head.extra) {
  7733. // Use untyped array for more conveniend processing later
  7734. state.head.extra = new Array(state.head.extra_len);
  7735. }
  7736. utils.arraySet(
  7737. state.head.extra,
  7738. input,
  7739. next,
  7740. // extra field is limited to 65536 bytes
  7741. // - no need for additional size check
  7742. copy,
  7743. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  7744. len
  7745. );
  7746. //zmemcpy(state.head.extra + len, next,
  7747. // len + copy > state.head.extra_max ?
  7748. // state.head.extra_max - len : copy);
  7749. }
  7750. if (state.flags & 0x0200) {
  7751. state.check = crc32(state.check, input, copy, next);
  7752. }
  7753. have -= copy;
  7754. next += copy;
  7755. state.length -= copy;
  7756. }
  7757. if (state.length) { break inf_leave; }
  7758. }
  7759. state.length = 0;
  7760. state.mode = NAME;
  7761. /* falls through */
  7762. case NAME:
  7763. if (state.flags & 0x0800) {
  7764. if (have === 0) { break inf_leave; }
  7765. copy = 0;
  7766. do {
  7767. // TODO: 2 or 1 bytes?
  7768. len = input[next + copy++];
  7769. /* use constant limit because in js we should not preallocate memory */
  7770. if (state.head && len &&
  7771. (state.length < 65536 /*state.head.name_max*/)) {
  7772. state.head.name += String.fromCharCode(len);
  7773. }
  7774. } while (len && copy < have);
  7775. if (state.flags & 0x0200) {
  7776. state.check = crc32(state.check, input, copy, next);
  7777. }
  7778. have -= copy;
  7779. next += copy;
  7780. if (len) { break inf_leave; }
  7781. }
  7782. else if (state.head) {
  7783. state.head.name = null;
  7784. }
  7785. state.length = 0;
  7786. state.mode = COMMENT;
  7787. /* falls through */
  7788. case COMMENT:
  7789. if (state.flags & 0x1000) {
  7790. if (have === 0) { break inf_leave; }
  7791. copy = 0;
  7792. do {
  7793. len = input[next + copy++];
  7794. /* use constant limit because in js we should not preallocate memory */
  7795. if (state.head && len &&
  7796. (state.length < 65536 /*state.head.comm_max*/)) {
  7797. state.head.comment += String.fromCharCode(len);
  7798. }
  7799. } while (len && copy < have);
  7800. if (state.flags & 0x0200) {
  7801. state.check = crc32(state.check, input, copy, next);
  7802. }
  7803. have -= copy;
  7804. next += copy;
  7805. if (len) { break inf_leave; }
  7806. }
  7807. else if (state.head) {
  7808. state.head.comment = null;
  7809. }
  7810. state.mode = HCRC;
  7811. /* falls through */
  7812. case HCRC:
  7813. if (state.flags & 0x0200) {
  7814. //=== NEEDBITS(16); */
  7815. while (bits < 16) {
  7816. if (have === 0) { break inf_leave; }
  7817. have--;
  7818. hold += input[next++] << bits;
  7819. bits += 8;
  7820. }
  7821. //===//
  7822. if (hold !== (state.check & 0xffff)) {
  7823. strm.msg = 'header crc mismatch';
  7824. state.mode = BAD;
  7825. break;
  7826. }
  7827. //=== INITBITS();
  7828. hold = 0;
  7829. bits = 0;
  7830. //===//
  7831. }
  7832. if (state.head) {
  7833. state.head.hcrc = ((state.flags >> 9) & 1);
  7834. state.head.done = true;
  7835. }
  7836. strm.adler = state.check = 0;
  7837. state.mode = TYPE;
  7838. break;
  7839. case DICTID:
  7840. //=== NEEDBITS(32); */
  7841. while (bits < 32) {
  7842. if (have === 0) { break inf_leave; }
  7843. have--;
  7844. hold += input[next++] << bits;
  7845. bits += 8;
  7846. }
  7847. //===//
  7848. strm.adler = state.check = zswap32(hold);
  7849. //=== INITBITS();
  7850. hold = 0;
  7851. bits = 0;
  7852. //===//
  7853. state.mode = DICT;
  7854. /* falls through */
  7855. case DICT:
  7856. if (state.havedict === 0) {
  7857. //--- RESTORE() ---
  7858. strm.next_out = put;
  7859. strm.avail_out = left;
  7860. strm.next_in = next;
  7861. strm.avail_in = have;
  7862. state.hold = hold;
  7863. state.bits = bits;
  7864. //---
  7865. return Z_NEED_DICT;
  7866. }
  7867. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  7868. state.mode = TYPE;
  7869. /* falls through */
  7870. case TYPE:
  7871. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  7872. /* falls through */
  7873. case TYPEDO:
  7874. if (state.last) {
  7875. //--- BYTEBITS() ---//
  7876. hold >>>= bits & 7;
  7877. bits -= bits & 7;
  7878. //---//
  7879. state.mode = CHECK;
  7880. break;
  7881. }
  7882. //=== NEEDBITS(3); */
  7883. while (bits < 3) {
  7884. if (have === 0) { break inf_leave; }
  7885. have--;
  7886. hold += input[next++] << bits;
  7887. bits += 8;
  7888. }
  7889. //===//
  7890. state.last = (hold & 0x01)/*BITS(1)*/;
  7891. //--- DROPBITS(1) ---//
  7892. hold >>>= 1;
  7893. bits -= 1;
  7894. //---//
  7895. switch ((hold & 0x03)/*BITS(2)*/) {
  7896. case 0: /* stored block */
  7897. //Tracev((stderr, "inflate: stored block%s\n",
  7898. // state.last ? " (last)" : ""));
  7899. state.mode = STORED;
  7900. break;
  7901. case 1: /* fixed block */
  7902. fixedtables(state);
  7903. //Tracev((stderr, "inflate: fixed codes block%s\n",
  7904. // state.last ? " (last)" : ""));
  7905. state.mode = LEN_; /* decode codes */
  7906. if (flush === Z_TREES) {
  7907. //--- DROPBITS(2) ---//
  7908. hold >>>= 2;
  7909. bits -= 2;
  7910. //---//
  7911. break inf_leave;
  7912. }
  7913. break;
  7914. case 2: /* dynamic block */
  7915. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  7916. // state.last ? " (last)" : ""));
  7917. state.mode = TABLE;
  7918. break;
  7919. case 3:
  7920. strm.msg = 'invalid block type';
  7921. state.mode = BAD;
  7922. }
  7923. //--- DROPBITS(2) ---//
  7924. hold >>>= 2;
  7925. bits -= 2;
  7926. //---//
  7927. break;
  7928. case STORED:
  7929. //--- BYTEBITS() ---// /* go to byte boundary */
  7930. hold >>>= bits & 7;
  7931. bits -= bits & 7;
  7932. //---//
  7933. //=== NEEDBITS(32); */
  7934. while (bits < 32) {
  7935. if (have === 0) { break inf_leave; }
  7936. have--;
  7937. hold += input[next++] << bits;
  7938. bits += 8;
  7939. }
  7940. //===//
  7941. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  7942. strm.msg = 'invalid stored block lengths';
  7943. state.mode = BAD;
  7944. break;
  7945. }
  7946. state.length = hold & 0xffff;
  7947. //Tracev((stderr, "inflate: stored length %u\n",
  7948. // state.length));
  7949. //=== INITBITS();
  7950. hold = 0;
  7951. bits = 0;
  7952. //===//
  7953. state.mode = COPY_;
  7954. if (flush === Z_TREES) { break inf_leave; }
  7955. /* falls through */
  7956. case COPY_:
  7957. state.mode = COPY;
  7958. /* falls through */
  7959. case COPY:
  7960. copy = state.length;
  7961. if (copy) {
  7962. if (copy > have) { copy = have; }
  7963. if (copy > left) { copy = left; }
  7964. if (copy === 0) { break inf_leave; }
  7965. //--- zmemcpy(put, next, copy); ---
  7966. utils.arraySet(output, input, next, copy, put);
  7967. //---//
  7968. have -= copy;
  7969. next += copy;
  7970. left -= copy;
  7971. put += copy;
  7972. state.length -= copy;
  7973. break;
  7974. }
  7975. //Tracev((stderr, "inflate: stored end\n"));
  7976. state.mode = TYPE;
  7977. break;
  7978. case TABLE:
  7979. //=== NEEDBITS(14); */
  7980. while (bits < 14) {
  7981. if (have === 0) { break inf_leave; }
  7982. have--;
  7983. hold += input[next++] << bits;
  7984. bits += 8;
  7985. }
  7986. //===//
  7987. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  7988. //--- DROPBITS(5) ---//
  7989. hold >>>= 5;
  7990. bits -= 5;
  7991. //---//
  7992. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  7993. //--- DROPBITS(5) ---//
  7994. hold >>>= 5;
  7995. bits -= 5;
  7996. //---//
  7997. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  7998. //--- DROPBITS(4) ---//
  7999. hold >>>= 4;
  8000. bits -= 4;
  8001. //---//
  8002. //#ifndef PKZIP_BUG_WORKAROUND
  8003. if (state.nlen > 286 || state.ndist > 30) {
  8004. strm.msg = 'too many length or distance symbols';
  8005. state.mode = BAD;
  8006. break;
  8007. }
  8008. //#endif
  8009. //Tracev((stderr, "inflate: table sizes ok\n"));
  8010. state.have = 0;
  8011. state.mode = LENLENS;
  8012. /* falls through */
  8013. case LENLENS:
  8014. while (state.have < state.ncode) {
  8015. //=== NEEDBITS(3);
  8016. while (bits < 3) {
  8017. if (have === 0) { break inf_leave; }
  8018. have--;
  8019. hold += input[next++] << bits;
  8020. bits += 8;
  8021. }
  8022. //===//
  8023. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  8024. //--- DROPBITS(3) ---//
  8025. hold >>>= 3;
  8026. bits -= 3;
  8027. //---//
  8028. }
  8029. while (state.have < 19) {
  8030. state.lens[order[state.have++]] = 0;
  8031. }
  8032. // We have separate tables & no pointers. 2 commented lines below not needed.
  8033. //state.next = state.codes;
  8034. //state.lencode = state.next;
  8035. // Switch to use dynamic table
  8036. state.lencode = state.lendyn;
  8037. state.lenbits = 7;
  8038. opts = { bits: state.lenbits };
  8039. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  8040. state.lenbits = opts.bits;
  8041. if (ret) {
  8042. strm.msg = 'invalid code lengths set';
  8043. state.mode = BAD;
  8044. break;
  8045. }
  8046. //Tracev((stderr, "inflate: code lengths ok\n"));
  8047. state.have = 0;
  8048. state.mode = CODELENS;
  8049. /* falls through */
  8050. case CODELENS:
  8051. while (state.have < state.nlen + state.ndist) {
  8052. for (;;) {
  8053. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  8054. here_bits = here >>> 24;
  8055. here_op = (here >>> 16) & 0xff;
  8056. here_val = here & 0xffff;
  8057. if ((here_bits) <= bits) { break; }
  8058. //--- PULLBYTE() ---//
  8059. if (have === 0) { break inf_leave; }
  8060. have--;
  8061. hold += input[next++] << bits;
  8062. bits += 8;
  8063. //---//
  8064. }
  8065. if (here_val < 16) {
  8066. //--- DROPBITS(here.bits) ---//
  8067. hold >>>= here_bits;
  8068. bits -= here_bits;
  8069. //---//
  8070. state.lens[state.have++] = here_val;
  8071. }
  8072. else {
  8073. if (here_val === 16) {
  8074. //=== NEEDBITS(here.bits + 2);
  8075. n = here_bits + 2;
  8076. while (bits < n) {
  8077. if (have === 0) { break inf_leave; }
  8078. have--;
  8079. hold += input[next++] << bits;
  8080. bits += 8;
  8081. }
  8082. //===//
  8083. //--- DROPBITS(here.bits) ---//
  8084. hold >>>= here_bits;
  8085. bits -= here_bits;
  8086. //---//
  8087. if (state.have === 0) {
  8088. strm.msg = 'invalid bit length repeat';
  8089. state.mode = BAD;
  8090. break;
  8091. }
  8092. len = state.lens[state.have - 1];
  8093. copy = 3 + (hold & 0x03);//BITS(2);
  8094. //--- DROPBITS(2) ---//
  8095. hold >>>= 2;
  8096. bits -= 2;
  8097. //---//
  8098. }
  8099. else if (here_val === 17) {
  8100. //=== NEEDBITS(here.bits + 3);
  8101. n = here_bits + 3;
  8102. while (bits < n) {
  8103. if (have === 0) { break inf_leave; }
  8104. have--;
  8105. hold += input[next++] << bits;
  8106. bits += 8;
  8107. }
  8108. //===//
  8109. //--- DROPBITS(here.bits) ---//
  8110. hold >>>= here_bits;
  8111. bits -= here_bits;
  8112. //---//
  8113. len = 0;
  8114. copy = 3 + (hold & 0x07);//BITS(3);
  8115. //--- DROPBITS(3) ---//
  8116. hold >>>= 3;
  8117. bits -= 3;
  8118. //---//
  8119. }
  8120. else {
  8121. //=== NEEDBITS(here.bits + 7);
  8122. n = here_bits + 7;
  8123. while (bits < n) {
  8124. if (have === 0) { break inf_leave; }
  8125. have--;
  8126. hold += input[next++] << bits;
  8127. bits += 8;
  8128. }
  8129. //===//
  8130. //--- DROPBITS(here.bits) ---//
  8131. hold >>>= here_bits;
  8132. bits -= here_bits;
  8133. //---//
  8134. len = 0;
  8135. copy = 11 + (hold & 0x7f);//BITS(7);
  8136. //--- DROPBITS(7) ---//
  8137. hold >>>= 7;
  8138. bits -= 7;
  8139. //---//
  8140. }
  8141. if (state.have + copy > state.nlen + state.ndist) {
  8142. strm.msg = 'invalid bit length repeat';
  8143. state.mode = BAD;
  8144. break;
  8145. }
  8146. while (copy--) {
  8147. state.lens[state.have++] = len;
  8148. }
  8149. }
  8150. }
  8151. /* handle error breaks in while */
  8152. if (state.mode === BAD) { break; }
  8153. /* check for end-of-block code (better have one) */
  8154. if (state.lens[256] === 0) {
  8155. strm.msg = 'invalid code -- missing end-of-block';
  8156. state.mode = BAD;
  8157. break;
  8158. }
  8159. /* build code tables -- note: do not change the lenbits or distbits
  8160. values here (9 and 6) without reading the comments in inftrees.h
  8161. concerning the ENOUGH constants, which depend on those values */
  8162. state.lenbits = 9;
  8163. opts = { bits: state.lenbits };
  8164. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  8165. // We have separate tables & no pointers. 2 commented lines below not needed.
  8166. // state.next_index = opts.table_index;
  8167. state.lenbits = opts.bits;
  8168. // state.lencode = state.next;
  8169. if (ret) {
  8170. strm.msg = 'invalid literal/lengths set';
  8171. state.mode = BAD;
  8172. break;
  8173. }
  8174. state.distbits = 6;
  8175. //state.distcode.copy(state.codes);
  8176. // Switch to use dynamic table
  8177. state.distcode = state.distdyn;
  8178. opts = { bits: state.distbits };
  8179. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  8180. // We have separate tables & no pointers. 2 commented lines below not needed.
  8181. // state.next_index = opts.table_index;
  8182. state.distbits = opts.bits;
  8183. // state.distcode = state.next;
  8184. if (ret) {
  8185. strm.msg = 'invalid distances set';
  8186. state.mode = BAD;
  8187. break;
  8188. }
  8189. //Tracev((stderr, 'inflate: codes ok\n'));
  8190. state.mode = LEN_;
  8191. if (flush === Z_TREES) { break inf_leave; }
  8192. /* falls through */
  8193. case LEN_:
  8194. state.mode = LEN;
  8195. /* falls through */
  8196. case LEN:
  8197. if (have >= 6 && left >= 258) {
  8198. //--- RESTORE() ---
  8199. strm.next_out = put;
  8200. strm.avail_out = left;
  8201. strm.next_in = next;
  8202. strm.avail_in = have;
  8203. state.hold = hold;
  8204. state.bits = bits;
  8205. //---
  8206. inflate_fast(strm, _out);
  8207. //--- LOAD() ---
  8208. put = strm.next_out;
  8209. output = strm.output;
  8210. left = strm.avail_out;
  8211. next = strm.next_in;
  8212. input = strm.input;
  8213. have = strm.avail_in;
  8214. hold = state.hold;
  8215. bits = state.bits;
  8216. //---
  8217. if (state.mode === TYPE) {
  8218. state.back = -1;
  8219. }
  8220. break;
  8221. }
  8222. state.back = 0;
  8223. for (;;) {
  8224. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  8225. here_bits = here >>> 24;
  8226. here_op = (here >>> 16) & 0xff;
  8227. here_val = here & 0xffff;
  8228. if (here_bits <= bits) { break; }
  8229. //--- PULLBYTE() ---//
  8230. if (have === 0) { break inf_leave; }
  8231. have--;
  8232. hold += input[next++] << bits;
  8233. bits += 8;
  8234. //---//
  8235. }
  8236. if (here_op && (here_op & 0xf0) === 0) {
  8237. last_bits = here_bits;
  8238. last_op = here_op;
  8239. last_val = here_val;
  8240. for (;;) {
  8241. here = state.lencode[last_val +
  8242. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8243. here_bits = here >>> 24;
  8244. here_op = (here >>> 16) & 0xff;
  8245. here_val = here & 0xffff;
  8246. if ((last_bits + here_bits) <= bits) { break; }
  8247. //--- PULLBYTE() ---//
  8248. if (have === 0) { break inf_leave; }
  8249. have--;
  8250. hold += input[next++] << bits;
  8251. bits += 8;
  8252. //---//
  8253. }
  8254. //--- DROPBITS(last.bits) ---//
  8255. hold >>>= last_bits;
  8256. bits -= last_bits;
  8257. //---//
  8258. state.back += last_bits;
  8259. }
  8260. //--- DROPBITS(here.bits) ---//
  8261. hold >>>= here_bits;
  8262. bits -= here_bits;
  8263. //---//
  8264. state.back += here_bits;
  8265. state.length = here_val;
  8266. if (here_op === 0) {
  8267. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8268. // "inflate: literal '%c'\n" :
  8269. // "inflate: literal 0x%02x\n", here.val));
  8270. state.mode = LIT;
  8271. break;
  8272. }
  8273. if (here_op & 32) {
  8274. //Tracevv((stderr, "inflate: end of block\n"));
  8275. state.back = -1;
  8276. state.mode = TYPE;
  8277. break;
  8278. }
  8279. if (here_op & 64) {
  8280. strm.msg = 'invalid literal/length code';
  8281. state.mode = BAD;
  8282. break;
  8283. }
  8284. state.extra = here_op & 15;
  8285. state.mode = LENEXT;
  8286. /* falls through */
  8287. case LENEXT:
  8288. if (state.extra) {
  8289. //=== NEEDBITS(state.extra);
  8290. n = state.extra;
  8291. while (bits < n) {
  8292. if (have === 0) { break inf_leave; }
  8293. have--;
  8294. hold += input[next++] << bits;
  8295. bits += 8;
  8296. }
  8297. //===//
  8298. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  8299. //--- DROPBITS(state.extra) ---//
  8300. hold >>>= state.extra;
  8301. bits -= state.extra;
  8302. //---//
  8303. state.back += state.extra;
  8304. }
  8305. //Tracevv((stderr, "inflate: length %u\n", state.length));
  8306. state.was = state.length;
  8307. state.mode = DIST;
  8308. /* falls through */
  8309. case DIST:
  8310. for (;;) {
  8311. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  8312. here_bits = here >>> 24;
  8313. here_op = (here >>> 16) & 0xff;
  8314. here_val = here & 0xffff;
  8315. if ((here_bits) <= bits) { break; }
  8316. //--- PULLBYTE() ---//
  8317. if (have === 0) { break inf_leave; }
  8318. have--;
  8319. hold += input[next++] << bits;
  8320. bits += 8;
  8321. //---//
  8322. }
  8323. if ((here_op & 0xf0) === 0) {
  8324. last_bits = here_bits;
  8325. last_op = here_op;
  8326. last_val = here_val;
  8327. for (;;) {
  8328. here = state.distcode[last_val +
  8329. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8330. here_bits = here >>> 24;
  8331. here_op = (here >>> 16) & 0xff;
  8332. here_val = here & 0xffff;
  8333. if ((last_bits + here_bits) <= bits) { break; }
  8334. //--- PULLBYTE() ---//
  8335. if (have === 0) { break inf_leave; }
  8336. have--;
  8337. hold += input[next++] << bits;
  8338. bits += 8;
  8339. //---//
  8340. }
  8341. //--- DROPBITS(last.bits) ---//
  8342. hold >>>= last_bits;
  8343. bits -= last_bits;
  8344. //---//
  8345. state.back += last_bits;
  8346. }
  8347. //--- DROPBITS(here.bits) ---//
  8348. hold >>>= here_bits;
  8349. bits -= here_bits;
  8350. //---//
  8351. state.back += here_bits;
  8352. if (here_op & 64) {
  8353. strm.msg = 'invalid distance code';
  8354. state.mode = BAD;
  8355. break;
  8356. }
  8357. state.offset = here_val;
  8358. state.extra = (here_op) & 15;
  8359. state.mode = DISTEXT;
  8360. /* falls through */
  8361. case DISTEXT:
  8362. if (state.extra) {
  8363. //=== NEEDBITS(state.extra);
  8364. n = state.extra;
  8365. while (bits < n) {
  8366. if (have === 0) { break inf_leave; }
  8367. have--;
  8368. hold += input[next++] << bits;
  8369. bits += 8;
  8370. }
  8371. //===//
  8372. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  8373. //--- DROPBITS(state.extra) ---//
  8374. hold >>>= state.extra;
  8375. bits -= state.extra;
  8376. //---//
  8377. state.back += state.extra;
  8378. }
  8379. //#ifdef INFLATE_STRICT
  8380. if (state.offset > state.dmax) {
  8381. strm.msg = 'invalid distance too far back';
  8382. state.mode = BAD;
  8383. break;
  8384. }
  8385. //#endif
  8386. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  8387. state.mode = MATCH;
  8388. /* falls through */
  8389. case MATCH:
  8390. if (left === 0) { break inf_leave; }
  8391. copy = _out - left;
  8392. if (state.offset > copy) { /* copy from window */
  8393. copy = state.offset - copy;
  8394. if (copy > state.whave) {
  8395. if (state.sane) {
  8396. strm.msg = 'invalid distance too far back';
  8397. state.mode = BAD;
  8398. break;
  8399. }
  8400. // (!) This block is disabled in zlib defailts,
  8401. // don't enable it for binary compatibility
  8402. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8403. // Trace((stderr, "inflate.c too far\n"));
  8404. // copy -= state.whave;
  8405. // if (copy > state.length) { copy = state.length; }
  8406. // if (copy > left) { copy = left; }
  8407. // left -= copy;
  8408. // state.length -= copy;
  8409. // do {
  8410. // output[put++] = 0;
  8411. // } while (--copy);
  8412. // if (state.length === 0) { state.mode = LEN; }
  8413. // break;
  8414. //#endif
  8415. }
  8416. if (copy > state.wnext) {
  8417. copy -= state.wnext;
  8418. from = state.wsize - copy;
  8419. }
  8420. else {
  8421. from = state.wnext - copy;
  8422. }
  8423. if (copy > state.length) { copy = state.length; }
  8424. from_source = state.window;
  8425. }
  8426. else { /* copy from output */
  8427. from_source = output;
  8428. from = put - state.offset;
  8429. copy = state.length;
  8430. }
  8431. if (copy > left) { copy = left; }
  8432. left -= copy;
  8433. state.length -= copy;
  8434. do {
  8435. output[put++] = from_source[from++];
  8436. } while (--copy);
  8437. if (state.length === 0) { state.mode = LEN; }
  8438. break;
  8439. case LIT:
  8440. if (left === 0) { break inf_leave; }
  8441. output[put++] = state.length;
  8442. left--;
  8443. state.mode = LEN;
  8444. break;
  8445. case CHECK:
  8446. if (state.wrap) {
  8447. //=== NEEDBITS(32);
  8448. while (bits < 32) {
  8449. if (have === 0) { break inf_leave; }
  8450. have--;
  8451. // Use '|' insdead of '+' to make sure that result is signed
  8452. hold |= input[next++] << bits;
  8453. bits += 8;
  8454. }
  8455. //===//
  8456. _out -= left;
  8457. strm.total_out += _out;
  8458. state.total += _out;
  8459. if (_out) {
  8460. strm.adler = state.check =
  8461. /*UPDATE(state.check, put - _out, _out);*/
  8462. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  8463. }
  8464. _out = left;
  8465. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  8466. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  8467. strm.msg = 'incorrect data check';
  8468. state.mode = BAD;
  8469. break;
  8470. }
  8471. //=== INITBITS();
  8472. hold = 0;
  8473. bits = 0;
  8474. //===//
  8475. //Tracev((stderr, "inflate: check matches trailer\n"));
  8476. }
  8477. state.mode = LENGTH;
  8478. /* falls through */
  8479. case LENGTH:
  8480. if (state.wrap && state.flags) {
  8481. //=== NEEDBITS(32);
  8482. while (bits < 32) {
  8483. if (have === 0) { break inf_leave; }
  8484. have--;
  8485. hold += input[next++] << bits;
  8486. bits += 8;
  8487. }
  8488. //===//
  8489. if (hold !== (state.total & 0xffffffff)) {
  8490. strm.msg = 'incorrect length check';
  8491. state.mode = BAD;
  8492. break;
  8493. }
  8494. //=== INITBITS();
  8495. hold = 0;
  8496. bits = 0;
  8497. //===//
  8498. //Tracev((stderr, "inflate: length matches trailer\n"));
  8499. }
  8500. state.mode = DONE;
  8501. /* falls through */
  8502. case DONE:
  8503. ret = Z_STREAM_END;
  8504. break inf_leave;
  8505. case BAD:
  8506. ret = Z_DATA_ERROR;
  8507. break inf_leave;
  8508. case MEM:
  8509. return Z_MEM_ERROR;
  8510. case SYNC:
  8511. /* falls through */
  8512. default:
  8513. return Z_STREAM_ERROR;
  8514. }
  8515. }
  8516. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  8517. /*
  8518. Return from inflate(), updating the total counts and the check value.
  8519. If there was no progress during the inflate() call, return a buffer
  8520. error. Call updatewindow() to create and/or update the window state.
  8521. Note: a memory error from inflate() is non-recoverable.
  8522. */
  8523. //--- RESTORE() ---
  8524. strm.next_out = put;
  8525. strm.avail_out = left;
  8526. strm.next_in = next;
  8527. strm.avail_in = have;
  8528. state.hold = hold;
  8529. state.bits = bits;
  8530. //---
  8531. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  8532. (state.mode < CHECK || flush !== Z_FINISH))) {
  8533. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  8534. state.mode = MEM;
  8535. return Z_MEM_ERROR;
  8536. }
  8537. }
  8538. _in -= strm.avail_in;
  8539. _out -= strm.avail_out;
  8540. strm.total_in += _in;
  8541. strm.total_out += _out;
  8542. state.total += _out;
  8543. if (state.wrap && _out) {
  8544. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  8545. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  8546. }
  8547. strm.data_type = state.bits + (state.last ? 64 : 0) +
  8548. (state.mode === TYPE ? 128 : 0) +
  8549. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  8550. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  8551. ret = Z_BUF_ERROR;
  8552. }
  8553. return ret;
  8554. }
  8555. function inflateEnd(strm) {
  8556. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  8557. return Z_STREAM_ERROR;
  8558. }
  8559. var state = strm.state;
  8560. if (state.window) {
  8561. state.window = null;
  8562. }
  8563. strm.state = null;
  8564. return Z_OK;
  8565. }
  8566. function inflateGetHeader(strm, head) {
  8567. var state;
  8568. /* check state */
  8569. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8570. state = strm.state;
  8571. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  8572. /* save header structure */
  8573. state.head = head;
  8574. head.done = false;
  8575. return Z_OK;
  8576. }
  8577. function inflateSetDictionary(strm, dictionary) {
  8578. var dictLength = dictionary.length;
  8579. var state;
  8580. var dictid;
  8581. var ret;
  8582. /* check state */
  8583. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  8584. state = strm.state;
  8585. if (state.wrap !== 0 && state.mode !== DICT) {
  8586. return Z_STREAM_ERROR;
  8587. }
  8588. /* check for correct dictionary identifier */
  8589. if (state.mode === DICT) {
  8590. dictid = 1; /* adler32(0, null, 0)*/
  8591. /* dictid = adler32(dictid, dictionary, dictLength); */
  8592. dictid = adler32(dictid, dictionary, dictLength, 0);
  8593. if (dictid !== state.check) {
  8594. return Z_DATA_ERROR;
  8595. }
  8596. }
  8597. /* copy dictionary to window using updatewindow(), which will amend the
  8598. existing dictionary if appropriate */
  8599. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  8600. if (ret) {
  8601. state.mode = MEM;
  8602. return Z_MEM_ERROR;
  8603. }
  8604. state.havedict = 1;
  8605. // Tracev((stderr, "inflate: dictionary set\n"));
  8606. return Z_OK;
  8607. }
  8608. exports.inflateReset = inflateReset;
  8609. exports.inflateReset2 = inflateReset2;
  8610. exports.inflateResetKeep = inflateResetKeep;
  8611. exports.inflateInit = inflateInit;
  8612. exports.inflateInit2 = inflateInit2;
  8613. exports.inflate = inflate;
  8614. exports.inflateEnd = inflateEnd;
  8615. exports.inflateGetHeader = inflateGetHeader;
  8616. exports.inflateSetDictionary = inflateSetDictionary;
  8617. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  8618. /* Not implemented
  8619. exports.inflateCopy = inflateCopy;
  8620. exports.inflateGetDictionary = inflateGetDictionary;
  8621. exports.inflateMark = inflateMark;
  8622. exports.inflatePrime = inflatePrime;
  8623. exports.inflateSync = inflateSync;
  8624. exports.inflateSyncPoint = inflateSyncPoint;
  8625. exports.inflateUndermine = inflateUndermine;
  8626. */
  8627. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
  8628. 'use strict';
  8629. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8630. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8631. //
  8632. // This software is provided 'as-is', without any express or implied
  8633. // warranty. In no event will the authors be held liable for any damages
  8634. // arising from the use of this software.
  8635. //
  8636. // Permission is granted to anyone to use this software for any purpose,
  8637. // including commercial applications, and to alter it and redistribute it
  8638. // freely, subject to the following restrictions:
  8639. //
  8640. // 1. The origin of this software must not be misrepresented; you must not
  8641. // claim that you wrote the original software. If you use this software
  8642. // in a product, an acknowledgment in the product documentation would be
  8643. // appreciated but is not required.
  8644. // 2. Altered source versions must be plainly marked as such, and must not be
  8645. // misrepresented as being the original software.
  8646. // 3. This notice may not be removed or altered from any source distribution.
  8647. var utils = require('../utils/common');
  8648. var MAXBITS = 15;
  8649. var ENOUGH_LENS = 852;
  8650. var ENOUGH_DISTS = 592;
  8651. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8652. var CODES = 0;
  8653. var LENS = 1;
  8654. var DISTS = 2;
  8655. var lbase = [ /* Length codes 257..285 base */
  8656. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  8657. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  8658. ];
  8659. var lext = [ /* Length codes 257..285 extra */
  8660. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  8661. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  8662. ];
  8663. var dbase = [ /* Distance codes 0..29 base */
  8664. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  8665. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  8666. 8193, 12289, 16385, 24577, 0, 0
  8667. ];
  8668. var dext = [ /* Distance codes 0..29 extra */
  8669. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  8670. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  8671. 28, 28, 29, 29, 64, 64
  8672. ];
  8673. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  8674. {
  8675. var bits = opts.bits;
  8676. //here = opts.here; /* table entry for duplication */
  8677. var len = 0; /* a code's length in bits */
  8678. var sym = 0; /* index of code symbols */
  8679. var min = 0, max = 0; /* minimum and maximum code lengths */
  8680. var root = 0; /* number of index bits for root table */
  8681. var curr = 0; /* number of index bits for current table */
  8682. var drop = 0; /* code bits to drop for sub-table */
  8683. var left = 0; /* number of prefix codes available */
  8684. var used = 0; /* code entries in table used */
  8685. var huff = 0; /* Huffman code */
  8686. var incr; /* for incrementing code, index */
  8687. var fill; /* index for replicating entries */
  8688. var low; /* low bits for current root entry */
  8689. var mask; /* mask for low root bits */
  8690. var next; /* next available space in table */
  8691. var base = null; /* base value table to use */
  8692. var base_index = 0;
  8693. // var shoextra; /* extra bits table to use */
  8694. var end; /* use base and extra for symbol > end */
  8695. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  8696. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  8697. var extra = null;
  8698. var extra_index = 0;
  8699. var here_bits, here_op, here_val;
  8700. /*
  8701. Process a set of code lengths to create a canonical Huffman code. The
  8702. code lengths are lens[0..codes-1]. Each length corresponds to the
  8703. symbols 0..codes-1. The Huffman code is generated by first sorting the
  8704. symbols by length from short to long, and retaining the symbol order
  8705. for codes with equal lengths. Then the code starts with all zero bits
  8706. for the first code of the shortest length, and the codes are integer
  8707. increments for the same length, and zeros are appended as the length
  8708. increases. For the deflate format, these bits are stored backwards
  8709. from their more natural integer increment ordering, and so when the
  8710. decoding tables are built in the large loop below, the integer codes
  8711. are incremented backwards.
  8712. This routine assumes, but does not check, that all of the entries in
  8713. lens[] are in the range 0..MAXBITS. The caller must assure this.
  8714. 1..MAXBITS is interpreted as that code length. zero means that that
  8715. symbol does not occur in this code.
  8716. The codes are sorted by computing a count of codes for each length,
  8717. creating from that a table of starting indices for each length in the
  8718. sorted table, and then entering the symbols in order in the sorted
  8719. table. The sorted table is work[], with that space being provided by
  8720. the caller.
  8721. The length counts are used for other purposes as well, i.e. finding
  8722. the minimum and maximum length codes, determining if there are any
  8723. codes at all, checking for a valid set of lengths, and looking ahead
  8724. at length counts to determine sub-table sizes when building the
  8725. decoding tables.
  8726. */
  8727. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  8728. for (len = 0; len <= MAXBITS; len++) {
  8729. count[len] = 0;
  8730. }
  8731. for (sym = 0; sym < codes; sym++) {
  8732. count[lens[lens_index + sym]]++;
  8733. }
  8734. /* bound code lengths, force root to be within code lengths */
  8735. root = bits;
  8736. for (max = MAXBITS; max >= 1; max--) {
  8737. if (count[max] !== 0) { break; }
  8738. }
  8739. if (root > max) {
  8740. root = max;
  8741. }
  8742. if (max === 0) { /* no symbols to code at all */
  8743. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  8744. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  8745. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  8746. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  8747. //table.op[opts.table_index] = 64;
  8748. //table.bits[opts.table_index] = 1;
  8749. //table.val[opts.table_index++] = 0;
  8750. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  8751. opts.bits = 1;
  8752. return 0; /* no symbols, but wait for decoding to report error */
  8753. }
  8754. for (min = 1; min < max; min++) {
  8755. if (count[min] !== 0) { break; }
  8756. }
  8757. if (root < min) {
  8758. root = min;
  8759. }
  8760. /* check for an over-subscribed or incomplete set of lengths */
  8761. left = 1;
  8762. for (len = 1; len <= MAXBITS; len++) {
  8763. left <<= 1;
  8764. left -= count[len];
  8765. if (left < 0) {
  8766. return -1;
  8767. } /* over-subscribed */
  8768. }
  8769. if (left > 0 && (type === CODES || max !== 1)) {
  8770. return -1; /* incomplete set */
  8771. }
  8772. /* generate offsets into symbol table for each length for sorting */
  8773. offs[1] = 0;
  8774. for (len = 1; len < MAXBITS; len++) {
  8775. offs[len + 1] = offs[len] + count[len];
  8776. }
  8777. /* sort symbols by length, by symbol order within each length */
  8778. for (sym = 0; sym < codes; sym++) {
  8779. if (lens[lens_index + sym] !== 0) {
  8780. work[offs[lens[lens_index + sym]]++] = sym;
  8781. }
  8782. }
  8783. /*
  8784. Create and fill in decoding tables. In this loop, the table being
  8785. filled is at next and has curr index bits. The code being used is huff
  8786. with length len. That code is converted to an index by dropping drop
  8787. bits off of the bottom. For codes where len is less than drop + curr,
  8788. those top drop + curr - len bits are incremented through all values to
  8789. fill the table with replicated entries.
  8790. root is the number of index bits for the root table. When len exceeds
  8791. root, sub-tables are created pointed to by the root entry with an index
  8792. of the low root bits of huff. This is saved in low to check for when a
  8793. new sub-table should be started. drop is zero when the root table is
  8794. being filled, and drop is root when sub-tables are being filled.
  8795. When a new sub-table is needed, it is necessary to look ahead in the
  8796. code lengths to determine what size sub-table is needed. The length
  8797. counts are used for this, and so count[] is decremented as codes are
  8798. entered in the tables.
  8799. used keeps track of how many table entries have been allocated from the
  8800. provided *table space. It is checked for LENS and DIST tables against
  8801. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  8802. the initial root table size constants. See the comments in inftrees.h
  8803. for more information.
  8804. sym increments through all symbols, and the loop terminates when
  8805. all codes of length max, i.e. all codes, have been processed. This
  8806. routine permits incomplete codes, so another loop after this one fills
  8807. in the rest of the decoding tables with invalid code markers.
  8808. */
  8809. /* set up for code type */
  8810. // poor man optimization - use if-else instead of switch,
  8811. // to avoid deopts in old v8
  8812. if (type === CODES) {
  8813. base = extra = work; /* dummy value--not used */
  8814. end = 19;
  8815. } else if (type === LENS) {
  8816. base = lbase;
  8817. base_index -= 257;
  8818. extra = lext;
  8819. extra_index -= 257;
  8820. end = 256;
  8821. } else { /* DISTS */
  8822. base = dbase;
  8823. extra = dext;
  8824. end = -1;
  8825. }
  8826. /* initialize opts for loop */
  8827. huff = 0; /* starting code */
  8828. sym = 0; /* starting code symbol */
  8829. len = min; /* starting code length */
  8830. next = table_index; /* current table to fill in */
  8831. curr = root; /* current table index bits */
  8832. drop = 0; /* current bits to drop from code for index */
  8833. low = -1; /* trigger new sub-table when len > root */
  8834. used = 1 << root; /* use root table entries */
  8835. mask = used - 1; /* mask for comparing low */
  8836. /* check available table space */
  8837. if ((type === LENS && used > ENOUGH_LENS) ||
  8838. (type === DISTS && used > ENOUGH_DISTS)) {
  8839. return 1;
  8840. }
  8841. /* process all codes and make table entries */
  8842. for (;;) {
  8843. /* create table entry */
  8844. here_bits = len - drop;
  8845. if (work[sym] < end) {
  8846. here_op = 0;
  8847. here_val = work[sym];
  8848. }
  8849. else if (work[sym] > end) {
  8850. here_op = extra[extra_index + work[sym]];
  8851. here_val = base[base_index + work[sym]];
  8852. }
  8853. else {
  8854. here_op = 32 + 64; /* end of block */
  8855. here_val = 0;
  8856. }
  8857. /* replicate for those indices with low len bits equal to huff */
  8858. incr = 1 << (len - drop);
  8859. fill = 1 << curr;
  8860. min = fill; /* save offset to next table */
  8861. do {
  8862. fill -= incr;
  8863. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  8864. } while (fill !== 0);
  8865. /* backwards increment the len-bit code huff */
  8866. incr = 1 << (len - 1);
  8867. while (huff & incr) {
  8868. incr >>= 1;
  8869. }
  8870. if (incr !== 0) {
  8871. huff &= incr - 1;
  8872. huff += incr;
  8873. } else {
  8874. huff = 0;
  8875. }
  8876. /* go to next symbol, update count, len */
  8877. sym++;
  8878. if (--count[len] === 0) {
  8879. if (len === max) { break; }
  8880. len = lens[lens_index + work[sym]];
  8881. }
  8882. /* create new sub-table if needed */
  8883. if (len > root && (huff & mask) !== low) {
  8884. /* if first time, transition to sub-tables */
  8885. if (drop === 0) {
  8886. drop = root;
  8887. }
  8888. /* increment past last table */
  8889. next += min; /* here min is 1 << curr */
  8890. /* determine length of next table */
  8891. curr = len - drop;
  8892. left = 1 << curr;
  8893. while (curr + drop < max) {
  8894. left -= count[curr + drop];
  8895. if (left <= 0) { break; }
  8896. curr++;
  8897. left <<= 1;
  8898. }
  8899. /* check for enough space */
  8900. used += 1 << curr;
  8901. if ((type === LENS && used > ENOUGH_LENS) ||
  8902. (type === DISTS && used > ENOUGH_DISTS)) {
  8903. return 1;
  8904. }
  8905. /* point entry in root table to sub-table */
  8906. low = huff & mask;
  8907. /*table.op[low] = curr;
  8908. table.bits[low] = root;
  8909. table.val[low] = next - opts.table_index;*/
  8910. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  8911. }
  8912. }
  8913. /* fill in remaining table entry if code is incomplete (guaranteed to have
  8914. at most one remaining entry, since if the code is incomplete, the
  8915. maximum code length that was allowed to get this far is one bit) */
  8916. if (huff !== 0) {
  8917. //table.op[next + huff] = 64; /* invalid code marker */
  8918. //table.bits[next + huff] = len - drop;
  8919. //table.val[next + huff] = 0;
  8920. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  8921. }
  8922. /* set return parameters */
  8923. //opts.table_index += used;
  8924. opts.bits = root;
  8925. return 0;
  8926. };
  8927. },{"../utils/common":41}],51:[function(require,module,exports){
  8928. 'use strict';
  8929. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8930. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8931. //
  8932. // This software is provided 'as-is', without any express or implied
  8933. // warranty. In no event will the authors be held liable for any damages
  8934. // arising from the use of this software.
  8935. //
  8936. // Permission is granted to anyone to use this software for any purpose,
  8937. // including commercial applications, and to alter it and redistribute it
  8938. // freely, subject to the following restrictions:
  8939. //
  8940. // 1. The origin of this software must not be misrepresented; you must not
  8941. // claim that you wrote the original software. If you use this software
  8942. // in a product, an acknowledgment in the product documentation would be
  8943. // appreciated but is not required.
  8944. // 2. Altered source versions must be plainly marked as such, and must not be
  8945. // misrepresented as being the original software.
  8946. // 3. This notice may not be removed or altered from any source distribution.
  8947. module.exports = {
  8948. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  8949. 1: 'stream end', /* Z_STREAM_END 1 */
  8950. 0: '', /* Z_OK 0 */
  8951. '-1': 'file error', /* Z_ERRNO (-1) */
  8952. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  8953. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  8954. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  8955. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  8956. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  8957. };
  8958. },{}],52:[function(require,module,exports){
  8959. 'use strict';
  8960. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8961. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8962. //
  8963. // This software is provided 'as-is', without any express or implied
  8964. // warranty. In no event will the authors be held liable for any damages
  8965. // arising from the use of this software.
  8966. //
  8967. // Permission is granted to anyone to use this software for any purpose,
  8968. // including commercial applications, and to alter it and redistribute it
  8969. // freely, subject to the following restrictions:
  8970. //
  8971. // 1. The origin of this software must not be misrepresented; you must not
  8972. // claim that you wrote the original software. If you use this software
  8973. // in a product, an acknowledgment in the product documentation would be
  8974. // appreciated but is not required.
  8975. // 2. Altered source versions must be plainly marked as such, and must not be
  8976. // misrepresented as being the original software.
  8977. // 3. This notice may not be removed or altered from any source distribution.
  8978. var utils = require('../utils/common');
  8979. /* Public constants ==========================================================*/
  8980. /* ===========================================================================*/
  8981. //var Z_FILTERED = 1;
  8982. //var Z_HUFFMAN_ONLY = 2;
  8983. //var Z_RLE = 3;
  8984. var Z_FIXED = 4;
  8985. //var Z_DEFAULT_STRATEGY = 0;
  8986. /* Possible values of the data_type field (though see inflate()) */
  8987. var Z_BINARY = 0;
  8988. var Z_TEXT = 1;
  8989. //var Z_ASCII = 1; // = Z_TEXT
  8990. var Z_UNKNOWN = 2;
  8991. /*============================================================================*/
  8992. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  8993. // From zutil.h
  8994. var STORED_BLOCK = 0;
  8995. var STATIC_TREES = 1;
  8996. var DYN_TREES = 2;
  8997. /* The three kinds of block type */
  8998. var MIN_MATCH = 3;
  8999. var MAX_MATCH = 258;
  9000. /* The minimum and maximum match lengths */
  9001. // From deflate.h
  9002. /* ===========================================================================
  9003. * Internal compression state.
  9004. */
  9005. var LENGTH_CODES = 29;
  9006. /* number of length codes, not counting the special END_BLOCK code */
  9007. var LITERALS = 256;
  9008. /* number of literal bytes 0..255 */
  9009. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9010. /* number of Literal or Length codes, including the END_BLOCK code */
  9011. var D_CODES = 30;
  9012. /* number of distance codes */
  9013. var BL_CODES = 19;
  9014. /* number of codes used to transfer the bit lengths */
  9015. var HEAP_SIZE = 2 * L_CODES + 1;
  9016. /* maximum heap size */
  9017. var MAX_BITS = 15;
  9018. /* All codes must not exceed MAX_BITS bits */
  9019. var Buf_size = 16;
  9020. /* size of bit buffer in bi_buf */
  9021. /* ===========================================================================
  9022. * Constants
  9023. */
  9024. var MAX_BL_BITS = 7;
  9025. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9026. var END_BLOCK = 256;
  9027. /* end of block literal code */
  9028. var REP_3_6 = 16;
  9029. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9030. var REPZ_3_10 = 17;
  9031. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9032. var REPZ_11_138 = 18;
  9033. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9034. /* eslint-disable comma-spacing,array-bracket-spacing */
  9035. var extra_lbits = /* extra bits for each length code */
  9036. [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];
  9037. var extra_dbits = /* extra bits for each distance code */
  9038. [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];
  9039. var extra_blbits = /* extra bits for each bit length code */
  9040. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9041. var bl_order =
  9042. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9043. /* eslint-enable comma-spacing,array-bracket-spacing */
  9044. /* The lengths of the bit length codes are sent in order of decreasing
  9045. * probability, to avoid transmitting the lengths for unused bit length codes.
  9046. */
  9047. /* ===========================================================================
  9048. * Local data. These are initialized only once.
  9049. */
  9050. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9051. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9052. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  9053. var static_ltree = new Array((L_CODES + 2) * 2);
  9054. zero(static_ltree);
  9055. /* The static literal tree. Since the bit lengths are imposed, there is no
  9056. * need for the L_CODES extra codes used during heap construction. However
  9057. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9058. * below).
  9059. */
  9060. var static_dtree = new Array(D_CODES * 2);
  9061. zero(static_dtree);
  9062. /* The static distance tree. (Actually a trivial tree since all codes use
  9063. * 5 bits.)
  9064. */
  9065. var _dist_code = new Array(DIST_CODE_LEN);
  9066. zero(_dist_code);
  9067. /* Distance codes. The first 256 values correspond to the distances
  9068. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9069. * the 15 bit distances.
  9070. */
  9071. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  9072. zero(_length_code);
  9073. /* length code for each normalized match length (0 == MIN_MATCH) */
  9074. var base_length = new Array(LENGTH_CODES);
  9075. zero(base_length);
  9076. /* First normalized length for each code (0 = MIN_MATCH) */
  9077. var base_dist = new Array(D_CODES);
  9078. zero(base_dist);
  9079. /* First normalized distance for each code (0 = distance of 1) */
  9080. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  9081. this.static_tree = static_tree; /* static tree or NULL */
  9082. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  9083. this.extra_base = extra_base; /* base index for extra_bits */
  9084. this.elems = elems; /* max number of elements in the tree */
  9085. this.max_length = max_length; /* max bit length for the codes */
  9086. // show if `static_tree` has data or dummy - needed for monomorphic objects
  9087. this.has_stree = static_tree && static_tree.length;
  9088. }
  9089. var static_l_desc;
  9090. var static_d_desc;
  9091. var static_bl_desc;
  9092. function TreeDesc(dyn_tree, stat_desc) {
  9093. this.dyn_tree = dyn_tree; /* the dynamic tree */
  9094. this.max_code = 0; /* largest code with non zero frequency */
  9095. this.stat_desc = stat_desc; /* the corresponding static tree */
  9096. }
  9097. function d_code(dist) {
  9098. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  9099. }
  9100. /* ===========================================================================
  9101. * Output a short LSB first on the stream.
  9102. * IN assertion: there is enough room in pendingBuf.
  9103. */
  9104. function put_short(s, w) {
  9105. // put_byte(s, (uch)((w) & 0xff));
  9106. // put_byte(s, (uch)((ush)(w) >> 8));
  9107. s.pending_buf[s.pending++] = (w) & 0xff;
  9108. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  9109. }
  9110. /* ===========================================================================
  9111. * Send a value on a given number of bits.
  9112. * IN assertion: length <= 16 and value fits in length bits.
  9113. */
  9114. function send_bits(s, value, length) {
  9115. if (s.bi_valid > (Buf_size - length)) {
  9116. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9117. put_short(s, s.bi_buf);
  9118. s.bi_buf = value >> (Buf_size - s.bi_valid);
  9119. s.bi_valid += length - Buf_size;
  9120. } else {
  9121. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9122. s.bi_valid += length;
  9123. }
  9124. }
  9125. function send_code(s, c, tree) {
  9126. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  9127. }
  9128. /* ===========================================================================
  9129. * Reverse the first len bits of a code, using straightforward code (a faster
  9130. * method would use a table)
  9131. * IN assertion: 1 <= len <= 15
  9132. */
  9133. function bi_reverse(code, len) {
  9134. var res = 0;
  9135. do {
  9136. res |= code & 1;
  9137. code >>>= 1;
  9138. res <<= 1;
  9139. } while (--len > 0);
  9140. return res >>> 1;
  9141. }
  9142. /* ===========================================================================
  9143. * Flush the bit buffer, keeping at most 7 bits in it.
  9144. */
  9145. function bi_flush(s) {
  9146. if (s.bi_valid === 16) {
  9147. put_short(s, s.bi_buf);
  9148. s.bi_buf = 0;
  9149. s.bi_valid = 0;
  9150. } else if (s.bi_valid >= 8) {
  9151. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  9152. s.bi_buf >>= 8;
  9153. s.bi_valid -= 8;
  9154. }
  9155. }
  9156. /* ===========================================================================
  9157. * Compute the optimal bit lengths for a tree and update the total bit length
  9158. * for the current block.
  9159. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  9160. * above are the tree nodes sorted by increasing frequency.
  9161. * OUT assertions: the field len is set to the optimal bit length, the
  9162. * array bl_count contains the frequencies for each bit length.
  9163. * The length opt_len is updated; static_len is also updated if stree is
  9164. * not null.
  9165. */
  9166. function gen_bitlen(s, desc)
  9167. // deflate_state *s;
  9168. // tree_desc *desc; /* the tree descriptor */
  9169. {
  9170. var tree = desc.dyn_tree;
  9171. var max_code = desc.max_code;
  9172. var stree = desc.stat_desc.static_tree;
  9173. var has_stree = desc.stat_desc.has_stree;
  9174. var extra = desc.stat_desc.extra_bits;
  9175. var base = desc.stat_desc.extra_base;
  9176. var max_length = desc.stat_desc.max_length;
  9177. var h; /* heap index */
  9178. var n, m; /* iterate over the tree elements */
  9179. var bits; /* bit length */
  9180. var xbits; /* extra bits */
  9181. var f; /* frequency */
  9182. var overflow = 0; /* number of elements with bit length too large */
  9183. for (bits = 0; bits <= MAX_BITS; bits++) {
  9184. s.bl_count[bits] = 0;
  9185. }
  9186. /* In a first pass, compute the optimal bit lengths (which may
  9187. * overflow in the case of the bit length tree).
  9188. */
  9189. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  9190. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9191. n = s.heap[h];
  9192. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  9193. if (bits > max_length) {
  9194. bits = max_length;
  9195. overflow++;
  9196. }
  9197. tree[n * 2 + 1]/*.Len*/ = bits;
  9198. /* We overwrite tree[n].Dad which is no longer needed */
  9199. if (n > max_code) { continue; } /* not a leaf node */
  9200. s.bl_count[bits]++;
  9201. xbits = 0;
  9202. if (n >= base) {
  9203. xbits = extra[n - base];
  9204. }
  9205. f = tree[n * 2]/*.Freq*/;
  9206. s.opt_len += f * (bits + xbits);
  9207. if (has_stree) {
  9208. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  9209. }
  9210. }
  9211. if (overflow === 0) { return; }
  9212. // Trace((stderr,"\nbit length overflow\n"));
  9213. /* This happens for example on obj2 and pic of the Calgary corpus */
  9214. /* Find the first bit length which could increase: */
  9215. do {
  9216. bits = max_length - 1;
  9217. while (s.bl_count[bits] === 0) { bits--; }
  9218. s.bl_count[bits]--; /* move one leaf down the tree */
  9219. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  9220. s.bl_count[max_length]--;
  9221. /* The brother of the overflow item also moves one step up,
  9222. * but this does not affect bl_count[max_length]
  9223. */
  9224. overflow -= 2;
  9225. } while (overflow > 0);
  9226. /* Now recompute all bit lengths, scanning in increasing frequency.
  9227. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  9228. * lengths instead of fixing only the wrong ones. This idea is taken
  9229. * from 'ar' written by Haruhiko Okumura.)
  9230. */
  9231. for (bits = max_length; bits !== 0; bits--) {
  9232. n = s.bl_count[bits];
  9233. while (n !== 0) {
  9234. m = s.heap[--h];
  9235. if (m > max_code) { continue; }
  9236. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  9237. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  9238. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  9239. tree[m * 2 + 1]/*.Len*/ = bits;
  9240. }
  9241. n--;
  9242. }
  9243. }
  9244. }
  9245. /* ===========================================================================
  9246. * Generate the codes for a given tree and bit counts (which need not be
  9247. * optimal).
  9248. * IN assertion: the array bl_count contains the bit length statistics for
  9249. * the given tree and the field len is set for all tree elements.
  9250. * OUT assertion: the field code is set for all tree elements of non
  9251. * zero code length.
  9252. */
  9253. function gen_codes(tree, max_code, bl_count)
  9254. // ct_data *tree; /* the tree to decorate */
  9255. // int max_code; /* largest code with non zero frequency */
  9256. // ushf *bl_count; /* number of codes at each bit length */
  9257. {
  9258. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  9259. var code = 0; /* running code value */
  9260. var bits; /* bit index */
  9261. var n; /* code index */
  9262. /* The distribution counts are first used to generate the code values
  9263. * without bit reversal.
  9264. */
  9265. for (bits = 1; bits <= MAX_BITS; bits++) {
  9266. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  9267. }
  9268. /* Check that the bit counts in bl_count are consistent. The last code
  9269. * must be all ones.
  9270. */
  9271. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9272. // "inconsistent bit counts");
  9273. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9274. for (n = 0; n <= max_code; n++) {
  9275. var len = tree[n * 2 + 1]/*.Len*/;
  9276. if (len === 0) { continue; }
  9277. /* Now reverse the bits */
  9278. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  9279. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  9280. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  9281. }
  9282. }
  9283. /* ===========================================================================
  9284. * Initialize the various 'constant' tables.
  9285. */
  9286. function tr_static_init() {
  9287. var n; /* iterates over tree elements */
  9288. var bits; /* bit counter */
  9289. var length; /* length value */
  9290. var code; /* code value */
  9291. var dist; /* distance index */
  9292. var bl_count = new Array(MAX_BITS + 1);
  9293. /* number of codes at each bit length for an optimal tree */
  9294. // do check in _tr_init()
  9295. //if (static_init_done) return;
  9296. /* For some embedded targets, global variables are not initialized: */
  9297. /*#ifdef NO_INIT_GLOBAL_POINTERS
  9298. static_l_desc.static_tree = static_ltree;
  9299. static_l_desc.extra_bits = extra_lbits;
  9300. static_d_desc.static_tree = static_dtree;
  9301. static_d_desc.extra_bits = extra_dbits;
  9302. static_bl_desc.extra_bits = extra_blbits;
  9303. #endif*/
  9304. /* Initialize the mapping length (0..255) -> length code (0..28) */
  9305. length = 0;
  9306. for (code = 0; code < LENGTH_CODES - 1; code++) {
  9307. base_length[code] = length;
  9308. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  9309. _length_code[length++] = code;
  9310. }
  9311. }
  9312. //Assert (length == 256, "tr_static_init: length != 256");
  9313. /* Note that the length 255 (match length 258) can be represented
  9314. * in two different ways: code 284 + 5 bits or code 285, so we
  9315. * overwrite length_code[255] to use the best encoding:
  9316. */
  9317. _length_code[length - 1] = code;
  9318. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  9319. dist = 0;
  9320. for (code = 0; code < 16; code++) {
  9321. base_dist[code] = dist;
  9322. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  9323. _dist_code[dist++] = code;
  9324. }
  9325. }
  9326. //Assert (dist == 256, "tr_static_init: dist != 256");
  9327. dist >>= 7; /* from now on, all distances are divided by 128 */
  9328. for (; code < D_CODES; code++) {
  9329. base_dist[code] = dist << 7;
  9330. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  9331. _dist_code[256 + dist++] = code;
  9332. }
  9333. }
  9334. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  9335. /* Construct the codes of the static literal tree */
  9336. for (bits = 0; bits <= MAX_BITS; bits++) {
  9337. bl_count[bits] = 0;
  9338. }
  9339. n = 0;
  9340. while (n <= 143) {
  9341. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9342. n++;
  9343. bl_count[8]++;
  9344. }
  9345. while (n <= 255) {
  9346. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  9347. n++;
  9348. bl_count[9]++;
  9349. }
  9350. while (n <= 279) {
  9351. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  9352. n++;
  9353. bl_count[7]++;
  9354. }
  9355. while (n <= 287) {
  9356. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9357. n++;
  9358. bl_count[8]++;
  9359. }
  9360. /* Codes 286 and 287 do not exist, but we must include them in the
  9361. * tree construction to get a canonical Huffman tree (longest code
  9362. * all ones)
  9363. */
  9364. gen_codes(static_ltree, L_CODES + 1, bl_count);
  9365. /* The static distance tree is trivial: */
  9366. for (n = 0; n < D_CODES; n++) {
  9367. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  9368. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  9369. }
  9370. // Now data ready and we can init static trees
  9371. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9372. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  9373. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9374. //static_init_done = true;
  9375. }
  9376. /* ===========================================================================
  9377. * Initialize a new block.
  9378. */
  9379. function init_block(s) {
  9380. var n; /* iterates over tree elements */
  9381. /* Initialize the trees. */
  9382. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  9383. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  9384. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  9385. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  9386. s.opt_len = s.static_len = 0;
  9387. s.last_lit = s.matches = 0;
  9388. }
  9389. /* ===========================================================================
  9390. * Flush the bit buffer and align the output on a byte boundary
  9391. */
  9392. function bi_windup(s)
  9393. {
  9394. if (s.bi_valid > 8) {
  9395. put_short(s, s.bi_buf);
  9396. } else if (s.bi_valid > 0) {
  9397. //put_byte(s, (Byte)s->bi_buf);
  9398. s.pending_buf[s.pending++] = s.bi_buf;
  9399. }
  9400. s.bi_buf = 0;
  9401. s.bi_valid = 0;
  9402. }
  9403. /* ===========================================================================
  9404. * Copy a stored block, storing first the length and its
  9405. * one's complement if requested.
  9406. */
  9407. function copy_block(s, buf, len, header)
  9408. //DeflateState *s;
  9409. //charf *buf; /* the input data */
  9410. //unsigned len; /* its length */
  9411. //int header; /* true if block header must be written */
  9412. {
  9413. bi_windup(s); /* align on byte boundary */
  9414. if (header) {
  9415. put_short(s, len);
  9416. put_short(s, ~len);
  9417. }
  9418. // while (len--) {
  9419. // put_byte(s, *buf++);
  9420. // }
  9421. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  9422. s.pending += len;
  9423. }
  9424. /* ===========================================================================
  9425. * Compares to subtrees, using the tree depth as tie breaker when
  9426. * the subtrees have equal frequency. This minimizes the worst case length.
  9427. */
  9428. function smaller(tree, n, m, depth) {
  9429. var _n2 = n * 2;
  9430. var _m2 = m * 2;
  9431. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  9432. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  9433. }
  9434. /* ===========================================================================
  9435. * Restore the heap property by moving down the tree starting at node k,
  9436. * exchanging a node with the smallest of its two sons if necessary, stopping
  9437. * when the heap property is re-established (each father smaller than its
  9438. * two sons).
  9439. */
  9440. function pqdownheap(s, tree, k)
  9441. // deflate_state *s;
  9442. // ct_data *tree; /* the tree to restore */
  9443. // int k; /* node to move down */
  9444. {
  9445. var v = s.heap[k];
  9446. var j = k << 1; /* left son of k */
  9447. while (j <= s.heap_len) {
  9448. /* Set j to the smallest of the two sons: */
  9449. if (j < s.heap_len &&
  9450. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  9451. j++;
  9452. }
  9453. /* Exit if v is smaller than both sons */
  9454. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  9455. /* Exchange v with the smallest son */
  9456. s.heap[k] = s.heap[j];
  9457. k = j;
  9458. /* And continue down the tree, setting j to the left son of k */
  9459. j <<= 1;
  9460. }
  9461. s.heap[k] = v;
  9462. }
  9463. // inlined manually
  9464. // var SMALLEST = 1;
  9465. /* ===========================================================================
  9466. * Send the block data compressed using the given Huffman trees
  9467. */
  9468. function compress_block(s, ltree, dtree)
  9469. // deflate_state *s;
  9470. // const ct_data *ltree; /* literal tree */
  9471. // const ct_data *dtree; /* distance tree */
  9472. {
  9473. var dist; /* distance of matched string */
  9474. var lc; /* match length or unmatched char (if dist == 0) */
  9475. var lx = 0; /* running index in l_buf */
  9476. var code; /* the code to send */
  9477. var extra; /* number of extra bits to send */
  9478. if (s.last_lit !== 0) {
  9479. do {
  9480. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  9481. lc = s.pending_buf[s.l_buf + lx];
  9482. lx++;
  9483. if (dist === 0) {
  9484. send_code(s, lc, ltree); /* send a literal byte */
  9485. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  9486. } else {
  9487. /* Here, lc is the match length - MIN_MATCH */
  9488. code = _length_code[lc];
  9489. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  9490. extra = extra_lbits[code];
  9491. if (extra !== 0) {
  9492. lc -= base_length[code];
  9493. send_bits(s, lc, extra); /* send the extra length bits */
  9494. }
  9495. dist--; /* dist is now the match distance - 1 */
  9496. code = d_code(dist);
  9497. //Assert (code < D_CODES, "bad d_code");
  9498. send_code(s, code, dtree); /* send the distance code */
  9499. extra = extra_dbits[code];
  9500. if (extra !== 0) {
  9501. dist -= base_dist[code];
  9502. send_bits(s, dist, extra); /* send the extra distance bits */
  9503. }
  9504. } /* literal or match pair ? */
  9505. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  9506. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  9507. // "pendingBuf overflow");
  9508. } while (lx < s.last_lit);
  9509. }
  9510. send_code(s, END_BLOCK, ltree);
  9511. }
  9512. /* ===========================================================================
  9513. * Construct one Huffman tree and assigns the code bit strings and lengths.
  9514. * Update the total bit length for the current block.
  9515. * IN assertion: the field freq is set for all tree elements.
  9516. * OUT assertions: the fields len and code are set to the optimal bit length
  9517. * and corresponding code. The length opt_len is updated; static_len is
  9518. * also updated if stree is not null. The field max_code is set.
  9519. */
  9520. function build_tree(s, desc)
  9521. // deflate_state *s;
  9522. // tree_desc *desc; /* the tree descriptor */
  9523. {
  9524. var tree = desc.dyn_tree;
  9525. var stree = desc.stat_desc.static_tree;
  9526. var has_stree = desc.stat_desc.has_stree;
  9527. var elems = desc.stat_desc.elems;
  9528. var n, m; /* iterate over heap elements */
  9529. var max_code = -1; /* largest code with non zero frequency */
  9530. var node; /* new node being created */
  9531. /* Construct the initial heap, with least frequent element in
  9532. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9533. * heap[0] is not used.
  9534. */
  9535. s.heap_len = 0;
  9536. s.heap_max = HEAP_SIZE;
  9537. for (n = 0; n < elems; n++) {
  9538. if (tree[n * 2]/*.Freq*/ !== 0) {
  9539. s.heap[++s.heap_len] = max_code = n;
  9540. s.depth[n] = 0;
  9541. } else {
  9542. tree[n * 2 + 1]/*.Len*/ = 0;
  9543. }
  9544. }
  9545. /* The pkzip format requires that at least one distance code exists,
  9546. * and that at least one bit should be sent even if there is only one
  9547. * possible code. So to avoid special checks later on we force at least
  9548. * two codes of non zero frequency.
  9549. */
  9550. while (s.heap_len < 2) {
  9551. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  9552. tree[node * 2]/*.Freq*/ = 1;
  9553. s.depth[node] = 0;
  9554. s.opt_len--;
  9555. if (has_stree) {
  9556. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  9557. }
  9558. /* node is 0 or 1 so it does not have extra bits */
  9559. }
  9560. desc.max_code = max_code;
  9561. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9562. * establish sub-heaps of increasing lengths:
  9563. */
  9564. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  9565. /* Construct the Huffman tree by repeatedly combining the least two
  9566. * frequent nodes.
  9567. */
  9568. node = elems; /* next internal node of the tree */
  9569. do {
  9570. //pqremove(s, tree, n); /* n = node of least frequency */
  9571. /*** pqremove ***/
  9572. n = s.heap[1/*SMALLEST*/];
  9573. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  9574. pqdownheap(s, tree, 1/*SMALLEST*/);
  9575. /***/
  9576. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  9577. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  9578. s.heap[--s.heap_max] = m;
  9579. /* Create a new node father of n and m */
  9580. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  9581. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  9582. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  9583. /* and insert the new node in the heap */
  9584. s.heap[1/*SMALLEST*/] = node++;
  9585. pqdownheap(s, tree, 1/*SMALLEST*/);
  9586. } while (s.heap_len >= 2);
  9587. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  9588. /* At this point, the fields freq and dad are set. We can now
  9589. * generate the bit lengths.
  9590. */
  9591. gen_bitlen(s, desc);
  9592. /* The field len is now set, we can generate the bit codes */
  9593. gen_codes(tree, max_code, s.bl_count);
  9594. }
  9595. /* ===========================================================================
  9596. * Scan a literal or distance tree to determine the frequencies of the codes
  9597. * in the bit length tree.
  9598. */
  9599. function scan_tree(s, tree, max_code)
  9600. // deflate_state *s;
  9601. // ct_data *tree; /* the tree to be scanned */
  9602. // int max_code; /* and its largest code of non zero frequency */
  9603. {
  9604. var n; /* iterates over all tree elements */
  9605. var prevlen = -1; /* last emitted length */
  9606. var curlen; /* length of current code */
  9607. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  9608. var count = 0; /* repeat count of the current code */
  9609. var max_count = 7; /* max repeat count */
  9610. var min_count = 4; /* min repeat count */
  9611. if (nextlen === 0) {
  9612. max_count = 138;
  9613. min_count = 3;
  9614. }
  9615. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  9616. for (n = 0; n <= max_code; n++) {
  9617. curlen = nextlen;
  9618. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  9619. if (++count < max_count && curlen === nextlen) {
  9620. continue;
  9621. } else if (count < min_count) {
  9622. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  9623. } else if (curlen !== 0) {
  9624. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  9625. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  9626. } else if (count <= 10) {
  9627. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  9628. } else {
  9629. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  9630. }
  9631. count = 0;
  9632. prevlen = curlen;
  9633. if (nextlen === 0) {
  9634. max_count = 138;
  9635. min_count = 3;
  9636. } else if (curlen === nextlen) {
  9637. max_count = 6;
  9638. min_count = 3;
  9639. } else {
  9640. max_count = 7;
  9641. min_count = 4;
  9642. }
  9643. }
  9644. }
  9645. /* ===========================================================================
  9646. * Send a literal or distance tree in compressed form, using the codes in
  9647. * bl_tree.
  9648. */
  9649. function send_tree(s, tree, max_code)
  9650. // deflate_state *s;
  9651. // ct_data *tree; /* the tree to be scanned */
  9652. // int max_code; /* and its largest code of non zero frequency */
  9653. {
  9654. var n; /* iterates over all tree elements */
  9655. var prevlen = -1; /* last emitted length */
  9656. var curlen; /* length of current code */
  9657. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  9658. var count = 0; /* repeat count of the current code */
  9659. var max_count = 7; /* max repeat count */
  9660. var min_count = 4; /* min repeat count */
  9661. /* tree[max_code+1].Len = -1; */ /* guard already set */
  9662. if (nextlen === 0) {
  9663. max_count = 138;
  9664. min_count = 3;
  9665. }
  9666. for (n = 0; n <= max_code; n++) {
  9667. curlen = nextlen;
  9668. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  9669. if (++count < max_count && curlen === nextlen) {
  9670. continue;
  9671. } else if (count < min_count) {
  9672. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  9673. } else if (curlen !== 0) {
  9674. if (curlen !== prevlen) {
  9675. send_code(s, curlen, s.bl_tree);
  9676. count--;
  9677. }
  9678. //Assert(count >= 3 && count <= 6, " 3_6?");
  9679. send_code(s, REP_3_6, s.bl_tree);
  9680. send_bits(s, count - 3, 2);
  9681. } else if (count <= 10) {
  9682. send_code(s, REPZ_3_10, s.bl_tree);
  9683. send_bits(s, count - 3, 3);
  9684. } else {
  9685. send_code(s, REPZ_11_138, s.bl_tree);
  9686. send_bits(s, count - 11, 7);
  9687. }
  9688. count = 0;
  9689. prevlen = curlen;
  9690. if (nextlen === 0) {
  9691. max_count = 138;
  9692. min_count = 3;
  9693. } else if (curlen === nextlen) {
  9694. max_count = 6;
  9695. min_count = 3;
  9696. } else {
  9697. max_count = 7;
  9698. min_count = 4;
  9699. }
  9700. }
  9701. }
  9702. /* ===========================================================================
  9703. * Construct the Huffman tree for the bit lengths and return the index in
  9704. * bl_order of the last bit length code to send.
  9705. */
  9706. function build_bl_tree(s) {
  9707. var max_blindex; /* index of last bit length code of non zero freq */
  9708. /* Determine the bit length frequencies for literal and distance trees */
  9709. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  9710. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  9711. /* Build the bit length tree: */
  9712. build_tree(s, s.bl_desc);
  9713. /* opt_len now includes the length of the tree representations, except
  9714. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  9715. */
  9716. /* Determine the number of bit length codes to send. The pkzip format
  9717. * requires that at least 4 bit length codes be sent. (appnote.txt says
  9718. * 3 but the actual value used is 4.)
  9719. */
  9720. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  9721. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  9722. break;
  9723. }
  9724. }
  9725. /* Update opt_len to include the bit length tree and counts */
  9726. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  9727. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  9728. // s->opt_len, s->static_len));
  9729. return max_blindex;
  9730. }
  9731. /* ===========================================================================
  9732. * Send the header for a block using dynamic Huffman trees: the counts, the
  9733. * lengths of the bit length codes, the literal tree and the distance tree.
  9734. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  9735. */
  9736. function send_all_trees(s, lcodes, dcodes, blcodes)
  9737. // deflate_state *s;
  9738. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  9739. {
  9740. var rank; /* index in bl_order */
  9741. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  9742. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  9743. // "too many codes");
  9744. //Tracev((stderr, "\nbl counts: "));
  9745. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  9746. send_bits(s, dcodes - 1, 5);
  9747. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  9748. for (rank = 0; rank < blcodes; rank++) {
  9749. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  9750. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  9751. }
  9752. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  9753. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  9754. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  9755. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  9756. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  9757. }
  9758. /* ===========================================================================
  9759. * Check if the data type is TEXT or BINARY, using the following algorithm:
  9760. * - TEXT if the two conditions below are satisfied:
  9761. * a) There are no non-portable control characters belonging to the
  9762. * "black list" (0..6, 14..25, 28..31).
  9763. * b) There is at least one printable character belonging to the
  9764. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  9765. * - BINARY otherwise.
  9766. * - The following partially-portable control characters form a
  9767. * "gray list" that is ignored in this detection algorithm:
  9768. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  9769. * IN assertion: the fields Freq of dyn_ltree are set.
  9770. */
  9771. function detect_data_type(s) {
  9772. /* black_mask is the bit mask of black-listed bytes
  9773. * set bits 0..6, 14..25, and 28..31
  9774. * 0xf3ffc07f = binary 11110011111111111100000001111111
  9775. */
  9776. var black_mask = 0xf3ffc07f;
  9777. var n;
  9778. /* Check for non-textual ("black-listed") bytes. */
  9779. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  9780. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  9781. return Z_BINARY;
  9782. }
  9783. }
  9784. /* Check for textual ("white-listed") bytes. */
  9785. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  9786. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  9787. return Z_TEXT;
  9788. }
  9789. for (n = 32; n < LITERALS; n++) {
  9790. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  9791. return Z_TEXT;
  9792. }
  9793. }
  9794. /* There are no "black-listed" or "white-listed" bytes:
  9795. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  9796. */
  9797. return Z_BINARY;
  9798. }
  9799. var static_init_done = false;
  9800. /* ===========================================================================
  9801. * Initialize the tree data structures for a new zlib stream.
  9802. */
  9803. function _tr_init(s)
  9804. {
  9805. if (!static_init_done) {
  9806. tr_static_init();
  9807. static_init_done = true;
  9808. }
  9809. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  9810. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  9811. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  9812. s.bi_buf = 0;
  9813. s.bi_valid = 0;
  9814. /* Initialize the first block of the first file: */
  9815. init_block(s);
  9816. }
  9817. /* ===========================================================================
  9818. * Send a stored block
  9819. */
  9820. function _tr_stored_block(s, buf, stored_len, last)
  9821. //DeflateState *s;
  9822. //charf *buf; /* input block */
  9823. //ulg stored_len; /* length of input block */
  9824. //int last; /* one if this is the last block for a file */
  9825. {
  9826. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  9827. copy_block(s, buf, stored_len, true); /* with header */
  9828. }
  9829. /* ===========================================================================
  9830. * Send one empty static block to give enough lookahead for inflate.
  9831. * This takes 10 bits, of which 7 may remain in the bit buffer.
  9832. */
  9833. function _tr_align(s) {
  9834. send_bits(s, STATIC_TREES << 1, 3);
  9835. send_code(s, END_BLOCK, static_ltree);
  9836. bi_flush(s);
  9837. }
  9838. /* ===========================================================================
  9839. * Determine the best encoding for the current block: dynamic trees, static
  9840. * trees or store, and output the encoded block to the zip file.
  9841. */
  9842. function _tr_flush_block(s, buf, stored_len, last)
  9843. //DeflateState *s;
  9844. //charf *buf; /* input block, or NULL if too old */
  9845. //ulg stored_len; /* length of input block */
  9846. //int last; /* one if this is the last block for a file */
  9847. {
  9848. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  9849. var max_blindex = 0; /* index of last bit length code of non zero freq */
  9850. /* Build the Huffman trees unless a stored block is forced */
  9851. if (s.level > 0) {
  9852. /* Check if the file is binary or text */
  9853. if (s.strm.data_type === Z_UNKNOWN) {
  9854. s.strm.data_type = detect_data_type(s);
  9855. }
  9856. /* Construct the literal and distance trees */
  9857. build_tree(s, s.l_desc);
  9858. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  9859. // s->static_len));
  9860. build_tree(s, s.d_desc);
  9861. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  9862. // s->static_len));
  9863. /* At this point, opt_len and static_len are the total bit lengths of
  9864. * the compressed block data, excluding the tree representations.
  9865. */
  9866. /* Build the bit length tree for the above two trees, and get the index
  9867. * in bl_order of the last bit length code to send.
  9868. */
  9869. max_blindex = build_bl_tree(s);
  9870. /* Determine the best encoding. Compute the block lengths in bytes. */
  9871. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  9872. static_lenb = (s.static_len + 3 + 7) >>> 3;
  9873. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  9874. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  9875. // s->last_lit));
  9876. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  9877. } else {
  9878. // Assert(buf != (char*)0, "lost buf");
  9879. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  9880. }
  9881. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  9882. /* 4: two words for the lengths */
  9883. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  9884. * Otherwise we can't have processed more than WSIZE input bytes since
  9885. * the last block flush, because compression would have been
  9886. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  9887. * transform a block into a stored block.
  9888. */
  9889. _tr_stored_block(s, buf, stored_len, last);
  9890. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  9891. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  9892. compress_block(s, static_ltree, static_dtree);
  9893. } else {
  9894. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  9895. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  9896. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  9897. }
  9898. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  9899. /* The above check is made mod 2^32, for files larger than 512 MB
  9900. * and uLong implemented on 32 bits.
  9901. */
  9902. init_block(s);
  9903. if (last) {
  9904. bi_windup(s);
  9905. }
  9906. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  9907. // s->compressed_len-7*last));
  9908. }
  9909. /* ===========================================================================
  9910. * Save the match info and tally the frequency counts. Return true if
  9911. * the current block must be flushed.
  9912. */
  9913. function _tr_tally(s, dist, lc)
  9914. // deflate_state *s;
  9915. // unsigned dist; /* distance of matched string */
  9916. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  9917. {
  9918. //var out_length, in_length, dcode;
  9919. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  9920. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  9921. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  9922. s.last_lit++;
  9923. if (dist === 0) {
  9924. /* lc is the unmatched char */
  9925. s.dyn_ltree[lc * 2]/*.Freq*/++;
  9926. } else {
  9927. s.matches++;
  9928. /* Here, lc is the match length - MIN_MATCH */
  9929. dist--; /* dist = match distance - 1 */
  9930. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  9931. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  9932. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  9933. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  9934. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  9935. }
  9936. // (!) This block is disabled in zlib defailts,
  9937. // don't enable it for binary compatibility
  9938. //#ifdef TRUNCATE_BLOCK
  9939. // /* Try to guess if it is profitable to stop the current block here */
  9940. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  9941. // /* Compute an upper bound for the compressed length */
  9942. // out_length = s.last_lit*8;
  9943. // in_length = s.strstart - s.block_start;
  9944. //
  9945. // for (dcode = 0; dcode < D_CODES; dcode++) {
  9946. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  9947. // }
  9948. // out_length >>>= 3;
  9949. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  9950. // // s->last_lit, in_length, out_length,
  9951. // // 100L - out_length*100L/in_length));
  9952. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  9953. // return true;
  9954. // }
  9955. // }
  9956. //#endif
  9957. return (s.last_lit === s.lit_bufsize - 1);
  9958. /* We avoid equality with lit_bufsize because of wraparound at 64K
  9959. * on 16 bit machines and because stored blocks are restricted to
  9960. * 64K-1 bytes.
  9961. */
  9962. }
  9963. exports._tr_init = _tr_init;
  9964. exports._tr_stored_block = _tr_stored_block;
  9965. exports._tr_flush_block = _tr_flush_block;
  9966. exports._tr_tally = _tr_tally;
  9967. exports._tr_align = _tr_align;
  9968. },{"../utils/common":41}],53:[function(require,module,exports){
  9969. 'use strict';
  9970. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9971. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9972. //
  9973. // This software is provided 'as-is', without any express or implied
  9974. // warranty. In no event will the authors be held liable for any damages
  9975. // arising from the use of this software.
  9976. //
  9977. // Permission is granted to anyone to use this software for any purpose,
  9978. // including commercial applications, and to alter it and redistribute it
  9979. // freely, subject to the following restrictions:
  9980. //
  9981. // 1. The origin of this software must not be misrepresented; you must not
  9982. // claim that you wrote the original software. If you use this software
  9983. // in a product, an acknowledgment in the product documentation would be
  9984. // appreciated but is not required.
  9985. // 2. Altered source versions must be plainly marked as such, and must not be
  9986. // misrepresented as being the original software.
  9987. // 3. This notice may not be removed or altered from any source distribution.
  9988. function ZStream() {
  9989. /* next input byte */
  9990. this.input = null; // JS specific, because we have no pointers
  9991. this.next_in = 0;
  9992. /* number of bytes available at input */
  9993. this.avail_in = 0;
  9994. /* total number of input bytes read so far */
  9995. this.total_in = 0;
  9996. /* next output byte should be put there */
  9997. this.output = null; // JS specific, because we have no pointers
  9998. this.next_out = 0;
  9999. /* remaining free space at output */
  10000. this.avail_out = 0;
  10001. /* total number of bytes output so far */
  10002. this.total_out = 0;
  10003. /* last error message, NULL if no error */
  10004. this.msg = ''/*Z_NULL*/;
  10005. /* not visible by applications */
  10006. this.state = null;
  10007. /* best guess about the data type: binary or text */
  10008. this.data_type = 2/*Z_UNKNOWN*/;
  10009. /* adler32 value of the uncompressed data */
  10010. this.adler = 0;
  10011. }
  10012. module.exports = ZStream;
  10013. },{}],54:[function(require,module,exports){
  10014. 'use strict';
  10015. module.exports = typeof setImmediate === 'function' ? setImmediate :
  10016. function setImmediate() {
  10017. var args = [].slice.apply(arguments);
  10018. args.splice(1, 0, 0);
  10019. setTimeout.apply(null, args);
  10020. };
  10021. },{}]},{},[10])(10)
  10022. });