luckyexcel.umd.js 706 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LuckyExcel = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. 'use strict'
  3. exports.byteLength = byteLength
  4. exports.toByteArray = toByteArray
  5. exports.fromByteArray = fromByteArray
  6. var lookup = []
  7. var revLookup = []
  8. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  9. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  10. for (var i = 0, len = code.length; i < len; ++i) {
  11. lookup[i] = code[i]
  12. revLookup[code.charCodeAt(i)] = i
  13. }
  14. // Support decoding URL-safe base64 strings, as Node.js does.
  15. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  16. revLookup['-'.charCodeAt(0)] = 62
  17. revLookup['_'.charCodeAt(0)] = 63
  18. function getLens (b64) {
  19. var len = b64.length
  20. if (len % 4 > 0) {
  21. throw new Error('Invalid string. Length must be a multiple of 4')
  22. }
  23. // Trim off extra bytes after placeholder bytes are found
  24. // See: https://github.com/beatgammit/base64-js/issues/42
  25. var validLen = b64.indexOf('=')
  26. if (validLen === -1) validLen = len
  27. var placeHoldersLen = validLen === len
  28. ? 0
  29. : 4 - (validLen % 4)
  30. return [validLen, placeHoldersLen]
  31. }
  32. // base64 is 4/3 + up to two characters of the original data
  33. function byteLength (b64) {
  34. var lens = getLens(b64)
  35. var validLen = lens[0]
  36. var placeHoldersLen = lens[1]
  37. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  38. }
  39. function _byteLength (b64, validLen, placeHoldersLen) {
  40. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  41. }
  42. function toByteArray (b64) {
  43. var tmp
  44. var lens = getLens(b64)
  45. var validLen = lens[0]
  46. var placeHoldersLen = lens[1]
  47. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  48. var curByte = 0
  49. // if there are placeholders, only get up to the last complete 4 chars
  50. var len = placeHoldersLen > 0
  51. ? validLen - 4
  52. : validLen
  53. var i
  54. for (i = 0; i < len; i += 4) {
  55. tmp =
  56. (revLookup[b64.charCodeAt(i)] << 18) |
  57. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  58. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  59. revLookup[b64.charCodeAt(i + 3)]
  60. arr[curByte++] = (tmp >> 16) & 0xFF
  61. arr[curByte++] = (tmp >> 8) & 0xFF
  62. arr[curByte++] = tmp & 0xFF
  63. }
  64. if (placeHoldersLen === 2) {
  65. tmp =
  66. (revLookup[b64.charCodeAt(i)] << 2) |
  67. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  68. arr[curByte++] = tmp & 0xFF
  69. }
  70. if (placeHoldersLen === 1) {
  71. tmp =
  72. (revLookup[b64.charCodeAt(i)] << 10) |
  73. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  74. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  75. arr[curByte++] = (tmp >> 8) & 0xFF
  76. arr[curByte++] = tmp & 0xFF
  77. }
  78. return arr
  79. }
  80. function tripletToBase64 (num) {
  81. return lookup[num >> 18 & 0x3F] +
  82. lookup[num >> 12 & 0x3F] +
  83. lookup[num >> 6 & 0x3F] +
  84. lookup[num & 0x3F]
  85. }
  86. function encodeChunk (uint8, start, end) {
  87. var tmp
  88. var output = []
  89. for (var i = start; i < end; i += 3) {
  90. tmp =
  91. ((uint8[i] << 16) & 0xFF0000) +
  92. ((uint8[i + 1] << 8) & 0xFF00) +
  93. (uint8[i + 2] & 0xFF)
  94. output.push(tripletToBase64(tmp))
  95. }
  96. return output.join('')
  97. }
  98. function fromByteArray (uint8) {
  99. var tmp
  100. var len = uint8.length
  101. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  102. var parts = []
  103. var maxChunkLength = 16383 // must be multiple of 3
  104. // go through the array every three bytes, we'll deal with trailing stuff later
  105. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  106. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  107. }
  108. // pad the end with zeros, but make sure to not forget the extra bytes
  109. if (extraBytes === 1) {
  110. tmp = uint8[len - 1]
  111. parts.push(
  112. lookup[tmp >> 2] +
  113. lookup[(tmp << 4) & 0x3F] +
  114. '=='
  115. )
  116. } else if (extraBytes === 2) {
  117. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  118. parts.push(
  119. lookup[tmp >> 10] +
  120. lookup[(tmp >> 4) & 0x3F] +
  121. lookup[(tmp << 2) & 0x3F] +
  122. '='
  123. )
  124. }
  125. return parts.join('')
  126. }
  127. },{}],2:[function(require,module,exports){
  128. },{}],3:[function(require,module,exports){
  129. (function (global,Buffer){
  130. /*!
  131. * The buffer module from node.js, for the browser.
  132. *
  133. * @author Feross Aboukhadijeh <http://feross.org>
  134. * @license MIT
  135. */
  136. /* eslint-disable no-proto */
  137. 'use strict'
  138. var base64 = require('base64-js')
  139. var ieee754 = require('ieee754')
  140. var isArray = require('isarray')
  141. exports.Buffer = Buffer
  142. exports.SlowBuffer = SlowBuffer
  143. exports.INSPECT_MAX_BYTES = 50
  144. /**
  145. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  146. * === true Use Uint8Array implementation (fastest)
  147. * === false Use Object implementation (most compatible, even IE6)
  148. *
  149. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  150. * Opera 11.6+, iOS 4.2+.
  151. *
  152. * Due to various browser bugs, sometimes the Object implementation will be used even
  153. * when the browser supports typed arrays.
  154. *
  155. * Note:
  156. *
  157. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  158. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  159. *
  160. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  161. *
  162. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  163. * incorrect length in some situations.
  164. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  165. * get the Object implementation, which is slower but behaves correctly.
  166. */
  167. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  168. ? global.TYPED_ARRAY_SUPPORT
  169. : typedArraySupport()
  170. /*
  171. * Export kMaxLength after typed array support is determined.
  172. */
  173. exports.kMaxLength = kMaxLength()
  174. function typedArraySupport () {
  175. try {
  176. var arr = new Uint8Array(1)
  177. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  178. return arr.foo() === 42 && // typed array instances can be augmented
  179. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  180. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  181. } catch (e) {
  182. return false
  183. }
  184. }
  185. function kMaxLength () {
  186. return Buffer.TYPED_ARRAY_SUPPORT
  187. ? 0x7fffffff
  188. : 0x3fffffff
  189. }
  190. function createBuffer (that, length) {
  191. if (kMaxLength() < length) {
  192. throw new RangeError('Invalid typed array length')
  193. }
  194. if (Buffer.TYPED_ARRAY_SUPPORT) {
  195. // Return an augmented `Uint8Array` instance, for best performance
  196. that = new Uint8Array(length)
  197. that.__proto__ = Buffer.prototype
  198. } else {
  199. // Fallback: Return an object instance of the Buffer class
  200. if (that === null) {
  201. that = new Buffer(length)
  202. }
  203. that.length = length
  204. }
  205. return that
  206. }
  207. /**
  208. * The Buffer constructor returns instances of `Uint8Array` that have their
  209. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  210. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  211. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  212. * returns a single octet.
  213. *
  214. * The `Uint8Array` prototype remains unmodified.
  215. */
  216. function Buffer (arg, encodingOrOffset, length) {
  217. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  218. return new Buffer(arg, encodingOrOffset, length)
  219. }
  220. // Common case.
  221. if (typeof arg === 'number') {
  222. if (typeof encodingOrOffset === 'string') {
  223. throw new Error(
  224. 'If encoding is specified then the first argument must be a string'
  225. )
  226. }
  227. return allocUnsafe(this, arg)
  228. }
  229. return from(this, arg, encodingOrOffset, length)
  230. }
  231. Buffer.poolSize = 8192 // not used by this implementation
  232. // TODO: Legacy, not needed anymore. Remove in next major version.
  233. Buffer._augment = function (arr) {
  234. arr.__proto__ = Buffer.prototype
  235. return arr
  236. }
  237. function from (that, value, encodingOrOffset, length) {
  238. if (typeof value === 'number') {
  239. throw new TypeError('"value" argument must not be a number')
  240. }
  241. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  242. return fromArrayBuffer(that, value, encodingOrOffset, length)
  243. }
  244. if (typeof value === 'string') {
  245. return fromString(that, value, encodingOrOffset)
  246. }
  247. return fromObject(that, value)
  248. }
  249. /**
  250. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  251. * if value is a number.
  252. * Buffer.from(str[, encoding])
  253. * Buffer.from(array)
  254. * Buffer.from(buffer)
  255. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  256. **/
  257. Buffer.from = function (value, encodingOrOffset, length) {
  258. return from(null, value, encodingOrOffset, length)
  259. }
  260. if (Buffer.TYPED_ARRAY_SUPPORT) {
  261. Buffer.prototype.__proto__ = Uint8Array.prototype
  262. Buffer.__proto__ = Uint8Array
  263. if (typeof Symbol !== 'undefined' && Symbol.species &&
  264. Buffer[Symbol.species] === Buffer) {
  265. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  266. Object.defineProperty(Buffer, Symbol.species, {
  267. value: null,
  268. configurable: true
  269. })
  270. }
  271. }
  272. function assertSize (size) {
  273. if (typeof size !== 'number') {
  274. throw new TypeError('"size" argument must be a number')
  275. } else if (size < 0) {
  276. throw new RangeError('"size" argument must not be negative')
  277. }
  278. }
  279. function alloc (that, size, fill, encoding) {
  280. assertSize(size)
  281. if (size <= 0) {
  282. return createBuffer(that, size)
  283. }
  284. if (fill !== undefined) {
  285. // Only pay attention to encoding if it's a string. This
  286. // prevents accidentally sending in a number that would
  287. // be interpretted as a start offset.
  288. return typeof encoding === 'string'
  289. ? createBuffer(that, size).fill(fill, encoding)
  290. : createBuffer(that, size).fill(fill)
  291. }
  292. return createBuffer(that, size)
  293. }
  294. /**
  295. * Creates a new filled Buffer instance.
  296. * alloc(size[, fill[, encoding]])
  297. **/
  298. Buffer.alloc = function (size, fill, encoding) {
  299. return alloc(null, size, fill, encoding)
  300. }
  301. function allocUnsafe (that, size) {
  302. assertSize(size)
  303. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  304. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  305. for (var i = 0; i < size; ++i) {
  306. that[i] = 0
  307. }
  308. }
  309. return that
  310. }
  311. /**
  312. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  313. * */
  314. Buffer.allocUnsafe = function (size) {
  315. return allocUnsafe(null, size)
  316. }
  317. /**
  318. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  319. */
  320. Buffer.allocUnsafeSlow = function (size) {
  321. return allocUnsafe(null, size)
  322. }
  323. function fromString (that, string, encoding) {
  324. if (typeof encoding !== 'string' || encoding === '') {
  325. encoding = 'utf8'
  326. }
  327. if (!Buffer.isEncoding(encoding)) {
  328. throw new TypeError('"encoding" must be a valid string encoding')
  329. }
  330. var length = byteLength(string, encoding) | 0
  331. that = createBuffer(that, length)
  332. var actual = that.write(string, encoding)
  333. if (actual !== length) {
  334. // Writing a hex string, for example, that contains invalid characters will
  335. // cause everything after the first invalid character to be ignored. (e.g.
  336. // 'abxxcd' will be treated as 'ab')
  337. that = that.slice(0, actual)
  338. }
  339. return that
  340. }
  341. function fromArrayLike (that, array) {
  342. var length = array.length < 0 ? 0 : checked(array.length) | 0
  343. that = createBuffer(that, length)
  344. for (var i = 0; i < length; i += 1) {
  345. that[i] = array[i] & 255
  346. }
  347. return that
  348. }
  349. function fromArrayBuffer (that, array, byteOffset, length) {
  350. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  351. if (byteOffset < 0 || array.byteLength < byteOffset) {
  352. throw new RangeError('\'offset\' is out of bounds')
  353. }
  354. if (array.byteLength < byteOffset + (length || 0)) {
  355. throw new RangeError('\'length\' is out of bounds')
  356. }
  357. if (byteOffset === undefined && length === undefined) {
  358. array = new Uint8Array(array)
  359. } else if (length === undefined) {
  360. array = new Uint8Array(array, byteOffset)
  361. } else {
  362. array = new Uint8Array(array, byteOffset, length)
  363. }
  364. if (Buffer.TYPED_ARRAY_SUPPORT) {
  365. // Return an augmented `Uint8Array` instance, for best performance
  366. that = array
  367. that.__proto__ = Buffer.prototype
  368. } else {
  369. // Fallback: Return an object instance of the Buffer class
  370. that = fromArrayLike(that, array)
  371. }
  372. return that
  373. }
  374. function fromObject (that, obj) {
  375. if (Buffer.isBuffer(obj)) {
  376. var len = checked(obj.length) | 0
  377. that = createBuffer(that, len)
  378. if (that.length === 0) {
  379. return that
  380. }
  381. obj.copy(that, 0, 0, len)
  382. return that
  383. }
  384. if (obj) {
  385. if ((typeof ArrayBuffer !== 'undefined' &&
  386. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  387. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  388. return createBuffer(that, 0)
  389. }
  390. return fromArrayLike(that, obj)
  391. }
  392. if (obj.type === 'Buffer' && isArray(obj.data)) {
  393. return fromArrayLike(that, obj.data)
  394. }
  395. }
  396. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  397. }
  398. function checked (length) {
  399. // Note: cannot use `length < kMaxLength()` here because that fails when
  400. // length is NaN (which is otherwise coerced to zero.)
  401. if (length >= kMaxLength()) {
  402. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  403. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  404. }
  405. return length | 0
  406. }
  407. function SlowBuffer (length) {
  408. if (+length != length) { // eslint-disable-line eqeqeq
  409. length = 0
  410. }
  411. return Buffer.alloc(+length)
  412. }
  413. Buffer.isBuffer = function isBuffer (b) {
  414. return !!(b != null && b._isBuffer)
  415. }
  416. Buffer.compare = function compare (a, b) {
  417. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  418. throw new TypeError('Arguments must be Buffers')
  419. }
  420. if (a === b) return 0
  421. var x = a.length
  422. var y = b.length
  423. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  424. if (a[i] !== b[i]) {
  425. x = a[i]
  426. y = b[i]
  427. break
  428. }
  429. }
  430. if (x < y) return -1
  431. if (y < x) return 1
  432. return 0
  433. }
  434. Buffer.isEncoding = function isEncoding (encoding) {
  435. switch (String(encoding).toLowerCase()) {
  436. case 'hex':
  437. case 'utf8':
  438. case 'utf-8':
  439. case 'ascii':
  440. case 'latin1':
  441. case 'binary':
  442. case 'base64':
  443. case 'ucs2':
  444. case 'ucs-2':
  445. case 'utf16le':
  446. case 'utf-16le':
  447. return true
  448. default:
  449. return false
  450. }
  451. }
  452. Buffer.concat = function concat (list, length) {
  453. if (!isArray(list)) {
  454. throw new TypeError('"list" argument must be an Array of Buffers')
  455. }
  456. if (list.length === 0) {
  457. return Buffer.alloc(0)
  458. }
  459. var i
  460. if (length === undefined) {
  461. length = 0
  462. for (i = 0; i < list.length; ++i) {
  463. length += list[i].length
  464. }
  465. }
  466. var buffer = Buffer.allocUnsafe(length)
  467. var pos = 0
  468. for (i = 0; i < list.length; ++i) {
  469. var buf = list[i]
  470. if (!Buffer.isBuffer(buf)) {
  471. throw new TypeError('"list" argument must be an Array of Buffers')
  472. }
  473. buf.copy(buffer, pos)
  474. pos += buf.length
  475. }
  476. return buffer
  477. }
  478. function byteLength (string, encoding) {
  479. if (Buffer.isBuffer(string)) {
  480. return string.length
  481. }
  482. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  483. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  484. return string.byteLength
  485. }
  486. if (typeof string !== 'string') {
  487. string = '' + string
  488. }
  489. var len = string.length
  490. if (len === 0) return 0
  491. // Use a for loop to avoid recursion
  492. var loweredCase = false
  493. for (;;) {
  494. switch (encoding) {
  495. case 'ascii':
  496. case 'latin1':
  497. case 'binary':
  498. return len
  499. case 'utf8':
  500. case 'utf-8':
  501. case undefined:
  502. return utf8ToBytes(string).length
  503. case 'ucs2':
  504. case 'ucs-2':
  505. case 'utf16le':
  506. case 'utf-16le':
  507. return len * 2
  508. case 'hex':
  509. return len >>> 1
  510. case 'base64':
  511. return base64ToBytes(string).length
  512. default:
  513. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  514. encoding = ('' + encoding).toLowerCase()
  515. loweredCase = true
  516. }
  517. }
  518. }
  519. Buffer.byteLength = byteLength
  520. function slowToString (encoding, start, end) {
  521. var loweredCase = false
  522. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  523. // property of a typed array.
  524. // This behaves neither like String nor Uint8Array in that we set start/end
  525. // to their upper/lower bounds if the value passed is out of range.
  526. // undefined is handled specially as per ECMA-262 6th Edition,
  527. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  528. if (start === undefined || start < 0) {
  529. start = 0
  530. }
  531. // Return early if start > this.length. Done here to prevent potential uint32
  532. // coercion fail below.
  533. if (start > this.length) {
  534. return ''
  535. }
  536. if (end === undefined || end > this.length) {
  537. end = this.length
  538. }
  539. if (end <= 0) {
  540. return ''
  541. }
  542. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  543. end >>>= 0
  544. start >>>= 0
  545. if (end <= start) {
  546. return ''
  547. }
  548. if (!encoding) encoding = 'utf8'
  549. while (true) {
  550. switch (encoding) {
  551. case 'hex':
  552. return hexSlice(this, start, end)
  553. case 'utf8':
  554. case 'utf-8':
  555. return utf8Slice(this, start, end)
  556. case 'ascii':
  557. return asciiSlice(this, start, end)
  558. case 'latin1':
  559. case 'binary':
  560. return latin1Slice(this, start, end)
  561. case 'base64':
  562. return base64Slice(this, start, end)
  563. case 'ucs2':
  564. case 'ucs-2':
  565. case 'utf16le':
  566. case 'utf-16le':
  567. return utf16leSlice(this, start, end)
  568. default:
  569. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  570. encoding = (encoding + '').toLowerCase()
  571. loweredCase = true
  572. }
  573. }
  574. }
  575. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  576. // Buffer instances.
  577. Buffer.prototype._isBuffer = true
  578. function swap (b, n, m) {
  579. var i = b[n]
  580. b[n] = b[m]
  581. b[m] = i
  582. }
  583. Buffer.prototype.swap16 = function swap16 () {
  584. var len = this.length
  585. if (len % 2 !== 0) {
  586. throw new RangeError('Buffer size must be a multiple of 16-bits')
  587. }
  588. for (var i = 0; i < len; i += 2) {
  589. swap(this, i, i + 1)
  590. }
  591. return this
  592. }
  593. Buffer.prototype.swap32 = function swap32 () {
  594. var len = this.length
  595. if (len % 4 !== 0) {
  596. throw new RangeError('Buffer size must be a multiple of 32-bits')
  597. }
  598. for (var i = 0; i < len; i += 4) {
  599. swap(this, i, i + 3)
  600. swap(this, i + 1, i + 2)
  601. }
  602. return this
  603. }
  604. Buffer.prototype.swap64 = function swap64 () {
  605. var len = this.length
  606. if (len % 8 !== 0) {
  607. throw new RangeError('Buffer size must be a multiple of 64-bits')
  608. }
  609. for (var i = 0; i < len; i += 8) {
  610. swap(this, i, i + 7)
  611. swap(this, i + 1, i + 6)
  612. swap(this, i + 2, i + 5)
  613. swap(this, i + 3, i + 4)
  614. }
  615. return this
  616. }
  617. Buffer.prototype.toString = function toString () {
  618. var length = this.length | 0
  619. if (length === 0) return ''
  620. if (arguments.length === 0) return utf8Slice(this, 0, length)
  621. return slowToString.apply(this, arguments)
  622. }
  623. Buffer.prototype.equals = function equals (b) {
  624. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  625. if (this === b) return true
  626. return Buffer.compare(this, b) === 0
  627. }
  628. Buffer.prototype.inspect = function inspect () {
  629. var str = ''
  630. var max = exports.INSPECT_MAX_BYTES
  631. if (this.length > 0) {
  632. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  633. if (this.length > max) str += ' ... '
  634. }
  635. return '<Buffer ' + str + '>'
  636. }
  637. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  638. if (!Buffer.isBuffer(target)) {
  639. throw new TypeError('Argument must be a Buffer')
  640. }
  641. if (start === undefined) {
  642. start = 0
  643. }
  644. if (end === undefined) {
  645. end = target ? target.length : 0
  646. }
  647. if (thisStart === undefined) {
  648. thisStart = 0
  649. }
  650. if (thisEnd === undefined) {
  651. thisEnd = this.length
  652. }
  653. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  654. throw new RangeError('out of range index')
  655. }
  656. if (thisStart >= thisEnd && start >= end) {
  657. return 0
  658. }
  659. if (thisStart >= thisEnd) {
  660. return -1
  661. }
  662. if (start >= end) {
  663. return 1
  664. }
  665. start >>>= 0
  666. end >>>= 0
  667. thisStart >>>= 0
  668. thisEnd >>>= 0
  669. if (this === target) return 0
  670. var x = thisEnd - thisStart
  671. var y = end - start
  672. var len = Math.min(x, y)
  673. var thisCopy = this.slice(thisStart, thisEnd)
  674. var targetCopy = target.slice(start, end)
  675. for (var i = 0; i < len; ++i) {
  676. if (thisCopy[i] !== targetCopy[i]) {
  677. x = thisCopy[i]
  678. y = targetCopy[i]
  679. break
  680. }
  681. }
  682. if (x < y) return -1
  683. if (y < x) return 1
  684. return 0
  685. }
  686. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  687. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  688. //
  689. // Arguments:
  690. // - buffer - a Buffer to search
  691. // - val - a string, Buffer, or number
  692. // - byteOffset - an index into `buffer`; will be clamped to an int32
  693. // - encoding - an optional encoding, relevant is val is a string
  694. // - dir - true for indexOf, false for lastIndexOf
  695. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  696. // Empty buffer means no match
  697. if (buffer.length === 0) return -1
  698. // Normalize byteOffset
  699. if (typeof byteOffset === 'string') {
  700. encoding = byteOffset
  701. byteOffset = 0
  702. } else if (byteOffset > 0x7fffffff) {
  703. byteOffset = 0x7fffffff
  704. } else if (byteOffset < -0x80000000) {
  705. byteOffset = -0x80000000
  706. }
  707. byteOffset = +byteOffset // Coerce to Number.
  708. if (isNaN(byteOffset)) {
  709. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  710. byteOffset = dir ? 0 : (buffer.length - 1)
  711. }
  712. // Normalize byteOffset: negative offsets start from the end of the buffer
  713. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  714. if (byteOffset >= buffer.length) {
  715. if (dir) return -1
  716. else byteOffset = buffer.length - 1
  717. } else if (byteOffset < 0) {
  718. if (dir) byteOffset = 0
  719. else return -1
  720. }
  721. // Normalize val
  722. if (typeof val === 'string') {
  723. val = Buffer.from(val, encoding)
  724. }
  725. // Finally, search either indexOf (if dir is true) or lastIndexOf
  726. if (Buffer.isBuffer(val)) {
  727. // Special case: looking for empty string/buffer always fails
  728. if (val.length === 0) {
  729. return -1
  730. }
  731. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  732. } else if (typeof val === 'number') {
  733. val = val & 0xFF // Search for a byte value [0-255]
  734. if (Buffer.TYPED_ARRAY_SUPPORT &&
  735. typeof Uint8Array.prototype.indexOf === 'function') {
  736. if (dir) {
  737. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  738. } else {
  739. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  740. }
  741. }
  742. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  743. }
  744. throw new TypeError('val must be string, number or Buffer')
  745. }
  746. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  747. var indexSize = 1
  748. var arrLength = arr.length
  749. var valLength = val.length
  750. if (encoding !== undefined) {
  751. encoding = String(encoding).toLowerCase()
  752. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  753. encoding === 'utf16le' || encoding === 'utf-16le') {
  754. if (arr.length < 2 || val.length < 2) {
  755. return -1
  756. }
  757. indexSize = 2
  758. arrLength /= 2
  759. valLength /= 2
  760. byteOffset /= 2
  761. }
  762. }
  763. function read (buf, i) {
  764. if (indexSize === 1) {
  765. return buf[i]
  766. } else {
  767. return buf.readUInt16BE(i * indexSize)
  768. }
  769. }
  770. var i
  771. if (dir) {
  772. var foundIndex = -1
  773. for (i = byteOffset; i < arrLength; i++) {
  774. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  775. if (foundIndex === -1) foundIndex = i
  776. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  777. } else {
  778. if (foundIndex !== -1) i -= i - foundIndex
  779. foundIndex = -1
  780. }
  781. }
  782. } else {
  783. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  784. for (i = byteOffset; i >= 0; i--) {
  785. var found = true
  786. for (var j = 0; j < valLength; j++) {
  787. if (read(arr, i + j) !== read(val, j)) {
  788. found = false
  789. break
  790. }
  791. }
  792. if (found) return i
  793. }
  794. }
  795. return -1
  796. }
  797. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  798. return this.indexOf(val, byteOffset, encoding) !== -1
  799. }
  800. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  801. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  802. }
  803. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  804. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  805. }
  806. function hexWrite (buf, string, offset, length) {
  807. offset = Number(offset) || 0
  808. var remaining = buf.length - offset
  809. if (!length) {
  810. length = remaining
  811. } else {
  812. length = Number(length)
  813. if (length > remaining) {
  814. length = remaining
  815. }
  816. }
  817. // must be an even number of digits
  818. var strLen = string.length
  819. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  820. if (length > strLen / 2) {
  821. length = strLen / 2
  822. }
  823. for (var i = 0; i < length; ++i) {
  824. var parsed = parseInt(string.substr(i * 2, 2), 16)
  825. if (isNaN(parsed)) return i
  826. buf[offset + i] = parsed
  827. }
  828. return i
  829. }
  830. function utf8Write (buf, string, offset, length) {
  831. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  832. }
  833. function asciiWrite (buf, string, offset, length) {
  834. return blitBuffer(asciiToBytes(string), buf, offset, length)
  835. }
  836. function latin1Write (buf, string, offset, length) {
  837. return asciiWrite(buf, string, offset, length)
  838. }
  839. function base64Write (buf, string, offset, length) {
  840. return blitBuffer(base64ToBytes(string), buf, offset, length)
  841. }
  842. function ucs2Write (buf, string, offset, length) {
  843. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  844. }
  845. Buffer.prototype.write = function write (string, offset, length, encoding) {
  846. // Buffer#write(string)
  847. if (offset === undefined) {
  848. encoding = 'utf8'
  849. length = this.length
  850. offset = 0
  851. // Buffer#write(string, encoding)
  852. } else if (length === undefined && typeof offset === 'string') {
  853. encoding = offset
  854. length = this.length
  855. offset = 0
  856. // Buffer#write(string, offset[, length][, encoding])
  857. } else if (isFinite(offset)) {
  858. offset = offset | 0
  859. if (isFinite(length)) {
  860. length = length | 0
  861. if (encoding === undefined) encoding = 'utf8'
  862. } else {
  863. encoding = length
  864. length = undefined
  865. }
  866. // legacy write(string, encoding, offset, length) - remove in v0.13
  867. } else {
  868. throw new Error(
  869. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  870. )
  871. }
  872. var remaining = this.length - offset
  873. if (length === undefined || length > remaining) length = remaining
  874. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  875. throw new RangeError('Attempt to write outside buffer bounds')
  876. }
  877. if (!encoding) encoding = 'utf8'
  878. var loweredCase = false
  879. for (;;) {
  880. switch (encoding) {
  881. case 'hex':
  882. return hexWrite(this, string, offset, length)
  883. case 'utf8':
  884. case 'utf-8':
  885. return utf8Write(this, string, offset, length)
  886. case 'ascii':
  887. return asciiWrite(this, string, offset, length)
  888. case 'latin1':
  889. case 'binary':
  890. return latin1Write(this, string, offset, length)
  891. case 'base64':
  892. // Warning: maxLength not taken into account in base64Write
  893. return base64Write(this, string, offset, length)
  894. case 'ucs2':
  895. case 'ucs-2':
  896. case 'utf16le':
  897. case 'utf-16le':
  898. return ucs2Write(this, string, offset, length)
  899. default:
  900. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  901. encoding = ('' + encoding).toLowerCase()
  902. loweredCase = true
  903. }
  904. }
  905. }
  906. Buffer.prototype.toJSON = function toJSON () {
  907. return {
  908. type: 'Buffer',
  909. data: Array.prototype.slice.call(this._arr || this, 0)
  910. }
  911. }
  912. function base64Slice (buf, start, end) {
  913. if (start === 0 && end === buf.length) {
  914. return base64.fromByteArray(buf)
  915. } else {
  916. return base64.fromByteArray(buf.slice(start, end))
  917. }
  918. }
  919. function utf8Slice (buf, start, end) {
  920. end = Math.min(buf.length, end)
  921. var res = []
  922. var i = start
  923. while (i < end) {
  924. var firstByte = buf[i]
  925. var codePoint = null
  926. var bytesPerSequence = (firstByte > 0xEF) ? 4
  927. : (firstByte > 0xDF) ? 3
  928. : (firstByte > 0xBF) ? 2
  929. : 1
  930. if (i + bytesPerSequence <= end) {
  931. var secondByte, thirdByte, fourthByte, tempCodePoint
  932. switch (bytesPerSequence) {
  933. case 1:
  934. if (firstByte < 0x80) {
  935. codePoint = firstByte
  936. }
  937. break
  938. case 2:
  939. secondByte = buf[i + 1]
  940. if ((secondByte & 0xC0) === 0x80) {
  941. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  942. if (tempCodePoint > 0x7F) {
  943. codePoint = tempCodePoint
  944. }
  945. }
  946. break
  947. case 3:
  948. secondByte = buf[i + 1]
  949. thirdByte = buf[i + 2]
  950. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  951. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  952. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  953. codePoint = tempCodePoint
  954. }
  955. }
  956. break
  957. case 4:
  958. secondByte = buf[i + 1]
  959. thirdByte = buf[i + 2]
  960. fourthByte = buf[i + 3]
  961. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  962. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  963. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  964. codePoint = tempCodePoint
  965. }
  966. }
  967. }
  968. }
  969. if (codePoint === null) {
  970. // we did not generate a valid codePoint so insert a
  971. // replacement char (U+FFFD) and advance only 1 byte
  972. codePoint = 0xFFFD
  973. bytesPerSequence = 1
  974. } else if (codePoint > 0xFFFF) {
  975. // encode to utf16 (surrogate pair dance)
  976. codePoint -= 0x10000
  977. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  978. codePoint = 0xDC00 | codePoint & 0x3FF
  979. }
  980. res.push(codePoint)
  981. i += bytesPerSequence
  982. }
  983. return decodeCodePointsArray(res)
  984. }
  985. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  986. // the lowest limit is Chrome, with 0x10000 args.
  987. // We go 1 magnitude less, for safety
  988. var MAX_ARGUMENTS_LENGTH = 0x1000
  989. function decodeCodePointsArray (codePoints) {
  990. var len = codePoints.length
  991. if (len <= MAX_ARGUMENTS_LENGTH) {
  992. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  993. }
  994. // Decode in chunks to avoid "call stack size exceeded".
  995. var res = ''
  996. var i = 0
  997. while (i < len) {
  998. res += String.fromCharCode.apply(
  999. String,
  1000. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1001. )
  1002. }
  1003. return res
  1004. }
  1005. function asciiSlice (buf, start, end) {
  1006. var ret = ''
  1007. end = Math.min(buf.length, end)
  1008. for (var i = start; i < end; ++i) {
  1009. ret += String.fromCharCode(buf[i] & 0x7F)
  1010. }
  1011. return ret
  1012. }
  1013. function latin1Slice (buf, start, end) {
  1014. var ret = ''
  1015. end = Math.min(buf.length, end)
  1016. for (var i = start; i < end; ++i) {
  1017. ret += String.fromCharCode(buf[i])
  1018. }
  1019. return ret
  1020. }
  1021. function hexSlice (buf, start, end) {
  1022. var len = buf.length
  1023. if (!start || start < 0) start = 0
  1024. if (!end || end < 0 || end > len) end = len
  1025. var out = ''
  1026. for (var i = start; i < end; ++i) {
  1027. out += toHex(buf[i])
  1028. }
  1029. return out
  1030. }
  1031. function utf16leSlice (buf, start, end) {
  1032. var bytes = buf.slice(start, end)
  1033. var res = ''
  1034. for (var i = 0; i < bytes.length; i += 2) {
  1035. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1036. }
  1037. return res
  1038. }
  1039. Buffer.prototype.slice = function slice (start, end) {
  1040. var len = this.length
  1041. start = ~~start
  1042. end = end === undefined ? len : ~~end
  1043. if (start < 0) {
  1044. start += len
  1045. if (start < 0) start = 0
  1046. } else if (start > len) {
  1047. start = len
  1048. }
  1049. if (end < 0) {
  1050. end += len
  1051. if (end < 0) end = 0
  1052. } else if (end > len) {
  1053. end = len
  1054. }
  1055. if (end < start) end = start
  1056. var newBuf
  1057. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1058. newBuf = this.subarray(start, end)
  1059. newBuf.__proto__ = Buffer.prototype
  1060. } else {
  1061. var sliceLen = end - start
  1062. newBuf = new Buffer(sliceLen, undefined)
  1063. for (var i = 0; i < sliceLen; ++i) {
  1064. newBuf[i] = this[i + start]
  1065. }
  1066. }
  1067. return newBuf
  1068. }
  1069. /*
  1070. * Need to make sure that buffer isn't trying to write out of bounds.
  1071. */
  1072. function checkOffset (offset, ext, length) {
  1073. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1074. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1075. }
  1076. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1077. offset = offset | 0
  1078. byteLength = byteLength | 0
  1079. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1080. var val = this[offset]
  1081. var mul = 1
  1082. var i = 0
  1083. while (++i < byteLength && (mul *= 0x100)) {
  1084. val += this[offset + i] * mul
  1085. }
  1086. return val
  1087. }
  1088. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1089. offset = offset | 0
  1090. byteLength = byteLength | 0
  1091. if (!noAssert) {
  1092. checkOffset(offset, byteLength, this.length)
  1093. }
  1094. var val = this[offset + --byteLength]
  1095. var mul = 1
  1096. while (byteLength > 0 && (mul *= 0x100)) {
  1097. val += this[offset + --byteLength] * mul
  1098. }
  1099. return val
  1100. }
  1101. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1102. if (!noAssert) checkOffset(offset, 1, this.length)
  1103. return this[offset]
  1104. }
  1105. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1106. if (!noAssert) checkOffset(offset, 2, this.length)
  1107. return this[offset] | (this[offset + 1] << 8)
  1108. }
  1109. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1110. if (!noAssert) checkOffset(offset, 2, this.length)
  1111. return (this[offset] << 8) | this[offset + 1]
  1112. }
  1113. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1114. if (!noAssert) checkOffset(offset, 4, this.length)
  1115. return ((this[offset]) |
  1116. (this[offset + 1] << 8) |
  1117. (this[offset + 2] << 16)) +
  1118. (this[offset + 3] * 0x1000000)
  1119. }
  1120. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1121. if (!noAssert) checkOffset(offset, 4, this.length)
  1122. return (this[offset] * 0x1000000) +
  1123. ((this[offset + 1] << 16) |
  1124. (this[offset + 2] << 8) |
  1125. this[offset + 3])
  1126. }
  1127. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1128. offset = offset | 0
  1129. byteLength = byteLength | 0
  1130. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1131. var val = this[offset]
  1132. var mul = 1
  1133. var i = 0
  1134. while (++i < byteLength && (mul *= 0x100)) {
  1135. val += this[offset + i] * mul
  1136. }
  1137. mul *= 0x80
  1138. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1139. return val
  1140. }
  1141. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1142. offset = offset | 0
  1143. byteLength = byteLength | 0
  1144. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1145. var i = byteLength
  1146. var mul = 1
  1147. var val = this[offset + --i]
  1148. while (i > 0 && (mul *= 0x100)) {
  1149. val += this[offset + --i] * mul
  1150. }
  1151. mul *= 0x80
  1152. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1153. return val
  1154. }
  1155. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1156. if (!noAssert) checkOffset(offset, 1, this.length)
  1157. if (!(this[offset] & 0x80)) return (this[offset])
  1158. return ((0xff - this[offset] + 1) * -1)
  1159. }
  1160. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1161. if (!noAssert) checkOffset(offset, 2, this.length)
  1162. var val = this[offset] | (this[offset + 1] << 8)
  1163. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1164. }
  1165. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1166. if (!noAssert) checkOffset(offset, 2, this.length)
  1167. var val = this[offset + 1] | (this[offset] << 8)
  1168. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1169. }
  1170. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1171. if (!noAssert) checkOffset(offset, 4, this.length)
  1172. return (this[offset]) |
  1173. (this[offset + 1] << 8) |
  1174. (this[offset + 2] << 16) |
  1175. (this[offset + 3] << 24)
  1176. }
  1177. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1178. if (!noAssert) checkOffset(offset, 4, this.length)
  1179. return (this[offset] << 24) |
  1180. (this[offset + 1] << 16) |
  1181. (this[offset + 2] << 8) |
  1182. (this[offset + 3])
  1183. }
  1184. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1185. if (!noAssert) checkOffset(offset, 4, this.length)
  1186. return ieee754.read(this, offset, true, 23, 4)
  1187. }
  1188. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1189. if (!noAssert) checkOffset(offset, 4, this.length)
  1190. return ieee754.read(this, offset, false, 23, 4)
  1191. }
  1192. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 8, this.length)
  1194. return ieee754.read(this, offset, true, 52, 8)
  1195. }
  1196. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1197. if (!noAssert) checkOffset(offset, 8, this.length)
  1198. return ieee754.read(this, offset, false, 52, 8)
  1199. }
  1200. function checkInt (buf, value, offset, ext, max, min) {
  1201. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1202. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1203. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1204. }
  1205. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1206. value = +value
  1207. offset = offset | 0
  1208. byteLength = byteLength | 0
  1209. if (!noAssert) {
  1210. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1211. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1212. }
  1213. var mul = 1
  1214. var i = 0
  1215. this[offset] = value & 0xFF
  1216. while (++i < byteLength && (mul *= 0x100)) {
  1217. this[offset + i] = (value / mul) & 0xFF
  1218. }
  1219. return offset + byteLength
  1220. }
  1221. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1222. value = +value
  1223. offset = offset | 0
  1224. byteLength = byteLength | 0
  1225. if (!noAssert) {
  1226. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1227. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1228. }
  1229. var i = byteLength - 1
  1230. var mul = 1
  1231. this[offset + i] = value & 0xFF
  1232. while (--i >= 0 && (mul *= 0x100)) {
  1233. this[offset + i] = (value / mul) & 0xFF
  1234. }
  1235. return offset + byteLength
  1236. }
  1237. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1238. value = +value
  1239. offset = offset | 0
  1240. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1241. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1242. this[offset] = (value & 0xff)
  1243. return offset + 1
  1244. }
  1245. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1246. if (value < 0) value = 0xffff + value + 1
  1247. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1248. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1249. (littleEndian ? i : 1 - i) * 8
  1250. }
  1251. }
  1252. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1253. value = +value
  1254. offset = offset | 0
  1255. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1256. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1257. this[offset] = (value & 0xff)
  1258. this[offset + 1] = (value >>> 8)
  1259. } else {
  1260. objectWriteUInt16(this, value, offset, true)
  1261. }
  1262. return offset + 2
  1263. }
  1264. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1265. value = +value
  1266. offset = offset | 0
  1267. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1268. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1269. this[offset] = (value >>> 8)
  1270. this[offset + 1] = (value & 0xff)
  1271. } else {
  1272. objectWriteUInt16(this, value, offset, false)
  1273. }
  1274. return offset + 2
  1275. }
  1276. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1277. if (value < 0) value = 0xffffffff + value + 1
  1278. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1279. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1280. }
  1281. }
  1282. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1283. value = +value
  1284. offset = offset | 0
  1285. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1286. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1287. this[offset + 3] = (value >>> 24)
  1288. this[offset + 2] = (value >>> 16)
  1289. this[offset + 1] = (value >>> 8)
  1290. this[offset] = (value & 0xff)
  1291. } else {
  1292. objectWriteUInt32(this, value, offset, true)
  1293. }
  1294. return offset + 4
  1295. }
  1296. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1297. value = +value
  1298. offset = offset | 0
  1299. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1300. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1301. this[offset] = (value >>> 24)
  1302. this[offset + 1] = (value >>> 16)
  1303. this[offset + 2] = (value >>> 8)
  1304. this[offset + 3] = (value & 0xff)
  1305. } else {
  1306. objectWriteUInt32(this, value, offset, false)
  1307. }
  1308. return offset + 4
  1309. }
  1310. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1311. value = +value
  1312. offset = offset | 0
  1313. if (!noAssert) {
  1314. var limit = Math.pow(2, 8 * byteLength - 1)
  1315. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1316. }
  1317. var i = 0
  1318. var mul = 1
  1319. var sub = 0
  1320. this[offset] = value & 0xFF
  1321. while (++i < byteLength && (mul *= 0x100)) {
  1322. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1323. sub = 1
  1324. }
  1325. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1326. }
  1327. return offset + byteLength
  1328. }
  1329. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1330. value = +value
  1331. offset = offset | 0
  1332. if (!noAssert) {
  1333. var limit = Math.pow(2, 8 * byteLength - 1)
  1334. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1335. }
  1336. var i = byteLength - 1
  1337. var mul = 1
  1338. var sub = 0
  1339. this[offset + i] = value & 0xFF
  1340. while (--i >= 0 && (mul *= 0x100)) {
  1341. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1342. sub = 1
  1343. }
  1344. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1345. }
  1346. return offset + byteLength
  1347. }
  1348. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1349. value = +value
  1350. offset = offset | 0
  1351. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1352. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1353. if (value < 0) value = 0xff + value + 1
  1354. this[offset] = (value & 0xff)
  1355. return offset + 1
  1356. }
  1357. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1358. value = +value
  1359. offset = offset | 0
  1360. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1361. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1362. this[offset] = (value & 0xff)
  1363. this[offset + 1] = (value >>> 8)
  1364. } else {
  1365. objectWriteUInt16(this, value, offset, true)
  1366. }
  1367. return offset + 2
  1368. }
  1369. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1370. value = +value
  1371. offset = offset | 0
  1372. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1373. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1374. this[offset] = (value >>> 8)
  1375. this[offset + 1] = (value & 0xff)
  1376. } else {
  1377. objectWriteUInt16(this, value, offset, false)
  1378. }
  1379. return offset + 2
  1380. }
  1381. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1382. value = +value
  1383. offset = offset | 0
  1384. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1385. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1386. this[offset] = (value & 0xff)
  1387. this[offset + 1] = (value >>> 8)
  1388. this[offset + 2] = (value >>> 16)
  1389. this[offset + 3] = (value >>> 24)
  1390. } else {
  1391. objectWriteUInt32(this, value, offset, true)
  1392. }
  1393. return offset + 4
  1394. }
  1395. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1396. value = +value
  1397. offset = offset | 0
  1398. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1399. if (value < 0) value = 0xffffffff + value + 1
  1400. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1401. this[offset] = (value >>> 24)
  1402. this[offset + 1] = (value >>> 16)
  1403. this[offset + 2] = (value >>> 8)
  1404. this[offset + 3] = (value & 0xff)
  1405. } else {
  1406. objectWriteUInt32(this, value, offset, false)
  1407. }
  1408. return offset + 4
  1409. }
  1410. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1411. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1412. if (offset < 0) throw new RangeError('Index out of range')
  1413. }
  1414. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1415. if (!noAssert) {
  1416. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1417. }
  1418. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1419. return offset + 4
  1420. }
  1421. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1422. return writeFloat(this, value, offset, true, noAssert)
  1423. }
  1424. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1425. return writeFloat(this, value, offset, false, noAssert)
  1426. }
  1427. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1428. if (!noAssert) {
  1429. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1430. }
  1431. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1432. return offset + 8
  1433. }
  1434. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1435. return writeDouble(this, value, offset, true, noAssert)
  1436. }
  1437. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1438. return writeDouble(this, value, offset, false, noAssert)
  1439. }
  1440. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1441. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1442. if (!start) start = 0
  1443. if (!end && end !== 0) end = this.length
  1444. if (targetStart >= target.length) targetStart = target.length
  1445. if (!targetStart) targetStart = 0
  1446. if (end > 0 && end < start) end = start
  1447. // Copy 0 bytes; we're done
  1448. if (end === start) return 0
  1449. if (target.length === 0 || this.length === 0) return 0
  1450. // Fatal error conditions
  1451. if (targetStart < 0) {
  1452. throw new RangeError('targetStart out of bounds')
  1453. }
  1454. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1455. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1456. // Are we oob?
  1457. if (end > this.length) end = this.length
  1458. if (target.length - targetStart < end - start) {
  1459. end = target.length - targetStart + start
  1460. }
  1461. var len = end - start
  1462. var i
  1463. if (this === target && start < targetStart && targetStart < end) {
  1464. // descending copy from end
  1465. for (i = len - 1; i >= 0; --i) {
  1466. target[i + targetStart] = this[i + start]
  1467. }
  1468. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1469. // ascending copy from start
  1470. for (i = 0; i < len; ++i) {
  1471. target[i + targetStart] = this[i + start]
  1472. }
  1473. } else {
  1474. Uint8Array.prototype.set.call(
  1475. target,
  1476. this.subarray(start, start + len),
  1477. targetStart
  1478. )
  1479. }
  1480. return len
  1481. }
  1482. // Usage:
  1483. // buffer.fill(number[, offset[, end]])
  1484. // buffer.fill(buffer[, offset[, end]])
  1485. // buffer.fill(string[, offset[, end]][, encoding])
  1486. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1487. // Handle string cases:
  1488. if (typeof val === 'string') {
  1489. if (typeof start === 'string') {
  1490. encoding = start
  1491. start = 0
  1492. end = this.length
  1493. } else if (typeof end === 'string') {
  1494. encoding = end
  1495. end = this.length
  1496. }
  1497. if (val.length === 1) {
  1498. var code = val.charCodeAt(0)
  1499. if (code < 256) {
  1500. val = code
  1501. }
  1502. }
  1503. if (encoding !== undefined && typeof encoding !== 'string') {
  1504. throw new TypeError('encoding must be a string')
  1505. }
  1506. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1507. throw new TypeError('Unknown encoding: ' + encoding)
  1508. }
  1509. } else if (typeof val === 'number') {
  1510. val = val & 255
  1511. }
  1512. // Invalid ranges are not set to a default, so can range check early.
  1513. if (start < 0 || this.length < start || this.length < end) {
  1514. throw new RangeError('Out of range index')
  1515. }
  1516. if (end <= start) {
  1517. return this
  1518. }
  1519. start = start >>> 0
  1520. end = end === undefined ? this.length : end >>> 0
  1521. if (!val) val = 0
  1522. var i
  1523. if (typeof val === 'number') {
  1524. for (i = start; i < end; ++i) {
  1525. this[i] = val
  1526. }
  1527. } else {
  1528. var bytes = Buffer.isBuffer(val)
  1529. ? val
  1530. : utf8ToBytes(new Buffer(val, encoding).toString())
  1531. var len = bytes.length
  1532. for (i = 0; i < end - start; ++i) {
  1533. this[i + start] = bytes[i % len]
  1534. }
  1535. }
  1536. return this
  1537. }
  1538. // HELPER FUNCTIONS
  1539. // ================
  1540. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1541. function base64clean (str) {
  1542. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1543. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1544. // Node converts strings with length < 2 to ''
  1545. if (str.length < 2) return ''
  1546. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1547. while (str.length % 4 !== 0) {
  1548. str = str + '='
  1549. }
  1550. return str
  1551. }
  1552. function stringtrim (str) {
  1553. if (str.trim) return str.trim()
  1554. return str.replace(/^\s+|\s+$/g, '')
  1555. }
  1556. function toHex (n) {
  1557. if (n < 16) return '0' + n.toString(16)
  1558. return n.toString(16)
  1559. }
  1560. function utf8ToBytes (string, units) {
  1561. units = units || Infinity
  1562. var codePoint
  1563. var length = string.length
  1564. var leadSurrogate = null
  1565. var bytes = []
  1566. for (var i = 0; i < length; ++i) {
  1567. codePoint = string.charCodeAt(i)
  1568. // is surrogate component
  1569. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1570. // last char was a lead
  1571. if (!leadSurrogate) {
  1572. // no lead yet
  1573. if (codePoint > 0xDBFF) {
  1574. // unexpected trail
  1575. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1576. continue
  1577. } else if (i + 1 === length) {
  1578. // unpaired lead
  1579. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1580. continue
  1581. }
  1582. // valid lead
  1583. leadSurrogate = codePoint
  1584. continue
  1585. }
  1586. // 2 leads in a row
  1587. if (codePoint < 0xDC00) {
  1588. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1589. leadSurrogate = codePoint
  1590. continue
  1591. }
  1592. // valid surrogate pair
  1593. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1594. } else if (leadSurrogate) {
  1595. // valid bmp char, but last char was a lead
  1596. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1597. }
  1598. leadSurrogate = null
  1599. // encode utf8
  1600. if (codePoint < 0x80) {
  1601. if ((units -= 1) < 0) break
  1602. bytes.push(codePoint)
  1603. } else if (codePoint < 0x800) {
  1604. if ((units -= 2) < 0) break
  1605. bytes.push(
  1606. codePoint >> 0x6 | 0xC0,
  1607. codePoint & 0x3F | 0x80
  1608. )
  1609. } else if (codePoint < 0x10000) {
  1610. if ((units -= 3) < 0) break
  1611. bytes.push(
  1612. codePoint >> 0xC | 0xE0,
  1613. codePoint >> 0x6 & 0x3F | 0x80,
  1614. codePoint & 0x3F | 0x80
  1615. )
  1616. } else if (codePoint < 0x110000) {
  1617. if ((units -= 4) < 0) break
  1618. bytes.push(
  1619. codePoint >> 0x12 | 0xF0,
  1620. codePoint >> 0xC & 0x3F | 0x80,
  1621. codePoint >> 0x6 & 0x3F | 0x80,
  1622. codePoint & 0x3F | 0x80
  1623. )
  1624. } else {
  1625. throw new Error('Invalid code point')
  1626. }
  1627. }
  1628. return bytes
  1629. }
  1630. function asciiToBytes (str) {
  1631. var byteArray = []
  1632. for (var i = 0; i < str.length; ++i) {
  1633. // Node's code seems to be doing this and not & 0x7F..
  1634. byteArray.push(str.charCodeAt(i) & 0xFF)
  1635. }
  1636. return byteArray
  1637. }
  1638. function utf16leToBytes (str, units) {
  1639. var c, hi, lo
  1640. var byteArray = []
  1641. for (var i = 0; i < str.length; ++i) {
  1642. if ((units -= 2) < 0) break
  1643. c = str.charCodeAt(i)
  1644. hi = c >> 8
  1645. lo = c % 256
  1646. byteArray.push(lo)
  1647. byteArray.push(hi)
  1648. }
  1649. return byteArray
  1650. }
  1651. function base64ToBytes (str) {
  1652. return base64.toByteArray(base64clean(str))
  1653. }
  1654. function blitBuffer (src, dst, offset, length) {
  1655. for (var i = 0; i < length; ++i) {
  1656. if ((i + offset >= dst.length) || (i >= src.length)) break
  1657. dst[i + offset] = src[i]
  1658. }
  1659. return i
  1660. }
  1661. function isnan (val) {
  1662. return val !== val // eslint-disable-line no-self-compare
  1663. }
  1664. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  1665. },{"base64-js":1,"buffer":3,"ieee754":7,"isarray":11}],4:[function(require,module,exports){
  1666. (function (Buffer){
  1667. // Copyright Joyent, Inc. and other Node contributors.
  1668. //
  1669. // Permission is hereby granted, free of charge, to any person obtaining a
  1670. // copy of this software and associated documentation files (the
  1671. // "Software"), to deal in the Software without restriction, including
  1672. // without limitation the rights to use, copy, modify, merge, publish,
  1673. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1674. // persons to whom the Software is furnished to do so, subject to the
  1675. // following conditions:
  1676. //
  1677. // The above copyright notice and this permission notice shall be included
  1678. // in all copies or substantial portions of the Software.
  1679. //
  1680. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1681. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1682. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1683. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1684. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1685. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1686. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1687. // NOTE: These type checking functions intentionally don't use `instanceof`
  1688. // because it is fragile and can be easily faked with `Object.create()`.
  1689. function isArray(arg) {
  1690. if (Array.isArray) {
  1691. return Array.isArray(arg);
  1692. }
  1693. return objectToString(arg) === '[object Array]';
  1694. }
  1695. exports.isArray = isArray;
  1696. function isBoolean(arg) {
  1697. return typeof arg === 'boolean';
  1698. }
  1699. exports.isBoolean = isBoolean;
  1700. function isNull(arg) {
  1701. return arg === null;
  1702. }
  1703. exports.isNull = isNull;
  1704. function isNullOrUndefined(arg) {
  1705. return arg == null;
  1706. }
  1707. exports.isNullOrUndefined = isNullOrUndefined;
  1708. function isNumber(arg) {
  1709. return typeof arg === 'number';
  1710. }
  1711. exports.isNumber = isNumber;
  1712. function isString(arg) {
  1713. return typeof arg === 'string';
  1714. }
  1715. exports.isString = isString;
  1716. function isSymbol(arg) {
  1717. return typeof arg === 'symbol';
  1718. }
  1719. exports.isSymbol = isSymbol;
  1720. function isUndefined(arg) {
  1721. return arg === void 0;
  1722. }
  1723. exports.isUndefined = isUndefined;
  1724. function isRegExp(re) {
  1725. return objectToString(re) === '[object RegExp]';
  1726. }
  1727. exports.isRegExp = isRegExp;
  1728. function isObject(arg) {
  1729. return typeof arg === 'object' && arg !== null;
  1730. }
  1731. exports.isObject = isObject;
  1732. function isDate(d) {
  1733. return objectToString(d) === '[object Date]';
  1734. }
  1735. exports.isDate = isDate;
  1736. function isError(e) {
  1737. return (objectToString(e) === '[object Error]' || e instanceof Error);
  1738. }
  1739. exports.isError = isError;
  1740. function isFunction(arg) {
  1741. return typeof arg === 'function';
  1742. }
  1743. exports.isFunction = isFunction;
  1744. function isPrimitive(arg) {
  1745. return arg === null ||
  1746. typeof arg === 'boolean' ||
  1747. typeof arg === 'number' ||
  1748. typeof arg === 'string' ||
  1749. typeof arg === 'symbol' || // ES6 symbol
  1750. typeof arg === 'undefined';
  1751. }
  1752. exports.isPrimitive = isPrimitive;
  1753. exports.isBuffer = Buffer.isBuffer;
  1754. function objectToString(o) {
  1755. return Object.prototype.toString.call(o);
  1756. }
  1757. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  1758. },{"../../is-buffer/index.js":10}],5:[function(require,module,exports){
  1759. !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",f="month",h="quarter",c="year",d="date",$="Invalid Date",l=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},g={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,f),s=n-i<0,u=e.clone().add(r+(s?-1:1),f);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:f,y:c,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:h}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},D="en",v={};v[D]=M;var p=function(t){return t instanceof _},S=function(t,e,n){var r;if(!t)return D;if("string"==typeof t)v[t]&&(r=t),e&&(v[t]=e,r=t);else{var i=t.name;v[i]=t,r=i}return!n&&r&&(D=r),r||!n&&D},w=function(t,e){if(p(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},O=g;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t)}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match(l);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return O},m.isValid=function(){return!(this.$d.toString()===$)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,h=O.p(t),$=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},l=function(t,e){return O.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,g="set"+(this.$u?"UTC":"");switch(h){case c:return r?$(1,0):$(31,11);case f:return r?$(1,M):$(0,M+1);case o:var D=this.$locale().weekStart||0,v=(y<D?y+7:y)-D;return $(r?m-v:m+(6-v),M);case a:case d:return l(g+"Hours",0);case u:return l(g+"Minutes",1);case s:return l(g+"Seconds",2);case i:return l(g+"Milliseconds",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),h="set"+(this.$u?"UTC":""),$=(n={},n[a]=h+"Date",n[d]=h+"Date",n[f]=h+"Month",n[c]=h+"FullYear",n[u]=h+"Hours",n[s]=h+"Minutes",n[i]=h+"Seconds",n[r]=h+"Milliseconds",n)[o],l=o===a?this.$D+(e-this.$W):e;if(o===f||o===c){var y=this.clone().set(d,1);y.$d[$](l),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else $&&this.$d[$](l);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,h){var d,$=this;r=Number(r);var l=O.p(h),y=function(t){var e=w($);return O.w(e.date(e.date()+Math.round(t*r)),$)};if(l===f)return this.set(f,this.$M+r);if(l===c)return this.set(c,this.$y+r);if(l===a)return y(1);if(l===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[l]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||$;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,f=n.months,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].substr(0,s)},c=function(t){return O.s(s%12||12,t,"0")},d=n.meridiem||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r},l={YY:String(this.$y).slice(-2),YYYY:this.$y,M:a+1,MM:O.s(a+1,2,"0"),MMM:h(n.monthsShort,a,f,3),MMMM:h(f,a),D:this.$D,DD:O.s(this.$D,2,"0"),d:String(this.$W),dd:h(n.weekdaysMin,this.$W,o,2),ddd:h(n.weekdaysShort,this.$W,o,3),dddd:o[this.$W],H:String(s),HH:O.s(s,2,"0"),h:c(1),hh:c(2),a:d(s,u,!0),A:d(s,u,!1),m:String(u),mm:O.s(u,2,"0"),s:String(this.$s),ss:O.s(this.$s,2,"0"),SSS:O.s(this.$ms,3,"0"),Z:i};return r.replace(y,(function(t,e){return e||l[t]||i.replace(":","")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,$){var l,y=O.p(d),M=w(r),m=(M.utcOffset()-this.utcOffset())*e,g=this-M,D=O.m(this,M);return D=(l={},l[c]=D/12,l[f]=D,l[h]=D/3,l[o]=(g-m)/6048e5,l[a]=(g-m)/864e5,l[u]=g/n,l[s]=g/e,l[i]=g/t,l)[y]||g,$?D:O.a(D)},m.daysInMonth=function(){return this.endOf(f).$D},m.$locale=function(){return v[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),b=_.prototype;return w.prototype=b,[["$ms",r],["$s",i],["$m",s],["$H",u],["$W",a],["$M",f],["$y",c],["$D",d]].forEach((function(t){b[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),w.extend=function(t,e){return t.$i||(t(e,_,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=v[D],w.Ls=v,w.p={},w}));
  1760. },{}],6:[function(require,module,exports){
  1761. // Copyright Joyent, Inc. and other Node contributors.
  1762. //
  1763. // Permission is hereby granted, free of charge, to any person obtaining a
  1764. // copy of this software and associated documentation files (the
  1765. // "Software"), to deal in the Software without restriction, including
  1766. // without limitation the rights to use, copy, modify, merge, publish,
  1767. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1768. // persons to whom the Software is furnished to do so, subject to the
  1769. // following conditions:
  1770. //
  1771. // The above copyright notice and this permission notice shall be included
  1772. // in all copies or substantial portions of the Software.
  1773. //
  1774. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1775. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1776. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1777. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1778. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1779. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1780. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1781. function EventEmitter() {
  1782. this._events = this._events || {};
  1783. this._maxListeners = this._maxListeners || undefined;
  1784. }
  1785. module.exports = EventEmitter;
  1786. // Backwards-compat with node 0.10.x
  1787. EventEmitter.EventEmitter = EventEmitter;
  1788. EventEmitter.prototype._events = undefined;
  1789. EventEmitter.prototype._maxListeners = undefined;
  1790. // By default EventEmitters will print a warning if more than 10 listeners are
  1791. // added to it. This is a useful default which helps finding memory leaks.
  1792. EventEmitter.defaultMaxListeners = 10;
  1793. // Obviously not all Emitters should be limited to 10. This function allows
  1794. // that to be increased. Set to zero for unlimited.
  1795. EventEmitter.prototype.setMaxListeners = function(n) {
  1796. if (!isNumber(n) || n < 0 || isNaN(n))
  1797. throw TypeError('n must be a positive number');
  1798. this._maxListeners = n;
  1799. return this;
  1800. };
  1801. EventEmitter.prototype.emit = function(type) {
  1802. var er, handler, len, args, i, listeners;
  1803. if (!this._events)
  1804. this._events = {};
  1805. // If there is no 'error' event listener then throw.
  1806. if (type === 'error') {
  1807. if (!this._events.error ||
  1808. (isObject(this._events.error) && !this._events.error.length)) {
  1809. er = arguments[1];
  1810. if (er instanceof Error) {
  1811. throw er; // Unhandled 'error' event
  1812. } else {
  1813. // At least give some kind of context to the user
  1814. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1815. err.context = er;
  1816. throw err;
  1817. }
  1818. }
  1819. }
  1820. handler = this._events[type];
  1821. if (isUndefined(handler))
  1822. return false;
  1823. if (isFunction(handler)) {
  1824. switch (arguments.length) {
  1825. // fast cases
  1826. case 1:
  1827. handler.call(this);
  1828. break;
  1829. case 2:
  1830. handler.call(this, arguments[1]);
  1831. break;
  1832. case 3:
  1833. handler.call(this, arguments[1], arguments[2]);
  1834. break;
  1835. // slower
  1836. default:
  1837. args = Array.prototype.slice.call(arguments, 1);
  1838. handler.apply(this, args);
  1839. }
  1840. } else if (isObject(handler)) {
  1841. args = Array.prototype.slice.call(arguments, 1);
  1842. listeners = handler.slice();
  1843. len = listeners.length;
  1844. for (i = 0; i < len; i++)
  1845. listeners[i].apply(this, args);
  1846. }
  1847. return true;
  1848. };
  1849. EventEmitter.prototype.addListener = function(type, listener) {
  1850. var m;
  1851. if (!isFunction(listener))
  1852. throw TypeError('listener must be a function');
  1853. if (!this._events)
  1854. this._events = {};
  1855. // To avoid recursion in the case that type === "newListener"! Before
  1856. // adding it to the listeners, first emit "newListener".
  1857. if (this._events.newListener)
  1858. this.emit('newListener', type,
  1859. isFunction(listener.listener) ?
  1860. listener.listener : listener);
  1861. if (!this._events[type])
  1862. // Optimize the case of one listener. Don't need the extra array object.
  1863. this._events[type] = listener;
  1864. else if (isObject(this._events[type]))
  1865. // If we've already got an array, just append.
  1866. this._events[type].push(listener);
  1867. else
  1868. // Adding the second element, need to change to array.
  1869. this._events[type] = [this._events[type], listener];
  1870. // Check for listener leak
  1871. if (isObject(this._events[type]) && !this._events[type].warned) {
  1872. if (!isUndefined(this._maxListeners)) {
  1873. m = this._maxListeners;
  1874. } else {
  1875. m = EventEmitter.defaultMaxListeners;
  1876. }
  1877. if (m && m > 0 && this._events[type].length > m) {
  1878. this._events[type].warned = true;
  1879. console.error('(node) warning: possible EventEmitter memory ' +
  1880. 'leak detected. %d listeners added. ' +
  1881. 'Use emitter.setMaxListeners() to increase limit.',
  1882. this._events[type].length);
  1883. if (typeof console.trace === 'function') {
  1884. // not supported in IE 10
  1885. console.trace();
  1886. }
  1887. }
  1888. }
  1889. return this;
  1890. };
  1891. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1892. EventEmitter.prototype.once = function(type, listener) {
  1893. if (!isFunction(listener))
  1894. throw TypeError('listener must be a function');
  1895. var fired = false;
  1896. function g() {
  1897. this.removeListener(type, g);
  1898. if (!fired) {
  1899. fired = true;
  1900. listener.apply(this, arguments);
  1901. }
  1902. }
  1903. g.listener = listener;
  1904. this.on(type, g);
  1905. return this;
  1906. };
  1907. // emits a 'removeListener' event iff the listener was removed
  1908. EventEmitter.prototype.removeListener = function(type, listener) {
  1909. var list, position, length, i;
  1910. if (!isFunction(listener))
  1911. throw TypeError('listener must be a function');
  1912. if (!this._events || !this._events[type])
  1913. return this;
  1914. list = this._events[type];
  1915. length = list.length;
  1916. position = -1;
  1917. if (list === listener ||
  1918. (isFunction(list.listener) && list.listener === listener)) {
  1919. delete this._events[type];
  1920. if (this._events.removeListener)
  1921. this.emit('removeListener', type, listener);
  1922. } else if (isObject(list)) {
  1923. for (i = length; i-- > 0;) {
  1924. if (list[i] === listener ||
  1925. (list[i].listener && list[i].listener === listener)) {
  1926. position = i;
  1927. break;
  1928. }
  1929. }
  1930. if (position < 0)
  1931. return this;
  1932. if (list.length === 1) {
  1933. list.length = 0;
  1934. delete this._events[type];
  1935. } else {
  1936. list.splice(position, 1);
  1937. }
  1938. if (this._events.removeListener)
  1939. this.emit('removeListener', type, listener);
  1940. }
  1941. return this;
  1942. };
  1943. EventEmitter.prototype.removeAllListeners = function(type) {
  1944. var key, listeners;
  1945. if (!this._events)
  1946. return this;
  1947. // not listening for removeListener, no need to emit
  1948. if (!this._events.removeListener) {
  1949. if (arguments.length === 0)
  1950. this._events = {};
  1951. else if (this._events[type])
  1952. delete this._events[type];
  1953. return this;
  1954. }
  1955. // emit removeListener for all listeners on all events
  1956. if (arguments.length === 0) {
  1957. for (key in this._events) {
  1958. if (key === 'removeListener') continue;
  1959. this.removeAllListeners(key);
  1960. }
  1961. this.removeAllListeners('removeListener');
  1962. this._events = {};
  1963. return this;
  1964. }
  1965. listeners = this._events[type];
  1966. if (isFunction(listeners)) {
  1967. this.removeListener(type, listeners);
  1968. } else if (listeners) {
  1969. // LIFO order
  1970. while (listeners.length)
  1971. this.removeListener(type, listeners[listeners.length - 1]);
  1972. }
  1973. delete this._events[type];
  1974. return this;
  1975. };
  1976. EventEmitter.prototype.listeners = function(type) {
  1977. var ret;
  1978. if (!this._events || !this._events[type])
  1979. ret = [];
  1980. else if (isFunction(this._events[type]))
  1981. ret = [this._events[type]];
  1982. else
  1983. ret = this._events[type].slice();
  1984. return ret;
  1985. };
  1986. EventEmitter.prototype.listenerCount = function(type) {
  1987. if (this._events) {
  1988. var evlistener = this._events[type];
  1989. if (isFunction(evlistener))
  1990. return 1;
  1991. else if (evlistener)
  1992. return evlistener.length;
  1993. }
  1994. return 0;
  1995. };
  1996. EventEmitter.listenerCount = function(emitter, type) {
  1997. return emitter.listenerCount(type);
  1998. };
  1999. function isFunction(arg) {
  2000. return typeof arg === 'function';
  2001. }
  2002. function isNumber(arg) {
  2003. return typeof arg === 'number';
  2004. }
  2005. function isObject(arg) {
  2006. return typeof arg === 'object' && arg !== null;
  2007. }
  2008. function isUndefined(arg) {
  2009. return arg === void 0;
  2010. }
  2011. },{}],7:[function(require,module,exports){
  2012. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  2013. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2014. var e, m
  2015. var eLen = (nBytes * 8) - mLen - 1
  2016. var eMax = (1 << eLen) - 1
  2017. var eBias = eMax >> 1
  2018. var nBits = -7
  2019. var i = isLE ? (nBytes - 1) : 0
  2020. var d = isLE ? -1 : 1
  2021. var s = buffer[offset + i]
  2022. i += d
  2023. e = s & ((1 << (-nBits)) - 1)
  2024. s >>= (-nBits)
  2025. nBits += eLen
  2026. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2027. m = e & ((1 << (-nBits)) - 1)
  2028. e >>= (-nBits)
  2029. nBits += mLen
  2030. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2031. if (e === 0) {
  2032. e = 1 - eBias
  2033. } else if (e === eMax) {
  2034. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2035. } else {
  2036. m = m + Math.pow(2, mLen)
  2037. e = e - eBias
  2038. }
  2039. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2040. }
  2041. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2042. var e, m, c
  2043. var eLen = (nBytes * 8) - mLen - 1
  2044. var eMax = (1 << eLen) - 1
  2045. var eBias = eMax >> 1
  2046. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2047. var i = isLE ? 0 : (nBytes - 1)
  2048. var d = isLE ? 1 : -1
  2049. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2050. value = Math.abs(value)
  2051. if (isNaN(value) || value === Infinity) {
  2052. m = isNaN(value) ? 1 : 0
  2053. e = eMax
  2054. } else {
  2055. e = Math.floor(Math.log(value) / Math.LN2)
  2056. if (value * (c = Math.pow(2, -e)) < 1) {
  2057. e--
  2058. c *= 2
  2059. }
  2060. if (e + eBias >= 1) {
  2061. value += rt / c
  2062. } else {
  2063. value += rt * Math.pow(2, 1 - eBias)
  2064. }
  2065. if (value * c >= 2) {
  2066. e++
  2067. c /= 2
  2068. }
  2069. if (e + eBias >= eMax) {
  2070. m = 0
  2071. e = eMax
  2072. } else if (e + eBias >= 1) {
  2073. m = ((value * c) - 1) * Math.pow(2, mLen)
  2074. e = e + eBias
  2075. } else {
  2076. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2077. e = 0
  2078. }
  2079. }
  2080. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2081. e = (e << mLen) | m
  2082. eLen += mLen
  2083. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2084. buffer[offset + i - d] |= s * 128
  2085. }
  2086. },{}],8:[function(require,module,exports){
  2087. (function (global){
  2088. 'use strict';
  2089. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  2090. var scheduleDrain;
  2091. {
  2092. if (Mutation) {
  2093. var called = 0;
  2094. var observer = new Mutation(nextTick);
  2095. var element = global.document.createTextNode('');
  2096. observer.observe(element, {
  2097. characterData: true
  2098. });
  2099. scheduleDrain = function () {
  2100. element.data = (called = ++called % 2);
  2101. };
  2102. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  2103. var channel = new global.MessageChannel();
  2104. channel.port1.onmessage = nextTick;
  2105. scheduleDrain = function () {
  2106. channel.port2.postMessage(0);
  2107. };
  2108. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  2109. scheduleDrain = function () {
  2110. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  2111. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  2112. var scriptEl = global.document.createElement('script');
  2113. scriptEl.onreadystatechange = function () {
  2114. nextTick();
  2115. scriptEl.onreadystatechange = null;
  2116. scriptEl.parentNode.removeChild(scriptEl);
  2117. scriptEl = null;
  2118. };
  2119. global.document.documentElement.appendChild(scriptEl);
  2120. };
  2121. } else {
  2122. scheduleDrain = function () {
  2123. setTimeout(nextTick, 0);
  2124. };
  2125. }
  2126. }
  2127. var draining;
  2128. var queue = [];
  2129. //named nextTick for less confusing stack traces
  2130. function nextTick() {
  2131. draining = true;
  2132. var i, oldQueue;
  2133. var len = queue.length;
  2134. while (len) {
  2135. oldQueue = queue;
  2136. queue = [];
  2137. i = -1;
  2138. while (++i < len) {
  2139. oldQueue[i]();
  2140. }
  2141. len = queue.length;
  2142. }
  2143. draining = false;
  2144. }
  2145. module.exports = immediate;
  2146. function immediate(task) {
  2147. if (queue.push(task) === 1 && !draining) {
  2148. scheduleDrain();
  2149. }
  2150. }
  2151. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2152. },{}],9:[function(require,module,exports){
  2153. if (typeof Object.create === 'function') {
  2154. // implementation from standard node.js 'util' module
  2155. module.exports = function inherits(ctor, superCtor) {
  2156. if (superCtor) {
  2157. ctor.super_ = superCtor
  2158. ctor.prototype = Object.create(superCtor.prototype, {
  2159. constructor: {
  2160. value: ctor,
  2161. enumerable: false,
  2162. writable: true,
  2163. configurable: true
  2164. }
  2165. })
  2166. }
  2167. };
  2168. } else {
  2169. // old school shim for old browsers
  2170. module.exports = function inherits(ctor, superCtor) {
  2171. if (superCtor) {
  2172. ctor.super_ = superCtor
  2173. var TempCtor = function () {}
  2174. TempCtor.prototype = superCtor.prototype
  2175. ctor.prototype = new TempCtor()
  2176. ctor.prototype.constructor = ctor
  2177. }
  2178. }
  2179. }
  2180. },{}],10:[function(require,module,exports){
  2181. /*!
  2182. * Determine if an object is a Buffer
  2183. *
  2184. * @author Feross Aboukhadijeh <https://feross.org>
  2185. * @license MIT
  2186. */
  2187. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2188. // Object.prototype.constructor. Remove this eventually
  2189. module.exports = function (obj) {
  2190. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2191. }
  2192. function isBuffer (obj) {
  2193. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2194. }
  2195. // For Node v0.10 support. Remove this eventually.
  2196. function isSlowBuffer (obj) {
  2197. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2198. }
  2199. },{}],11:[function(require,module,exports){
  2200. var toString = {}.toString;
  2201. module.exports = Array.isArray || function (arr) {
  2202. return toString.call(arr) == '[object Array]';
  2203. };
  2204. },{}],12:[function(require,module,exports){
  2205. 'use strict';
  2206. var utils = require('./utils');
  2207. var support = require('./support');
  2208. // private property
  2209. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2210. // public method for encoding
  2211. exports.encode = function(input) {
  2212. var output = [];
  2213. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  2214. var i = 0, len = input.length, remainingBytes = len;
  2215. var isArray = utils.getTypeOf(input) !== "string";
  2216. while (i < input.length) {
  2217. remainingBytes = len - i;
  2218. if (!isArray) {
  2219. chr1 = input.charCodeAt(i++);
  2220. chr2 = i < len ? input.charCodeAt(i++) : 0;
  2221. chr3 = i < len ? input.charCodeAt(i++) : 0;
  2222. } else {
  2223. chr1 = input[i++];
  2224. chr2 = i < len ? input[i++] : 0;
  2225. chr3 = i < len ? input[i++] : 0;
  2226. }
  2227. enc1 = chr1 >> 2;
  2228. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2229. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  2230. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  2231. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  2232. }
  2233. return output.join("");
  2234. };
  2235. // public method for decoding
  2236. exports.decode = function(input) {
  2237. var chr1, chr2, chr3;
  2238. var enc1, enc2, enc3, enc4;
  2239. var i = 0, resultIndex = 0;
  2240. var dataUrlPrefix = "data:";
  2241. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  2242. // This is a common error: people give a data url
  2243. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  2244. // wonders why things don't work.
  2245. // We can detect that the string input looks like a data url but we
  2246. // *can't* be sure it is one: removing everything up to the comma would
  2247. // be too dangerous.
  2248. throw new Error("Invalid base64 input, it looks like a data url.");
  2249. }
  2250. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  2251. var totalLength = input.length * 3 / 4;
  2252. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  2253. totalLength--;
  2254. }
  2255. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  2256. totalLength--;
  2257. }
  2258. if (totalLength % 1 !== 0) {
  2259. // totalLength is not an integer, the length does not match a valid
  2260. // base64 content. That can happen if:
  2261. // - the input is not a base64 content
  2262. // - the input is *almost* a base64 content, with a extra chars at the
  2263. // beginning or at the end
  2264. // - the input uses a base64 variant (base64url for example)
  2265. throw new Error("Invalid base64 input, bad content length.");
  2266. }
  2267. var output;
  2268. if (support.uint8array) {
  2269. output = new Uint8Array(totalLength|0);
  2270. } else {
  2271. output = new Array(totalLength|0);
  2272. }
  2273. while (i < input.length) {
  2274. enc1 = _keyStr.indexOf(input.charAt(i++));
  2275. enc2 = _keyStr.indexOf(input.charAt(i++));
  2276. enc3 = _keyStr.indexOf(input.charAt(i++));
  2277. enc4 = _keyStr.indexOf(input.charAt(i++));
  2278. chr1 = (enc1 << 2) | (enc2 >> 4);
  2279. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  2280. chr3 = ((enc3 & 3) << 6) | enc4;
  2281. output[resultIndex++] = chr1;
  2282. if (enc3 !== 64) {
  2283. output[resultIndex++] = chr2;
  2284. }
  2285. if (enc4 !== 64) {
  2286. output[resultIndex++] = chr3;
  2287. }
  2288. }
  2289. return output;
  2290. };
  2291. },{"./support":41,"./utils":43}],13:[function(require,module,exports){
  2292. 'use strict';
  2293. var external = require("./external");
  2294. var DataWorker = require('./stream/DataWorker');
  2295. var DataLengthProbe = require('./stream/DataLengthProbe');
  2296. var Crc32Probe = require('./stream/Crc32Probe');
  2297. var DataLengthProbe = require('./stream/DataLengthProbe');
  2298. /**
  2299. * Represent a compressed object, with everything needed to decompress it.
  2300. * @constructor
  2301. * @param {number} compressedSize the size of the data compressed.
  2302. * @param {number} uncompressedSize the size of the data after decompression.
  2303. * @param {number} crc32 the crc32 of the decompressed file.
  2304. * @param {object} compression the type of compression, see lib/compressions.js.
  2305. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  2306. */
  2307. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  2308. this.compressedSize = compressedSize;
  2309. this.uncompressedSize = uncompressedSize;
  2310. this.crc32 = crc32;
  2311. this.compression = compression;
  2312. this.compressedContent = data;
  2313. }
  2314. CompressedObject.prototype = {
  2315. /**
  2316. * Create a worker to get the uncompressed content.
  2317. * @return {GenericWorker} the worker.
  2318. */
  2319. getContentWorker : function () {
  2320. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  2321. .pipe(this.compression.uncompressWorker())
  2322. .pipe(new DataLengthProbe("data_length"));
  2323. var that = this;
  2324. worker.on("end", function () {
  2325. if(this.streamInfo['data_length'] !== that.uncompressedSize) {
  2326. throw new Error("Bug : uncompressed data size mismatch");
  2327. }
  2328. });
  2329. return worker;
  2330. },
  2331. /**
  2332. * Create a worker to get the compressed content.
  2333. * @return {GenericWorker} the worker.
  2334. */
  2335. getCompressedWorker : function () {
  2336. return new DataWorker(external.Promise.resolve(this.compressedContent))
  2337. .withStreamInfo("compressedSize", this.compressedSize)
  2338. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  2339. .withStreamInfo("crc32", this.crc32)
  2340. .withStreamInfo("compression", this.compression)
  2341. ;
  2342. }
  2343. };
  2344. /**
  2345. * Chain the given worker with other workers to compress the content with the
  2346. * given compression.
  2347. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  2348. * @param {Object} compression the compression object.
  2349. * @param {Object} compressionOptions the options to use when compressing.
  2350. * @return {GenericWorker} the new worker compressing the content.
  2351. */
  2352. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  2353. return uncompressedWorker
  2354. .pipe(new Crc32Probe())
  2355. .pipe(new DataLengthProbe("uncompressedSize"))
  2356. .pipe(compression.compressWorker(compressionOptions))
  2357. .pipe(new DataLengthProbe("compressedSize"))
  2358. .withStreamInfo("compression", compression);
  2359. };
  2360. module.exports = CompressedObject;
  2361. },{"./external":17,"./stream/Crc32Probe":36,"./stream/DataLengthProbe":37,"./stream/DataWorker":38}],14:[function(require,module,exports){
  2362. 'use strict';
  2363. var GenericWorker = require("./stream/GenericWorker");
  2364. exports.STORE = {
  2365. magic: "\x00\x00",
  2366. compressWorker : function (compressionOptions) {
  2367. return new GenericWorker("STORE compression");
  2368. },
  2369. uncompressWorker : function () {
  2370. return new GenericWorker("STORE decompression");
  2371. }
  2372. };
  2373. exports.DEFLATE = require('./flate');
  2374. },{"./flate":18,"./stream/GenericWorker":39}],15:[function(require,module,exports){
  2375. 'use strict';
  2376. var utils = require('./utils');
  2377. /**
  2378. * The following functions come from pako, from pako/lib/zlib/crc32.js
  2379. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2380. */
  2381. // Use ordinary array, since untyped makes no boost here
  2382. function makeTable() {
  2383. var c, table = [];
  2384. for(var n =0; n < 256; n++){
  2385. c = n;
  2386. for(var k =0; k < 8; k++){
  2387. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  2388. }
  2389. table[n] = c;
  2390. }
  2391. return table;
  2392. }
  2393. // Create table on load. Just 255 signed longs. Not a problem.
  2394. var crcTable = makeTable();
  2395. function crc32(crc, buf, len, pos) {
  2396. var t = crcTable, end = pos + len;
  2397. crc = crc ^ (-1);
  2398. for (var i = pos; i < end; i++ ) {
  2399. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  2400. }
  2401. return (crc ^ (-1)); // >>> 0;
  2402. }
  2403. // That's all for the pako functions.
  2404. /**
  2405. * Compute the crc32 of a string.
  2406. * This is almost the same as the function crc32, but for strings. Using the
  2407. * same function for the two use cases leads to horrible performances.
  2408. * @param {Number} crc the starting value of the crc.
  2409. * @param {String} str the string to use.
  2410. * @param {Number} len the length of the string.
  2411. * @param {Number} pos the starting position for the crc32 computation.
  2412. * @return {Number} the computed crc32.
  2413. */
  2414. function crc32str(crc, str, len, pos) {
  2415. var t = crcTable, end = pos + len;
  2416. crc = crc ^ (-1);
  2417. for (var i = pos; i < end; i++ ) {
  2418. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  2419. }
  2420. return (crc ^ (-1)); // >>> 0;
  2421. }
  2422. module.exports = function crc32wrapper(input, crc) {
  2423. if (typeof input === "undefined" || !input.length) {
  2424. return 0;
  2425. }
  2426. var isArray = utils.getTypeOf(input) !== "string";
  2427. if(isArray) {
  2428. return crc32(crc|0, input, input.length, 0);
  2429. } else {
  2430. return crc32str(crc|0, input, input.length, 0);
  2431. }
  2432. };
  2433. },{"./utils":43}],16:[function(require,module,exports){
  2434. 'use strict';
  2435. exports.base64 = false;
  2436. exports.binary = false;
  2437. exports.dir = false;
  2438. exports.createFolders = true;
  2439. exports.date = null;
  2440. exports.compression = null;
  2441. exports.compressionOptions = null;
  2442. exports.comment = null;
  2443. exports.unixPermissions = null;
  2444. exports.dosPermissions = null;
  2445. },{}],17:[function(require,module,exports){
  2446. /* global Promise */
  2447. 'use strict';
  2448. // load the global object first:
  2449. // - it should be better integrated in the system (unhandledRejection in node)
  2450. // - the environment may have a custom Promise implementation (see zone.js)
  2451. var ES6Promise = null;
  2452. if (typeof Promise !== "undefined") {
  2453. ES6Promise = Promise;
  2454. } else {
  2455. ES6Promise = require("lie");
  2456. }
  2457. /**
  2458. * Let the user use/change some implementations.
  2459. */
  2460. module.exports = {
  2461. Promise: ES6Promise
  2462. };
  2463. },{"lie":47}],18:[function(require,module,exports){
  2464. 'use strict';
  2465. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  2466. var pako = require("pako");
  2467. var utils = require("./utils");
  2468. var GenericWorker = require("./stream/GenericWorker");
  2469. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  2470. exports.magic = "\x08\x00";
  2471. /**
  2472. * Create a worker that uses pako to inflate/deflate.
  2473. * @constructor
  2474. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  2475. * @param {Object} options the options to use when (de)compressing.
  2476. */
  2477. function FlateWorker(action, options) {
  2478. GenericWorker.call(this, "FlateWorker/" + action);
  2479. this._pako = null;
  2480. this._pakoAction = action;
  2481. this._pakoOptions = options;
  2482. // the `meta` object from the last chunk received
  2483. // this allow this worker to pass around metadata
  2484. this.meta = {};
  2485. }
  2486. utils.inherits(FlateWorker, GenericWorker);
  2487. /**
  2488. * @see GenericWorker.processChunk
  2489. */
  2490. FlateWorker.prototype.processChunk = function (chunk) {
  2491. this.meta = chunk.meta;
  2492. if (this._pako === null) {
  2493. this._createPako();
  2494. }
  2495. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  2496. };
  2497. /**
  2498. * @see GenericWorker.flush
  2499. */
  2500. FlateWorker.prototype.flush = function () {
  2501. GenericWorker.prototype.flush.call(this);
  2502. if (this._pako === null) {
  2503. this._createPako();
  2504. }
  2505. this._pako.push([], true);
  2506. };
  2507. /**
  2508. * @see GenericWorker.cleanUp
  2509. */
  2510. FlateWorker.prototype.cleanUp = function () {
  2511. GenericWorker.prototype.cleanUp.call(this);
  2512. this._pako = null;
  2513. };
  2514. /**
  2515. * Create the _pako object.
  2516. * TODO: lazy-loading this object isn't the best solution but it's the
  2517. * quickest. The best solution is to lazy-load the worker list. See also the
  2518. * issue #446.
  2519. */
  2520. FlateWorker.prototype._createPako = function () {
  2521. this._pako = new pako[this._pakoAction]({
  2522. raw: true,
  2523. level: this._pakoOptions.level || -1 // default compression
  2524. });
  2525. var self = this;
  2526. this._pako.onData = function(data) {
  2527. self.push({
  2528. data : data,
  2529. meta : self.meta
  2530. });
  2531. };
  2532. };
  2533. exports.compressWorker = function (compressionOptions) {
  2534. return new FlateWorker("Deflate", compressionOptions);
  2535. };
  2536. exports.uncompressWorker = function () {
  2537. return new FlateWorker("Inflate", {});
  2538. };
  2539. },{"./stream/GenericWorker":39,"./utils":43,"pako":48}],19:[function(require,module,exports){
  2540. 'use strict';
  2541. var utils = require('../utils');
  2542. var GenericWorker = require('../stream/GenericWorker');
  2543. var utf8 = require('../utf8');
  2544. var crc32 = require('../crc32');
  2545. var signature = require('../signature');
  2546. /**
  2547. * Transform an integer into a string in hexadecimal.
  2548. * @private
  2549. * @param {number} dec the number to convert.
  2550. * @param {number} bytes the number of bytes to generate.
  2551. * @returns {string} the result.
  2552. */
  2553. var decToHex = function(dec, bytes) {
  2554. var hex = "", i;
  2555. for (i = 0; i < bytes; i++) {
  2556. hex += String.fromCharCode(dec & 0xff);
  2557. dec = dec >>> 8;
  2558. }
  2559. return hex;
  2560. };
  2561. /**
  2562. * Generate the UNIX part of the external file attributes.
  2563. * @param {Object} unixPermissions the unix permissions or null.
  2564. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  2565. * @return {Number} a 32 bit integer.
  2566. *
  2567. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  2568. *
  2569. * TTTTsstrwxrwxrwx0000000000ADVSHR
  2570. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  2571. * ^^^_________________________ setuid, setgid, sticky
  2572. * ^^^^^^^^^________________ permissions
  2573. * ^^^^^^^^^^______ not used ?
  2574. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  2575. */
  2576. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  2577. var result = unixPermissions;
  2578. if (!unixPermissions) {
  2579. // I can't use octal values in strict mode, hence the hexa.
  2580. // 040775 => 0x41fd
  2581. // 0100664 => 0x81b4
  2582. result = isDir ? 0x41fd : 0x81b4;
  2583. }
  2584. return (result & 0xFFFF) << 16;
  2585. };
  2586. /**
  2587. * Generate the DOS part of the external file attributes.
  2588. * @param {Object} dosPermissions the dos permissions or null.
  2589. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  2590. * @return {Number} a 32 bit integer.
  2591. *
  2592. * Bit 0 Read-Only
  2593. * Bit 1 Hidden
  2594. * Bit 2 System
  2595. * Bit 3 Volume Label
  2596. * Bit 4 Directory
  2597. * Bit 5 Archive
  2598. */
  2599. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  2600. // the dir flag is already set for compatibility
  2601. return (dosPermissions || 0) & 0x3F;
  2602. };
  2603. /**
  2604. * Generate the various parts used in the construction of the final zip file.
  2605. * @param {Object} streamInfo the hash with information about the compressed file.
  2606. * @param {Boolean} streamedContent is the content streamed ?
  2607. * @param {Boolean} streamingEnded is the stream finished ?
  2608. * @param {number} offset the current offset from the start of the zip file.
  2609. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  2610. * @param {Function} encodeFileName the function to encode the file name / comment.
  2611. * @return {Object} the zip parts.
  2612. */
  2613. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  2614. var file = streamInfo['file'],
  2615. compression = streamInfo['compression'],
  2616. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  2617. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  2618. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  2619. comment = file.comment,
  2620. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  2621. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  2622. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  2623. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  2624. dosTime,
  2625. dosDate,
  2626. extraFields = "",
  2627. unicodePathExtraField = "",
  2628. unicodeCommentExtraField = "",
  2629. dir = file.dir,
  2630. date = file.date;
  2631. var dataInfo = {
  2632. crc32 : 0,
  2633. compressedSize : 0,
  2634. uncompressedSize : 0
  2635. };
  2636. // if the content is streamed, the sizes/crc32 are only available AFTER
  2637. // the end of the stream.
  2638. if (!streamedContent || streamingEnded) {
  2639. dataInfo.crc32 = streamInfo['crc32'];
  2640. dataInfo.compressedSize = streamInfo['compressedSize'];
  2641. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  2642. }
  2643. var bitflag = 0;
  2644. if (streamedContent) {
  2645. // Bit 3: the sizes/crc32 are set to zero in the local header.
  2646. // The correct values are put in the data descriptor immediately
  2647. // following the compressed data.
  2648. bitflag |= 0x0008;
  2649. }
  2650. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  2651. // Bit 11: Language encoding flag (EFS).
  2652. bitflag |= 0x0800;
  2653. }
  2654. var extFileAttr = 0;
  2655. var versionMadeBy = 0;
  2656. if (dir) {
  2657. // dos or unix, we set the dos dir flag
  2658. extFileAttr |= 0x00010;
  2659. }
  2660. if(platform === "UNIX") {
  2661. versionMadeBy = 0x031E; // UNIX, version 3.0
  2662. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  2663. } else { // DOS or other, fallback to DOS
  2664. versionMadeBy = 0x0014; // DOS, version 2.0
  2665. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  2666. }
  2667. // date
  2668. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  2669. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  2670. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  2671. dosTime = date.getUTCHours();
  2672. dosTime = dosTime << 6;
  2673. dosTime = dosTime | date.getUTCMinutes();
  2674. dosTime = dosTime << 5;
  2675. dosTime = dosTime | date.getUTCSeconds() / 2;
  2676. dosDate = date.getUTCFullYear() - 1980;
  2677. dosDate = dosDate << 4;
  2678. dosDate = dosDate | (date.getUTCMonth() + 1);
  2679. dosDate = dosDate << 5;
  2680. dosDate = dosDate | date.getUTCDate();
  2681. if (useUTF8ForFileName) {
  2682. // set the unicode path extra field. unzip needs at least one extra
  2683. // field to correctly handle unicode path, so using the path is as good
  2684. // as any other information. This could improve the situation with
  2685. // other archive managers too.
  2686. // This field is usually used without the utf8 flag, with a non
  2687. // unicode path in the header (winrar, winzip). This helps (a bit)
  2688. // with the messy Windows' default compressed folders feature but
  2689. // breaks on p7zip which doesn't seek the unicode path extra field.
  2690. // So for now, UTF-8 everywhere !
  2691. unicodePathExtraField =
  2692. // Version
  2693. decToHex(1, 1) +
  2694. // NameCRC32
  2695. decToHex(crc32(encodedFileName), 4) +
  2696. // UnicodeName
  2697. utfEncodedFileName;
  2698. extraFields +=
  2699. // Info-ZIP Unicode Path Extra Field
  2700. "\x75\x70" +
  2701. // size
  2702. decToHex(unicodePathExtraField.length, 2) +
  2703. // content
  2704. unicodePathExtraField;
  2705. }
  2706. if(useUTF8ForComment) {
  2707. unicodeCommentExtraField =
  2708. // Version
  2709. decToHex(1, 1) +
  2710. // CommentCRC32
  2711. decToHex(crc32(encodedComment), 4) +
  2712. // UnicodeName
  2713. utfEncodedComment;
  2714. extraFields +=
  2715. // Info-ZIP Unicode Path Extra Field
  2716. "\x75\x63" +
  2717. // size
  2718. decToHex(unicodeCommentExtraField.length, 2) +
  2719. // content
  2720. unicodeCommentExtraField;
  2721. }
  2722. var header = "";
  2723. // version needed to extract
  2724. header += "\x0A\x00";
  2725. // general purpose bit flag
  2726. header += decToHex(bitflag, 2);
  2727. // compression method
  2728. header += compression.magic;
  2729. // last mod file time
  2730. header += decToHex(dosTime, 2);
  2731. // last mod file date
  2732. header += decToHex(dosDate, 2);
  2733. // crc-32
  2734. header += decToHex(dataInfo.crc32, 4);
  2735. // compressed size
  2736. header += decToHex(dataInfo.compressedSize, 4);
  2737. // uncompressed size
  2738. header += decToHex(dataInfo.uncompressedSize, 4);
  2739. // file name length
  2740. header += decToHex(encodedFileName.length, 2);
  2741. // extra field length
  2742. header += decToHex(extraFields.length, 2);
  2743. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  2744. var dirRecord = signature.CENTRAL_FILE_HEADER +
  2745. // version made by (00: DOS)
  2746. decToHex(versionMadeBy, 2) +
  2747. // file header (common to file and central directory)
  2748. header +
  2749. // file comment length
  2750. decToHex(encodedComment.length, 2) +
  2751. // disk number start
  2752. "\x00\x00" +
  2753. // internal file attributes TODO
  2754. "\x00\x00" +
  2755. // external file attributes
  2756. decToHex(extFileAttr, 4) +
  2757. // relative offset of local header
  2758. decToHex(offset, 4) +
  2759. // file name
  2760. encodedFileName +
  2761. // extra field
  2762. extraFields +
  2763. // file comment
  2764. encodedComment;
  2765. return {
  2766. fileRecord: fileRecord,
  2767. dirRecord: dirRecord
  2768. };
  2769. };
  2770. /**
  2771. * Generate the EOCD record.
  2772. * @param {Number} entriesCount the number of entries in the zip file.
  2773. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  2774. * @param {Number} localDirLength the length (in bytes) of the local dir.
  2775. * @param {String} comment the zip file comment as a binary string.
  2776. * @param {Function} encodeFileName the function to encode the comment.
  2777. * @return {String} the EOCD record.
  2778. */
  2779. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  2780. var dirEnd = "";
  2781. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  2782. // end of central dir signature
  2783. dirEnd = signature.CENTRAL_DIRECTORY_END +
  2784. // number of this disk
  2785. "\x00\x00" +
  2786. // number of the disk with the start of the central directory
  2787. "\x00\x00" +
  2788. // total number of entries in the central directory on this disk
  2789. decToHex(entriesCount, 2) +
  2790. // total number of entries in the central directory
  2791. decToHex(entriesCount, 2) +
  2792. // size of the central directory 4 bytes
  2793. decToHex(centralDirLength, 4) +
  2794. // offset of start of central directory with respect to the starting disk number
  2795. decToHex(localDirLength, 4) +
  2796. // .ZIP file comment length
  2797. decToHex(encodedComment.length, 2) +
  2798. // .ZIP file comment
  2799. encodedComment;
  2800. return dirEnd;
  2801. };
  2802. /**
  2803. * Generate data descriptors for a file entry.
  2804. * @param {Object} streamInfo the hash generated by a worker, containing information
  2805. * on the file entry.
  2806. * @return {String} the data descriptors.
  2807. */
  2808. var generateDataDescriptors = function (streamInfo) {
  2809. var descriptor = "";
  2810. descriptor = signature.DATA_DESCRIPTOR +
  2811. // crc-32 4 bytes
  2812. decToHex(streamInfo['crc32'], 4) +
  2813. // compressed size 4 bytes
  2814. decToHex(streamInfo['compressedSize'], 4) +
  2815. // uncompressed size 4 bytes
  2816. decToHex(streamInfo['uncompressedSize'], 4);
  2817. return descriptor;
  2818. };
  2819. /**
  2820. * A worker to concatenate other workers to create a zip file.
  2821. * @param {Boolean} streamFiles `true` to stream the content of the files,
  2822. * `false` to accumulate it.
  2823. * @param {String} comment the comment to use.
  2824. * @param {String} platform the platform to use, "UNIX" or "DOS".
  2825. * @param {Function} encodeFileName the function to encode file names and comments.
  2826. */
  2827. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  2828. GenericWorker.call(this, "ZipFileWorker");
  2829. // The number of bytes written so far. This doesn't count accumulated chunks.
  2830. this.bytesWritten = 0;
  2831. // The comment of the zip file
  2832. this.zipComment = comment;
  2833. // The platform "generating" the zip file.
  2834. this.zipPlatform = platform;
  2835. // the function to encode file names and comments.
  2836. this.encodeFileName = encodeFileName;
  2837. // Should we stream the content of the files ?
  2838. this.streamFiles = streamFiles;
  2839. // If `streamFiles` is false, we will need to accumulate the content of the
  2840. // files to calculate sizes / crc32 (and write them *before* the content).
  2841. // This boolean indicates if we are accumulating chunks (it will change a lot
  2842. // during the lifetime of this worker).
  2843. this.accumulate = false;
  2844. // The buffer receiving chunks when accumulating content.
  2845. this.contentBuffer = [];
  2846. // The list of generated directory records.
  2847. this.dirRecords = [];
  2848. // The offset (in bytes) from the beginning of the zip file for the current source.
  2849. this.currentSourceOffset = 0;
  2850. // The total number of entries in this zip file.
  2851. this.entriesCount = 0;
  2852. // the name of the file currently being added, null when handling the end of the zip file.
  2853. // Used for the emitted metadata.
  2854. this.currentFile = null;
  2855. this._sources = [];
  2856. }
  2857. utils.inherits(ZipFileWorker, GenericWorker);
  2858. /**
  2859. * @see GenericWorker.push
  2860. */
  2861. ZipFileWorker.prototype.push = function (chunk) {
  2862. var currentFilePercent = chunk.meta.percent || 0;
  2863. var entriesCount = this.entriesCount;
  2864. var remainingFiles = this._sources.length;
  2865. if(this.accumulate) {
  2866. this.contentBuffer.push(chunk);
  2867. } else {
  2868. this.bytesWritten += chunk.data.length;
  2869. GenericWorker.prototype.push.call(this, {
  2870. data : chunk.data,
  2871. meta : {
  2872. currentFile : this.currentFile,
  2873. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  2874. }
  2875. });
  2876. }
  2877. };
  2878. /**
  2879. * The worker started a new source (an other worker).
  2880. * @param {Object} streamInfo the streamInfo object from the new source.
  2881. */
  2882. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  2883. this.currentSourceOffset = this.bytesWritten;
  2884. this.currentFile = streamInfo['file'].name;
  2885. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  2886. // don't stream folders (because they don't have any content)
  2887. if(streamedContent) {
  2888. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  2889. this.push({
  2890. data : record.fileRecord,
  2891. meta : {percent:0}
  2892. });
  2893. } else {
  2894. // we need to wait for the whole file before pushing anything
  2895. this.accumulate = true;
  2896. }
  2897. };
  2898. /**
  2899. * The worker finished a source (an other worker).
  2900. * @param {Object} streamInfo the streamInfo object from the finished source.
  2901. */
  2902. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  2903. this.accumulate = false;
  2904. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  2905. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  2906. this.dirRecords.push(record.dirRecord);
  2907. if(streamedContent) {
  2908. // after the streamed file, we put data descriptors
  2909. this.push({
  2910. data : generateDataDescriptors(streamInfo),
  2911. meta : {percent:100}
  2912. });
  2913. } else {
  2914. // the content wasn't streamed, we need to push everything now
  2915. // first the file record, then the content
  2916. this.push({
  2917. data : record.fileRecord,
  2918. meta : {percent:0}
  2919. });
  2920. while(this.contentBuffer.length) {
  2921. this.push(this.contentBuffer.shift());
  2922. }
  2923. }
  2924. this.currentFile = null;
  2925. };
  2926. /**
  2927. * @see GenericWorker.flush
  2928. */
  2929. ZipFileWorker.prototype.flush = function () {
  2930. var localDirLength = this.bytesWritten;
  2931. for(var i = 0; i < this.dirRecords.length; i++) {
  2932. this.push({
  2933. data : this.dirRecords[i],
  2934. meta : {percent:100}
  2935. });
  2936. }
  2937. var centralDirLength = this.bytesWritten - localDirLength;
  2938. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  2939. this.push({
  2940. data : dirEnd,
  2941. meta : {percent:100}
  2942. });
  2943. };
  2944. /**
  2945. * Prepare the next source to be read.
  2946. */
  2947. ZipFileWorker.prototype.prepareNextSource = function () {
  2948. this.previous = this._sources.shift();
  2949. this.openedSource(this.previous.streamInfo);
  2950. if (this.isPaused) {
  2951. this.previous.pause();
  2952. } else {
  2953. this.previous.resume();
  2954. }
  2955. };
  2956. /**
  2957. * @see GenericWorker.registerPrevious
  2958. */
  2959. ZipFileWorker.prototype.registerPrevious = function (previous) {
  2960. this._sources.push(previous);
  2961. var self = this;
  2962. previous.on('data', function (chunk) {
  2963. self.processChunk(chunk);
  2964. });
  2965. previous.on('end', function () {
  2966. self.closedSource(self.previous.streamInfo);
  2967. if(self._sources.length) {
  2968. self.prepareNextSource();
  2969. } else {
  2970. self.end();
  2971. }
  2972. });
  2973. previous.on('error', function (e) {
  2974. self.error(e);
  2975. });
  2976. return this;
  2977. };
  2978. /**
  2979. * @see GenericWorker.resume
  2980. */
  2981. ZipFileWorker.prototype.resume = function () {
  2982. if(!GenericWorker.prototype.resume.call(this)) {
  2983. return false;
  2984. }
  2985. if (!this.previous && this._sources.length) {
  2986. this.prepareNextSource();
  2987. return true;
  2988. }
  2989. if (!this.previous && !this._sources.length && !this.generatedError) {
  2990. this.end();
  2991. return true;
  2992. }
  2993. };
  2994. /**
  2995. * @see GenericWorker.error
  2996. */
  2997. ZipFileWorker.prototype.error = function (e) {
  2998. var sources = this._sources;
  2999. if(!GenericWorker.prototype.error.call(this, e)) {
  3000. return false;
  3001. }
  3002. for(var i = 0; i < sources.length; i++) {
  3003. try {
  3004. sources[i].error(e);
  3005. } catch(e) {
  3006. // the `error` exploded, nothing to do
  3007. }
  3008. }
  3009. return true;
  3010. };
  3011. /**
  3012. * @see GenericWorker.lock
  3013. */
  3014. ZipFileWorker.prototype.lock = function () {
  3015. GenericWorker.prototype.lock.call(this);
  3016. var sources = this._sources;
  3017. for(var i = 0; i < sources.length; i++) {
  3018. sources[i].lock();
  3019. }
  3020. };
  3021. module.exports = ZipFileWorker;
  3022. },{"../crc32":15,"../signature":34,"../stream/GenericWorker":39,"../utf8":42,"../utils":43}],20:[function(require,module,exports){
  3023. 'use strict';
  3024. var compressions = require('../compressions');
  3025. var ZipFileWorker = require('./ZipFileWorker');
  3026. /**
  3027. * Find the compression to use.
  3028. * @param {String} fileCompression the compression defined at the file level, if any.
  3029. * @param {String} zipCompression the compression defined at the load() level.
  3030. * @return {Object} the compression object to use.
  3031. */
  3032. var getCompression = function (fileCompression, zipCompression) {
  3033. var compressionName = fileCompression || zipCompression;
  3034. var compression = compressions[compressionName];
  3035. if (!compression) {
  3036. throw new Error(compressionName + " is not a valid compression method !");
  3037. }
  3038. return compression;
  3039. };
  3040. /**
  3041. * Create a worker to generate a zip file.
  3042. * @param {JSZip} zip the JSZip instance at the right root level.
  3043. * @param {Object} options to generate the zip file.
  3044. * @param {String} comment the comment to use.
  3045. */
  3046. exports.generateWorker = function (zip, options, comment) {
  3047. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  3048. var entriesCount = 0;
  3049. try {
  3050. zip.forEach(function (relativePath, file) {
  3051. entriesCount++;
  3052. var compression = getCompression(file.options.compression, options.compression);
  3053. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  3054. var dir = file.dir, date = file.date;
  3055. file._compressWorker(compression, compressionOptions)
  3056. .withStreamInfo("file", {
  3057. name : relativePath,
  3058. dir : dir,
  3059. date : date,
  3060. comment : file.comment || "",
  3061. unixPermissions : file.unixPermissions,
  3062. dosPermissions : file.dosPermissions
  3063. })
  3064. .pipe(zipFileWorker);
  3065. });
  3066. zipFileWorker.entriesCount = entriesCount;
  3067. } catch (e) {
  3068. zipFileWorker.error(e);
  3069. }
  3070. return zipFileWorker;
  3071. };
  3072. },{"../compressions":14,"./ZipFileWorker":19}],21:[function(require,module,exports){
  3073. 'use strict';
  3074. /**
  3075. * Representation a of zip file in js
  3076. * @constructor
  3077. */
  3078. function JSZip() {
  3079. // if this constructor is used without `new`, it adds `new` before itself:
  3080. if(!(this instanceof JSZip)) {
  3081. return new JSZip();
  3082. }
  3083. if(arguments.length) {
  3084. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  3085. }
  3086. // object containing the files :
  3087. // {
  3088. // "folder/" : {...},
  3089. // "folder/data.txt" : {...}
  3090. // }
  3091. this.files = {};
  3092. this.comment = null;
  3093. // Where we are in the hierarchy
  3094. this.root = "";
  3095. this.clone = function() {
  3096. var newObj = new JSZip();
  3097. for (var i in this) {
  3098. if (typeof this[i] !== "function") {
  3099. newObj[i] = this[i];
  3100. }
  3101. }
  3102. return newObj;
  3103. };
  3104. }
  3105. JSZip.prototype = require('./object');
  3106. JSZip.prototype.loadAsync = require('./load');
  3107. JSZip.support = require('./support');
  3108. JSZip.defaults = require('./defaults');
  3109. // TODO find a better way to handle this version,
  3110. // a require('package.json').version doesn't work with webpack, see #327
  3111. JSZip.version = "3.5.0";
  3112. JSZip.loadAsync = function (content, options) {
  3113. return new JSZip().loadAsync(content, options);
  3114. };
  3115. JSZip.external = require("./external");
  3116. module.exports = JSZip;
  3117. },{"./defaults":16,"./external":17,"./load":22,"./object":26,"./support":41}],22:[function(require,module,exports){
  3118. 'use strict';
  3119. var utils = require('./utils');
  3120. var external = require("./external");
  3121. var utf8 = require('./utf8');
  3122. var utils = require('./utils');
  3123. var ZipEntries = require('./zipEntries');
  3124. var Crc32Probe = require('./stream/Crc32Probe');
  3125. var nodejsUtils = require("./nodejsUtils");
  3126. /**
  3127. * Check the CRC32 of an entry.
  3128. * @param {ZipEntry} zipEntry the zip entry to check.
  3129. * @return {Promise} the result.
  3130. */
  3131. function checkEntryCRC32(zipEntry) {
  3132. return new external.Promise(function (resolve, reject) {
  3133. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  3134. worker.on("error", function (e) {
  3135. reject(e);
  3136. })
  3137. .on("end", function () {
  3138. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  3139. reject(new Error("Corrupted zip : CRC32 mismatch"));
  3140. } else {
  3141. resolve();
  3142. }
  3143. })
  3144. .resume();
  3145. });
  3146. }
  3147. module.exports = function(data, options) {
  3148. var zip = this;
  3149. options = utils.extend(options || {}, {
  3150. base64: false,
  3151. checkCRC32: false,
  3152. optimizedBinaryString: false,
  3153. createFolders: false,
  3154. decodeFileName: utf8.utf8decode
  3155. });
  3156. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  3157. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  3158. }
  3159. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  3160. .then(function(data) {
  3161. var zipEntries = new ZipEntries(options);
  3162. zipEntries.load(data);
  3163. return zipEntries;
  3164. }).then(function checkCRC32(zipEntries) {
  3165. var promises = [external.Promise.resolve(zipEntries)];
  3166. var files = zipEntries.files;
  3167. if (options.checkCRC32) {
  3168. for (var i = 0; i < files.length; i++) {
  3169. promises.push(checkEntryCRC32(files[i]));
  3170. }
  3171. }
  3172. return external.Promise.all(promises);
  3173. }).then(function addFiles(results) {
  3174. var zipEntries = results.shift();
  3175. var files = zipEntries.files;
  3176. for (var i = 0; i < files.length; i++) {
  3177. var input = files[i];
  3178. zip.file(input.fileNameStr, input.decompressed, {
  3179. binary: true,
  3180. optimizedBinaryString: true,
  3181. date: input.date,
  3182. dir: input.dir,
  3183. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  3184. unixPermissions : input.unixPermissions,
  3185. dosPermissions : input.dosPermissions,
  3186. createFolders: options.createFolders
  3187. });
  3188. }
  3189. if (zipEntries.zipComment.length) {
  3190. zip.comment = zipEntries.zipComment;
  3191. }
  3192. return zip;
  3193. });
  3194. };
  3195. },{"./external":17,"./nodejsUtils":23,"./stream/Crc32Probe":36,"./utf8":42,"./utils":43,"./zipEntries":44}],23:[function(require,module,exports){
  3196. (function (Buffer){
  3197. 'use strict';
  3198. module.exports = {
  3199. /**
  3200. * True if this is running in Nodejs, will be undefined in a browser.
  3201. * In a browser, browserify won't include this file and the whole module
  3202. * will be resolved an empty object.
  3203. */
  3204. isNode : typeof Buffer !== "undefined",
  3205. /**
  3206. * Create a new nodejs Buffer from an existing content.
  3207. * @param {Object} data the data to pass to the constructor.
  3208. * @param {String} encoding the encoding to use.
  3209. * @return {Buffer} a new Buffer.
  3210. */
  3211. newBufferFrom: function(data, encoding) {
  3212. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  3213. return Buffer.from(data, encoding);
  3214. } else {
  3215. if (typeof data === "number") {
  3216. // Safeguard for old Node.js versions. On newer versions,
  3217. // Buffer.from(number) / Buffer(number, encoding) already throw.
  3218. throw new Error("The \"data\" argument must not be a number");
  3219. }
  3220. return new Buffer(data, encoding);
  3221. }
  3222. },
  3223. /**
  3224. * Create a new nodejs Buffer with the specified size.
  3225. * @param {Integer} size the size of the buffer.
  3226. * @return {Buffer} a new Buffer.
  3227. */
  3228. allocBuffer: function (size) {
  3229. if (Buffer.alloc) {
  3230. return Buffer.alloc(size);
  3231. } else {
  3232. var buf = new Buffer(size);
  3233. buf.fill(0);
  3234. return buf;
  3235. }
  3236. },
  3237. /**
  3238. * Find out if an object is a Buffer.
  3239. * @param {Object} b the object to test.
  3240. * @return {Boolean} true if the object is a Buffer, false otherwise.
  3241. */
  3242. isBuffer : function(b){
  3243. return Buffer.isBuffer(b);
  3244. },
  3245. isStream : function (obj) {
  3246. return obj &&
  3247. typeof obj.on === "function" &&
  3248. typeof obj.pause === "function" &&
  3249. typeof obj.resume === "function";
  3250. }
  3251. };
  3252. }).call(this,require("buffer").Buffer)
  3253. },{"buffer":3}],24:[function(require,module,exports){
  3254. "use strict";
  3255. var utils = require('../utils');
  3256. var GenericWorker = require('../stream/GenericWorker');
  3257. /**
  3258. * A worker that use a nodejs stream as source.
  3259. * @constructor
  3260. * @param {String} filename the name of the file entry for this stream.
  3261. * @param {Readable} stream the nodejs stream.
  3262. */
  3263. function NodejsStreamInputAdapter(filename, stream) {
  3264. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  3265. this._upstreamEnded = false;
  3266. this._bindStream(stream);
  3267. }
  3268. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  3269. /**
  3270. * Prepare the stream and bind the callbacks on it.
  3271. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  3272. * @param {Stream} stream the nodejs stream to use.
  3273. */
  3274. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  3275. var self = this;
  3276. this._stream = stream;
  3277. stream.pause();
  3278. stream
  3279. .on("data", function (chunk) {
  3280. self.push({
  3281. data: chunk,
  3282. meta : {
  3283. percent : 0
  3284. }
  3285. });
  3286. })
  3287. .on("error", function (e) {
  3288. if(self.isPaused) {
  3289. this.generatedError = e;
  3290. } else {
  3291. self.error(e);
  3292. }
  3293. })
  3294. .on("end", function () {
  3295. if(self.isPaused) {
  3296. self._upstreamEnded = true;
  3297. } else {
  3298. self.end();
  3299. }
  3300. });
  3301. };
  3302. NodejsStreamInputAdapter.prototype.pause = function () {
  3303. if(!GenericWorker.prototype.pause.call(this)) {
  3304. return false;
  3305. }
  3306. this._stream.pause();
  3307. return true;
  3308. };
  3309. NodejsStreamInputAdapter.prototype.resume = function () {
  3310. if(!GenericWorker.prototype.resume.call(this)) {
  3311. return false;
  3312. }
  3313. if(this._upstreamEnded) {
  3314. this.end();
  3315. } else {
  3316. this._stream.resume();
  3317. }
  3318. return true;
  3319. };
  3320. module.exports = NodejsStreamInputAdapter;
  3321. },{"../stream/GenericWorker":39,"../utils":43}],25:[function(require,module,exports){
  3322. 'use strict';
  3323. var Readable = require('readable-stream').Readable;
  3324. var utils = require('../utils');
  3325. utils.inherits(NodejsStreamOutputAdapter, Readable);
  3326. /**
  3327. * A nodejs stream using a worker as source.
  3328. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  3329. * @constructor
  3330. * @param {StreamHelper} helper the helper wrapping the worker
  3331. * @param {Object} options the nodejs stream options
  3332. * @param {Function} updateCb the update callback.
  3333. */
  3334. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  3335. Readable.call(this, options);
  3336. this._helper = helper;
  3337. var self = this;
  3338. helper.on("data", function (data, meta) {
  3339. if (!self.push(data)) {
  3340. self._helper.pause();
  3341. }
  3342. if(updateCb) {
  3343. updateCb(meta);
  3344. }
  3345. })
  3346. .on("error", function(e) {
  3347. self.emit('error', e);
  3348. })
  3349. .on("end", function () {
  3350. self.push(null);
  3351. });
  3352. }
  3353. NodejsStreamOutputAdapter.prototype._read = function() {
  3354. this._helper.resume();
  3355. };
  3356. module.exports = NodejsStreamOutputAdapter;
  3357. },{"../utils":43,"readable-stream":27}],26:[function(require,module,exports){
  3358. 'use strict';
  3359. var utf8 = require('./utf8');
  3360. var utils = require('./utils');
  3361. var GenericWorker = require('./stream/GenericWorker');
  3362. var StreamHelper = require('./stream/StreamHelper');
  3363. var defaults = require('./defaults');
  3364. var CompressedObject = require('./compressedObject');
  3365. var ZipObject = require('./zipObject');
  3366. var generate = require("./generate");
  3367. var nodejsUtils = require("./nodejsUtils");
  3368. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  3369. /**
  3370. * Add a file in the current folder.
  3371. * @private
  3372. * @param {string} name the name of the file
  3373. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  3374. * @param {Object} originalOptions the options of the file
  3375. * @return {Object} the new file.
  3376. */
  3377. var fileAdd = function(name, data, originalOptions) {
  3378. // be sure sub folders exist
  3379. var dataType = utils.getTypeOf(data),
  3380. parent;
  3381. /*
  3382. * Correct options.
  3383. */
  3384. var o = utils.extend(originalOptions || {}, defaults);
  3385. o.date = o.date || new Date();
  3386. if (o.compression !== null) {
  3387. o.compression = o.compression.toUpperCase();
  3388. }
  3389. if (typeof o.unixPermissions === "string") {
  3390. o.unixPermissions = parseInt(o.unixPermissions, 8);
  3391. }
  3392. // UNX_IFDIR 0040000 see zipinfo.c
  3393. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  3394. o.dir = true;
  3395. }
  3396. // Bit 4 Directory
  3397. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  3398. o.dir = true;
  3399. }
  3400. if (o.dir) {
  3401. name = forceTrailingSlash(name);
  3402. }
  3403. if (o.createFolders && (parent = parentFolder(name))) {
  3404. folderAdd.call(this, parent, true);
  3405. }
  3406. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  3407. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  3408. o.binary = !isUnicodeString;
  3409. }
  3410. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  3411. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  3412. o.base64 = false;
  3413. o.binary = true;
  3414. data = "";
  3415. o.compression = "STORE";
  3416. dataType = "string";
  3417. }
  3418. /*
  3419. * Convert content to fit.
  3420. */
  3421. var zipObjectContent = null;
  3422. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  3423. zipObjectContent = data;
  3424. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  3425. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  3426. } else {
  3427. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  3428. }
  3429. var object = new ZipObject(name, zipObjectContent, o);
  3430. this.files[name] = object;
  3431. /*
  3432. TODO: we can't throw an exception because we have async promises
  3433. (we can have a promise of a Date() for example) but returning a
  3434. promise is useless because file(name, data) returns the JSZip
  3435. object for chaining. Should we break that to allow the user
  3436. to catch the error ?
  3437. return external.Promise.resolve(zipObjectContent)
  3438. .then(function () {
  3439. return object;
  3440. });
  3441. */
  3442. };
  3443. /**
  3444. * Find the parent folder of the path.
  3445. * @private
  3446. * @param {string} path the path to use
  3447. * @return {string} the parent folder, or ""
  3448. */
  3449. var parentFolder = function (path) {
  3450. if (path.slice(-1) === '/') {
  3451. path = path.substring(0, path.length - 1);
  3452. }
  3453. var lastSlash = path.lastIndexOf('/');
  3454. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  3455. };
  3456. /**
  3457. * Returns the path with a slash at the end.
  3458. * @private
  3459. * @param {String} path the path to check.
  3460. * @return {String} the path with a trailing slash.
  3461. */
  3462. var forceTrailingSlash = function(path) {
  3463. // Check the name ends with a /
  3464. if (path.slice(-1) !== "/") {
  3465. path += "/"; // IE doesn't like substr(-1)
  3466. }
  3467. return path;
  3468. };
  3469. /**
  3470. * Add a (sub) folder in the current folder.
  3471. * @private
  3472. * @param {string} name the folder's name
  3473. * @param {boolean=} [createFolders] If true, automatically create sub
  3474. * folders. Defaults to false.
  3475. * @return {Object} the new folder.
  3476. */
  3477. var folderAdd = function(name, createFolders) {
  3478. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  3479. name = forceTrailingSlash(name);
  3480. // Does this folder already exist?
  3481. if (!this.files[name]) {
  3482. fileAdd.call(this, name, null, {
  3483. dir: true,
  3484. createFolders: createFolders
  3485. });
  3486. }
  3487. return this.files[name];
  3488. };
  3489. /**
  3490. * Cross-window, cross-Node-context regular expression detection
  3491. * @param {Object} object Anything
  3492. * @return {Boolean} true if the object is a regular expression,
  3493. * false otherwise
  3494. */
  3495. function isRegExp(object) {
  3496. return Object.prototype.toString.call(object) === "[object RegExp]";
  3497. }
  3498. // return the actual prototype of JSZip
  3499. var out = {
  3500. /**
  3501. * @see loadAsync
  3502. */
  3503. load: function() {
  3504. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3505. },
  3506. /**
  3507. * Call a callback function for each entry at this folder level.
  3508. * @param {Function} cb the callback function:
  3509. * function (relativePath, file) {...}
  3510. * It takes 2 arguments : the relative path and the file.
  3511. */
  3512. forEach: function(cb) {
  3513. var filename, relativePath, file;
  3514. for (filename in this.files) {
  3515. if (!this.files.hasOwnProperty(filename)) {
  3516. continue;
  3517. }
  3518. file = this.files[filename];
  3519. relativePath = filename.slice(this.root.length, filename.length);
  3520. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  3521. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  3522. }
  3523. }
  3524. },
  3525. /**
  3526. * Filter nested files/folders with the specified function.
  3527. * @param {Function} search the predicate to use :
  3528. * function (relativePath, file) {...}
  3529. * It takes 2 arguments : the relative path and the file.
  3530. * @return {Array} An array of matching elements.
  3531. */
  3532. filter: function(search) {
  3533. var result = [];
  3534. this.forEach(function (relativePath, entry) {
  3535. if (search(relativePath, entry)) { // the file matches the function
  3536. result.push(entry);
  3537. }
  3538. });
  3539. return result;
  3540. },
  3541. /**
  3542. * Add a file to the zip file, or search a file.
  3543. * @param {string|RegExp} name The name of the file to add (if data is defined),
  3544. * the name of the file to find (if no data) or a regex to match files.
  3545. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  3546. * @param {Object} o File options
  3547. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  3548. * a file (when searching by string) or an array of files (when searching by regex).
  3549. */
  3550. file: function(name, data, o) {
  3551. if (arguments.length === 1) {
  3552. if (isRegExp(name)) {
  3553. var regexp = name;
  3554. return this.filter(function(relativePath, file) {
  3555. return !file.dir && regexp.test(relativePath);
  3556. });
  3557. }
  3558. else { // text
  3559. var obj = this.files[this.root + name];
  3560. if (obj && !obj.dir) {
  3561. return obj;
  3562. } else {
  3563. return null;
  3564. }
  3565. }
  3566. }
  3567. else { // more than one argument : we have data !
  3568. name = this.root + name;
  3569. fileAdd.call(this, name, data, o);
  3570. }
  3571. return this;
  3572. },
  3573. /**
  3574. * Add a directory to the zip file, or search.
  3575. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  3576. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  3577. */
  3578. folder: function(arg) {
  3579. if (!arg) {
  3580. return this;
  3581. }
  3582. if (isRegExp(arg)) {
  3583. return this.filter(function(relativePath, file) {
  3584. return file.dir && arg.test(relativePath);
  3585. });
  3586. }
  3587. // else, name is a new folder
  3588. var name = this.root + arg;
  3589. var newFolder = folderAdd.call(this, name);
  3590. // Allow chaining by returning a new object with this folder as the root
  3591. var ret = this.clone();
  3592. ret.root = newFolder.name;
  3593. return ret;
  3594. },
  3595. /**
  3596. * Delete a file, or a directory and all sub-files, from the zip
  3597. * @param {string} name the name of the file to delete
  3598. * @return {JSZip} this JSZip object
  3599. */
  3600. remove: function(name) {
  3601. name = this.root + name;
  3602. var file = this.files[name];
  3603. if (!file) {
  3604. // Look for any folders
  3605. if (name.slice(-1) !== "/") {
  3606. name += "/";
  3607. }
  3608. file = this.files[name];
  3609. }
  3610. if (file && !file.dir) {
  3611. // file
  3612. delete this.files[name];
  3613. } else {
  3614. // maybe a folder, delete recursively
  3615. var kids = this.filter(function(relativePath, file) {
  3616. return file.name.slice(0, name.length) === name;
  3617. });
  3618. for (var i = 0; i < kids.length; i++) {
  3619. delete this.files[kids[i].name];
  3620. }
  3621. }
  3622. return this;
  3623. },
  3624. /**
  3625. * Generate the complete zip file
  3626. * @param {Object} options the options to generate the zip file :
  3627. * - compression, "STORE" by default.
  3628. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  3629. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  3630. */
  3631. generate: function(options) {
  3632. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3633. },
  3634. /**
  3635. * Generate the complete zip file as an internal stream.
  3636. * @param {Object} options the options to generate the zip file :
  3637. * - compression, "STORE" by default.
  3638. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  3639. * @return {StreamHelper} the streamed zip file.
  3640. */
  3641. generateInternalStream: function(options) {
  3642. var worker, opts = {};
  3643. try {
  3644. opts = utils.extend(options || {}, {
  3645. streamFiles: false,
  3646. compression: "STORE",
  3647. compressionOptions : null,
  3648. type: "",
  3649. platform: "DOS",
  3650. comment: null,
  3651. mimeType: 'application/zip',
  3652. encodeFileName: utf8.utf8encode
  3653. });
  3654. opts.type = opts.type.toLowerCase();
  3655. opts.compression = opts.compression.toUpperCase();
  3656. // "binarystring" is preferred but the internals use "string".
  3657. if(opts.type === "binarystring") {
  3658. opts.type = "string";
  3659. }
  3660. if (!opts.type) {
  3661. throw new Error("No output type specified.");
  3662. }
  3663. utils.checkSupport(opts.type);
  3664. // accept nodejs `process.platform`
  3665. if(
  3666. opts.platform === 'darwin' ||
  3667. opts.platform === 'freebsd' ||
  3668. opts.platform === 'linux' ||
  3669. opts.platform === 'sunos'
  3670. ) {
  3671. opts.platform = "UNIX";
  3672. }
  3673. if (opts.platform === 'win32') {
  3674. opts.platform = "DOS";
  3675. }
  3676. var comment = opts.comment || this.comment || "";
  3677. worker = generate.generateWorker(this, opts, comment);
  3678. } catch (e) {
  3679. worker = new GenericWorker("error");
  3680. worker.error(e);
  3681. }
  3682. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  3683. },
  3684. /**
  3685. * Generate the complete zip file asynchronously.
  3686. * @see generateInternalStream
  3687. */
  3688. generateAsync: function(options, onUpdate) {
  3689. return this.generateInternalStream(options).accumulate(onUpdate);
  3690. },
  3691. /**
  3692. * Generate the complete zip file asynchronously.
  3693. * @see generateInternalStream
  3694. */
  3695. generateNodeStream: function(options, onUpdate) {
  3696. options = options || {};
  3697. if (!options.type) {
  3698. options.type = "nodebuffer";
  3699. }
  3700. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  3701. }
  3702. };
  3703. module.exports = out;
  3704. },{"./compressedObject":13,"./defaults":16,"./generate":20,"./nodejs/NodejsStreamInputAdapter":24,"./nodejsUtils":23,"./stream/GenericWorker":39,"./stream/StreamHelper":40,"./utf8":42,"./utils":43,"./zipObject":46}],27:[function(require,module,exports){
  3705. /*
  3706. * This file is used by module bundlers (browserify/webpack/etc) when
  3707. * including a stream implementation. We use "readable-stream" to get a
  3708. * consistent behavior between nodejs versions but bundlers often have a shim
  3709. * for "stream". Using this shim greatly improve the compatibility and greatly
  3710. * reduce the final size of the bundle (only one stream implementation, not
  3711. * two).
  3712. */
  3713. module.exports = require("stream");
  3714. },{"stream":81}],28:[function(require,module,exports){
  3715. 'use strict';
  3716. var DataReader = require('./DataReader');
  3717. var utils = require('../utils');
  3718. function ArrayReader(data) {
  3719. DataReader.call(this, data);
  3720. for(var i = 0; i < this.data.length; i++) {
  3721. data[i] = data[i] & 0xFF;
  3722. }
  3723. }
  3724. utils.inherits(ArrayReader, DataReader);
  3725. /**
  3726. * @see DataReader.byteAt
  3727. */
  3728. ArrayReader.prototype.byteAt = function(i) {
  3729. return this.data[this.zero + i];
  3730. };
  3731. /**
  3732. * @see DataReader.lastIndexOfSignature
  3733. */
  3734. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  3735. var sig0 = sig.charCodeAt(0),
  3736. sig1 = sig.charCodeAt(1),
  3737. sig2 = sig.charCodeAt(2),
  3738. sig3 = sig.charCodeAt(3);
  3739. for (var i = this.length - 4; i >= 0; --i) {
  3740. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  3741. return i - this.zero;
  3742. }
  3743. }
  3744. return -1;
  3745. };
  3746. /**
  3747. * @see DataReader.readAndCheckSignature
  3748. */
  3749. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  3750. var sig0 = sig.charCodeAt(0),
  3751. sig1 = sig.charCodeAt(1),
  3752. sig2 = sig.charCodeAt(2),
  3753. sig3 = sig.charCodeAt(3),
  3754. data = this.readData(4);
  3755. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  3756. };
  3757. /**
  3758. * @see DataReader.readData
  3759. */
  3760. ArrayReader.prototype.readData = function(size) {
  3761. this.checkOffset(size);
  3762. if(size === 0) {
  3763. return [];
  3764. }
  3765. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3766. this.index += size;
  3767. return result;
  3768. };
  3769. module.exports = ArrayReader;
  3770. },{"../utils":43,"./DataReader":29}],29:[function(require,module,exports){
  3771. 'use strict';
  3772. var utils = require('../utils');
  3773. function DataReader(data) {
  3774. this.data = data; // type : see implementation
  3775. this.length = data.length;
  3776. this.index = 0;
  3777. this.zero = 0;
  3778. }
  3779. DataReader.prototype = {
  3780. /**
  3781. * Check that the offset will not go too far.
  3782. * @param {string} offset the additional offset to check.
  3783. * @throws {Error} an Error if the offset is out of bounds.
  3784. */
  3785. checkOffset: function(offset) {
  3786. this.checkIndex(this.index + offset);
  3787. },
  3788. /**
  3789. * Check that the specified index will not be too far.
  3790. * @param {string} newIndex the index to check.
  3791. * @throws {Error} an Error if the index is out of bounds.
  3792. */
  3793. checkIndex: function(newIndex) {
  3794. if (this.length < this.zero + newIndex || newIndex < 0) {
  3795. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  3796. }
  3797. },
  3798. /**
  3799. * Change the index.
  3800. * @param {number} newIndex The new index.
  3801. * @throws {Error} if the new index is out of the data.
  3802. */
  3803. setIndex: function(newIndex) {
  3804. this.checkIndex(newIndex);
  3805. this.index = newIndex;
  3806. },
  3807. /**
  3808. * Skip the next n bytes.
  3809. * @param {number} n the number of bytes to skip.
  3810. * @throws {Error} if the new index is out of the data.
  3811. */
  3812. skip: function(n) {
  3813. this.setIndex(this.index + n);
  3814. },
  3815. /**
  3816. * Get the byte at the specified index.
  3817. * @param {number} i the index to use.
  3818. * @return {number} a byte.
  3819. */
  3820. byteAt: function(i) {
  3821. // see implementations
  3822. },
  3823. /**
  3824. * Get the next number with a given byte size.
  3825. * @param {number} size the number of bytes to read.
  3826. * @return {number} the corresponding number.
  3827. */
  3828. readInt: function(size) {
  3829. var result = 0,
  3830. i;
  3831. this.checkOffset(size);
  3832. for (i = this.index + size - 1; i >= this.index; i--) {
  3833. result = (result << 8) + this.byteAt(i);
  3834. }
  3835. this.index += size;
  3836. return result;
  3837. },
  3838. /**
  3839. * Get the next string with a given byte size.
  3840. * @param {number} size the number of bytes to read.
  3841. * @return {string} the corresponding string.
  3842. */
  3843. readString: function(size) {
  3844. return utils.transformTo("string", this.readData(size));
  3845. },
  3846. /**
  3847. * Get raw data without conversion, <size> bytes.
  3848. * @param {number} size the number of bytes to read.
  3849. * @return {Object} the raw data, implementation specific.
  3850. */
  3851. readData: function(size) {
  3852. // see implementations
  3853. },
  3854. /**
  3855. * Find the last occurrence of a zip signature (4 bytes).
  3856. * @param {string} sig the signature to find.
  3857. * @return {number} the index of the last occurrence, -1 if not found.
  3858. */
  3859. lastIndexOfSignature: function(sig) {
  3860. // see implementations
  3861. },
  3862. /**
  3863. * Read the signature (4 bytes) at the current position and compare it with sig.
  3864. * @param {string} sig the expected signature
  3865. * @return {boolean} true if the signature matches, false otherwise.
  3866. */
  3867. readAndCheckSignature: function(sig) {
  3868. // see implementations
  3869. },
  3870. /**
  3871. * Get the next date.
  3872. * @return {Date} the date.
  3873. */
  3874. readDate: function() {
  3875. var dostime = this.readInt(4);
  3876. return new Date(Date.UTC(
  3877. ((dostime >> 25) & 0x7f) + 1980, // year
  3878. ((dostime >> 21) & 0x0f) - 1, // month
  3879. (dostime >> 16) & 0x1f, // day
  3880. (dostime >> 11) & 0x1f, // hour
  3881. (dostime >> 5) & 0x3f, // minute
  3882. (dostime & 0x1f) << 1)); // second
  3883. }
  3884. };
  3885. module.exports = DataReader;
  3886. },{"../utils":43}],30:[function(require,module,exports){
  3887. 'use strict';
  3888. var Uint8ArrayReader = require('./Uint8ArrayReader');
  3889. var utils = require('../utils');
  3890. function NodeBufferReader(data) {
  3891. Uint8ArrayReader.call(this, data);
  3892. }
  3893. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  3894. /**
  3895. * @see DataReader.readData
  3896. */
  3897. NodeBufferReader.prototype.readData = function(size) {
  3898. this.checkOffset(size);
  3899. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3900. this.index += size;
  3901. return result;
  3902. };
  3903. module.exports = NodeBufferReader;
  3904. },{"../utils":43,"./Uint8ArrayReader":32}],31:[function(require,module,exports){
  3905. 'use strict';
  3906. var DataReader = require('./DataReader');
  3907. var utils = require('../utils');
  3908. function StringReader(data) {
  3909. DataReader.call(this, data);
  3910. }
  3911. utils.inherits(StringReader, DataReader);
  3912. /**
  3913. * @see DataReader.byteAt
  3914. */
  3915. StringReader.prototype.byteAt = function(i) {
  3916. return this.data.charCodeAt(this.zero + i);
  3917. };
  3918. /**
  3919. * @see DataReader.lastIndexOfSignature
  3920. */
  3921. StringReader.prototype.lastIndexOfSignature = function(sig) {
  3922. return this.data.lastIndexOf(sig) - this.zero;
  3923. };
  3924. /**
  3925. * @see DataReader.readAndCheckSignature
  3926. */
  3927. StringReader.prototype.readAndCheckSignature = function (sig) {
  3928. var data = this.readData(4);
  3929. return sig === data;
  3930. };
  3931. /**
  3932. * @see DataReader.readData
  3933. */
  3934. StringReader.prototype.readData = function(size) {
  3935. this.checkOffset(size);
  3936. // this will work because the constructor applied the "& 0xff" mask.
  3937. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3938. this.index += size;
  3939. return result;
  3940. };
  3941. module.exports = StringReader;
  3942. },{"../utils":43,"./DataReader":29}],32:[function(require,module,exports){
  3943. 'use strict';
  3944. var ArrayReader = require('./ArrayReader');
  3945. var utils = require('../utils');
  3946. function Uint8ArrayReader(data) {
  3947. ArrayReader.call(this, data);
  3948. }
  3949. utils.inherits(Uint8ArrayReader, ArrayReader);
  3950. /**
  3951. * @see DataReader.readData
  3952. */
  3953. Uint8ArrayReader.prototype.readData = function(size) {
  3954. this.checkOffset(size);
  3955. if(size === 0) {
  3956. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  3957. return new Uint8Array(0);
  3958. }
  3959. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  3960. this.index += size;
  3961. return result;
  3962. };
  3963. module.exports = Uint8ArrayReader;
  3964. },{"../utils":43,"./ArrayReader":28}],33:[function(require,module,exports){
  3965. 'use strict';
  3966. var utils = require('../utils');
  3967. var support = require('../support');
  3968. var ArrayReader = require('./ArrayReader');
  3969. var StringReader = require('./StringReader');
  3970. var NodeBufferReader = require('./NodeBufferReader');
  3971. var Uint8ArrayReader = require('./Uint8ArrayReader');
  3972. /**
  3973. * Create a reader adapted to the data.
  3974. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  3975. * @return {DataReader} the data reader.
  3976. */
  3977. module.exports = function (data) {
  3978. var type = utils.getTypeOf(data);
  3979. utils.checkSupport(type);
  3980. if (type === "string" && !support.uint8array) {
  3981. return new StringReader(data);
  3982. }
  3983. if (type === "nodebuffer") {
  3984. return new NodeBufferReader(data);
  3985. }
  3986. if (support.uint8array) {
  3987. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  3988. }
  3989. return new ArrayReader(utils.transformTo("array", data));
  3990. };
  3991. },{"../support":41,"../utils":43,"./ArrayReader":28,"./NodeBufferReader":30,"./StringReader":31,"./Uint8ArrayReader":32}],34:[function(require,module,exports){
  3992. 'use strict';
  3993. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  3994. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  3995. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  3996. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  3997. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  3998. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  3999. },{}],35:[function(require,module,exports){
  4000. 'use strict';
  4001. var GenericWorker = require('./GenericWorker');
  4002. var utils = require('../utils');
  4003. /**
  4004. * A worker which convert chunks to a specified type.
  4005. * @constructor
  4006. * @param {String} destType the destination type.
  4007. */
  4008. function ConvertWorker(destType) {
  4009. GenericWorker.call(this, "ConvertWorker to " + destType);
  4010. this.destType = destType;
  4011. }
  4012. utils.inherits(ConvertWorker, GenericWorker);
  4013. /**
  4014. * @see GenericWorker.processChunk
  4015. */
  4016. ConvertWorker.prototype.processChunk = function (chunk) {
  4017. this.push({
  4018. data : utils.transformTo(this.destType, chunk.data),
  4019. meta : chunk.meta
  4020. });
  4021. };
  4022. module.exports = ConvertWorker;
  4023. },{"../utils":43,"./GenericWorker":39}],36:[function(require,module,exports){
  4024. 'use strict';
  4025. var GenericWorker = require('./GenericWorker');
  4026. var crc32 = require('../crc32');
  4027. var utils = require('../utils');
  4028. /**
  4029. * A worker which calculate the crc32 of the data flowing through.
  4030. * @constructor
  4031. */
  4032. function Crc32Probe() {
  4033. GenericWorker.call(this, "Crc32Probe");
  4034. this.withStreamInfo("crc32", 0);
  4035. }
  4036. utils.inherits(Crc32Probe, GenericWorker);
  4037. /**
  4038. * @see GenericWorker.processChunk
  4039. */
  4040. Crc32Probe.prototype.processChunk = function (chunk) {
  4041. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  4042. this.push(chunk);
  4043. };
  4044. module.exports = Crc32Probe;
  4045. },{"../crc32":15,"../utils":43,"./GenericWorker":39}],37:[function(require,module,exports){
  4046. 'use strict';
  4047. var utils = require('../utils');
  4048. var GenericWorker = require('./GenericWorker');
  4049. /**
  4050. * A worker which calculate the total length of the data flowing through.
  4051. * @constructor
  4052. * @param {String} propName the name used to expose the length
  4053. */
  4054. function DataLengthProbe(propName) {
  4055. GenericWorker.call(this, "DataLengthProbe for " + propName);
  4056. this.propName = propName;
  4057. this.withStreamInfo(propName, 0);
  4058. }
  4059. utils.inherits(DataLengthProbe, GenericWorker);
  4060. /**
  4061. * @see GenericWorker.processChunk
  4062. */
  4063. DataLengthProbe.prototype.processChunk = function (chunk) {
  4064. if(chunk) {
  4065. var length = this.streamInfo[this.propName] || 0;
  4066. this.streamInfo[this.propName] = length + chunk.data.length;
  4067. }
  4068. GenericWorker.prototype.processChunk.call(this, chunk);
  4069. };
  4070. module.exports = DataLengthProbe;
  4071. },{"../utils":43,"./GenericWorker":39}],38:[function(require,module,exports){
  4072. 'use strict';
  4073. var utils = require('../utils');
  4074. var GenericWorker = require('./GenericWorker');
  4075. // the size of the generated chunks
  4076. // TODO expose this as a public variable
  4077. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  4078. /**
  4079. * A worker that reads a content and emits chunks.
  4080. * @constructor
  4081. * @param {Promise} dataP the promise of the data to split
  4082. */
  4083. function DataWorker(dataP) {
  4084. GenericWorker.call(this, "DataWorker");
  4085. var self = this;
  4086. this.dataIsReady = false;
  4087. this.index = 0;
  4088. this.max = 0;
  4089. this.data = null;
  4090. this.type = "";
  4091. this._tickScheduled = false;
  4092. dataP.then(function (data) {
  4093. self.dataIsReady = true;
  4094. self.data = data;
  4095. self.max = data && data.length || 0;
  4096. self.type = utils.getTypeOf(data);
  4097. if(!self.isPaused) {
  4098. self._tickAndRepeat();
  4099. }
  4100. }, function (e) {
  4101. self.error(e);
  4102. });
  4103. }
  4104. utils.inherits(DataWorker, GenericWorker);
  4105. /**
  4106. * @see GenericWorker.cleanUp
  4107. */
  4108. DataWorker.prototype.cleanUp = function () {
  4109. GenericWorker.prototype.cleanUp.call(this);
  4110. this.data = null;
  4111. };
  4112. /**
  4113. * @see GenericWorker.resume
  4114. */
  4115. DataWorker.prototype.resume = function () {
  4116. if(!GenericWorker.prototype.resume.call(this)) {
  4117. return false;
  4118. }
  4119. if (!this._tickScheduled && this.dataIsReady) {
  4120. this._tickScheduled = true;
  4121. utils.delay(this._tickAndRepeat, [], this);
  4122. }
  4123. return true;
  4124. };
  4125. /**
  4126. * Trigger a tick a schedule an other call to this function.
  4127. */
  4128. DataWorker.prototype._tickAndRepeat = function() {
  4129. this._tickScheduled = false;
  4130. if(this.isPaused || this.isFinished) {
  4131. return;
  4132. }
  4133. this._tick();
  4134. if(!this.isFinished) {
  4135. utils.delay(this._tickAndRepeat, [], this);
  4136. this._tickScheduled = true;
  4137. }
  4138. };
  4139. /**
  4140. * Read and push a chunk.
  4141. */
  4142. DataWorker.prototype._tick = function() {
  4143. if(this.isPaused || this.isFinished) {
  4144. return false;
  4145. }
  4146. var size = DEFAULT_BLOCK_SIZE;
  4147. var data = null, nextIndex = Math.min(this.max, this.index + size);
  4148. if (this.index >= this.max) {
  4149. // EOF
  4150. return this.end();
  4151. } else {
  4152. switch(this.type) {
  4153. case "string":
  4154. data = this.data.substring(this.index, nextIndex);
  4155. break;
  4156. case "uint8array":
  4157. data = this.data.subarray(this.index, nextIndex);
  4158. break;
  4159. case "array":
  4160. case "nodebuffer":
  4161. data = this.data.slice(this.index, nextIndex);
  4162. break;
  4163. }
  4164. this.index = nextIndex;
  4165. return this.push({
  4166. data : data,
  4167. meta : {
  4168. percent : this.max ? this.index / this.max * 100 : 0
  4169. }
  4170. });
  4171. }
  4172. };
  4173. module.exports = DataWorker;
  4174. },{"../utils":43,"./GenericWorker":39}],39:[function(require,module,exports){
  4175. 'use strict';
  4176. /**
  4177. * A worker that does nothing but passing chunks to the next one. This is like
  4178. * a nodejs stream but with some differences. On the good side :
  4179. * - it works on IE 6-9 without any issue / polyfill
  4180. * - it weights less than the full dependencies bundled with browserify
  4181. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  4182. *
  4183. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  4184. * object containing anything (`percent` for example), see each worker for more
  4185. * details. The latter is the real data (String, Uint8Array, etc).
  4186. *
  4187. * @constructor
  4188. * @param {String} name the name of the stream (mainly used for debugging purposes)
  4189. */
  4190. function GenericWorker(name) {
  4191. // the name of the worker
  4192. this.name = name || "default";
  4193. // an object containing metadata about the workers chain
  4194. this.streamInfo = {};
  4195. // an error which happened when the worker was paused
  4196. this.generatedError = null;
  4197. // an object containing metadata to be merged by this worker into the general metadata
  4198. this.extraStreamInfo = {};
  4199. // true if the stream is paused (and should not do anything), false otherwise
  4200. this.isPaused = true;
  4201. // true if the stream is finished (and should not do anything), false otherwise
  4202. this.isFinished = false;
  4203. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  4204. this.isLocked = false;
  4205. // the event listeners
  4206. this._listeners = {
  4207. 'data':[],
  4208. 'end':[],
  4209. 'error':[]
  4210. };
  4211. // the previous worker, if any
  4212. this.previous = null;
  4213. }
  4214. GenericWorker.prototype = {
  4215. /**
  4216. * Push a chunk to the next workers.
  4217. * @param {Object} chunk the chunk to push
  4218. */
  4219. push : function (chunk) {
  4220. this.emit("data", chunk);
  4221. },
  4222. /**
  4223. * End the stream.
  4224. * @return {Boolean} true if this call ended the worker, false otherwise.
  4225. */
  4226. end : function () {
  4227. if (this.isFinished) {
  4228. return false;
  4229. }
  4230. this.flush();
  4231. try {
  4232. this.emit("end");
  4233. this.cleanUp();
  4234. this.isFinished = true;
  4235. } catch (e) {
  4236. this.emit("error", e);
  4237. }
  4238. return true;
  4239. },
  4240. /**
  4241. * End the stream with an error.
  4242. * @param {Error} e the error which caused the premature end.
  4243. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  4244. */
  4245. error : function (e) {
  4246. if (this.isFinished) {
  4247. return false;
  4248. }
  4249. if(this.isPaused) {
  4250. this.generatedError = e;
  4251. } else {
  4252. this.isFinished = true;
  4253. this.emit("error", e);
  4254. // in the workers chain exploded in the middle of the chain,
  4255. // the error event will go downward but we also need to notify
  4256. // workers upward that there has been an error.
  4257. if(this.previous) {
  4258. this.previous.error(e);
  4259. }
  4260. this.cleanUp();
  4261. }
  4262. return true;
  4263. },
  4264. /**
  4265. * Add a callback on an event.
  4266. * @param {String} name the name of the event (data, end, error)
  4267. * @param {Function} listener the function to call when the event is triggered
  4268. * @return {GenericWorker} the current object for chainability
  4269. */
  4270. on : function (name, listener) {
  4271. this._listeners[name].push(listener);
  4272. return this;
  4273. },
  4274. /**
  4275. * Clean any references when a worker is ending.
  4276. */
  4277. cleanUp : function () {
  4278. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  4279. this._listeners = [];
  4280. },
  4281. /**
  4282. * Trigger an event. This will call registered callback with the provided arg.
  4283. * @param {String} name the name of the event (data, end, error)
  4284. * @param {Object} arg the argument to call the callback with.
  4285. */
  4286. emit : function (name, arg) {
  4287. if (this._listeners[name]) {
  4288. for(var i = 0; i < this._listeners[name].length; i++) {
  4289. this._listeners[name][i].call(this, arg);
  4290. }
  4291. }
  4292. },
  4293. /**
  4294. * Chain a worker with an other.
  4295. * @param {Worker} next the worker receiving events from the current one.
  4296. * @return {worker} the next worker for chainability
  4297. */
  4298. pipe : function (next) {
  4299. return next.registerPrevious(this);
  4300. },
  4301. /**
  4302. * Same as `pipe` in the other direction.
  4303. * Using an API with `pipe(next)` is very easy.
  4304. * Implementing the API with the point of view of the next one registering
  4305. * a source is easier, see the ZipFileWorker.
  4306. * @param {Worker} previous the previous worker, sending events to this one
  4307. * @return {Worker} the current worker for chainability
  4308. */
  4309. registerPrevious : function (previous) {
  4310. if (this.isLocked) {
  4311. throw new Error("The stream '" + this + "' has already been used.");
  4312. }
  4313. // sharing the streamInfo...
  4314. this.streamInfo = previous.streamInfo;
  4315. // ... and adding our own bits
  4316. this.mergeStreamInfo();
  4317. this.previous = previous;
  4318. var self = this;
  4319. previous.on('data', function (chunk) {
  4320. self.processChunk(chunk);
  4321. });
  4322. previous.on('end', function () {
  4323. self.end();
  4324. });
  4325. previous.on('error', function (e) {
  4326. self.error(e);
  4327. });
  4328. return this;
  4329. },
  4330. /**
  4331. * Pause the stream so it doesn't send events anymore.
  4332. * @return {Boolean} true if this call paused the worker, false otherwise.
  4333. */
  4334. pause : function () {
  4335. if(this.isPaused || this.isFinished) {
  4336. return false;
  4337. }
  4338. this.isPaused = true;
  4339. if(this.previous) {
  4340. this.previous.pause();
  4341. }
  4342. return true;
  4343. },
  4344. /**
  4345. * Resume a paused stream.
  4346. * @return {Boolean} true if this call resumed the worker, false otherwise.
  4347. */
  4348. resume : function () {
  4349. if(!this.isPaused || this.isFinished) {
  4350. return false;
  4351. }
  4352. this.isPaused = false;
  4353. // if true, the worker tried to resume but failed
  4354. var withError = false;
  4355. if(this.generatedError) {
  4356. this.error(this.generatedError);
  4357. withError = true;
  4358. }
  4359. if(this.previous) {
  4360. this.previous.resume();
  4361. }
  4362. return !withError;
  4363. },
  4364. /**
  4365. * Flush any remaining bytes as the stream is ending.
  4366. */
  4367. flush : function () {},
  4368. /**
  4369. * Process a chunk. This is usually the method overridden.
  4370. * @param {Object} chunk the chunk to process.
  4371. */
  4372. processChunk : function(chunk) {
  4373. this.push(chunk);
  4374. },
  4375. /**
  4376. * Add a key/value to be added in the workers chain streamInfo once activated.
  4377. * @param {String} key the key to use
  4378. * @param {Object} value the associated value
  4379. * @return {Worker} the current worker for chainability
  4380. */
  4381. withStreamInfo : function (key, value) {
  4382. this.extraStreamInfo[key] = value;
  4383. this.mergeStreamInfo();
  4384. return this;
  4385. },
  4386. /**
  4387. * Merge this worker's streamInfo into the chain's streamInfo.
  4388. */
  4389. mergeStreamInfo : function () {
  4390. for(var key in this.extraStreamInfo) {
  4391. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  4392. continue;
  4393. }
  4394. this.streamInfo[key] = this.extraStreamInfo[key];
  4395. }
  4396. },
  4397. /**
  4398. * Lock the stream to prevent further updates on the workers chain.
  4399. * After calling this method, all calls to pipe will fail.
  4400. */
  4401. lock: function () {
  4402. if (this.isLocked) {
  4403. throw new Error("The stream '" + this + "' has already been used.");
  4404. }
  4405. this.isLocked = true;
  4406. if (this.previous) {
  4407. this.previous.lock();
  4408. }
  4409. },
  4410. /**
  4411. *
  4412. * Pretty print the workers chain.
  4413. */
  4414. toString : function () {
  4415. var me = "Worker " + this.name;
  4416. if (this.previous) {
  4417. return this.previous + " -> " + me;
  4418. } else {
  4419. return me;
  4420. }
  4421. }
  4422. };
  4423. module.exports = GenericWorker;
  4424. },{}],40:[function(require,module,exports){
  4425. (function (Buffer){
  4426. 'use strict';
  4427. var utils = require('../utils');
  4428. var ConvertWorker = require('./ConvertWorker');
  4429. var GenericWorker = require('./GenericWorker');
  4430. var base64 = require('../base64');
  4431. var support = require("../support");
  4432. var external = require("../external");
  4433. var NodejsStreamOutputAdapter = null;
  4434. if (support.nodestream) {
  4435. try {
  4436. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  4437. } catch(e) {}
  4438. }
  4439. /**
  4440. * Apply the final transformation of the data. If the user wants a Blob for
  4441. * example, it's easier to work with an U8intArray and finally do the
  4442. * ArrayBuffer/Blob conversion.
  4443. * @param {String} type the name of the final type
  4444. * @param {String|Uint8Array|Buffer} content the content to transform
  4445. * @param {String} mimeType the mime type of the content, if applicable.
  4446. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  4447. */
  4448. function transformZipOutput(type, content, mimeType) {
  4449. switch(type) {
  4450. case "blob" :
  4451. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  4452. case "base64" :
  4453. return base64.encode(content);
  4454. default :
  4455. return utils.transformTo(type, content);
  4456. }
  4457. }
  4458. /**
  4459. * Concatenate an array of data of the given type.
  4460. * @param {String} type the type of the data in the given array.
  4461. * @param {Array} dataArray the array containing the data chunks to concatenate
  4462. * @return {String|Uint8Array|Buffer} the concatenated data
  4463. * @throws Error if the asked type is unsupported
  4464. */
  4465. function concat (type, dataArray) {
  4466. var i, index = 0, res = null, totalLength = 0;
  4467. for(i = 0; i < dataArray.length; i++) {
  4468. totalLength += dataArray[i].length;
  4469. }
  4470. switch(type) {
  4471. case "string":
  4472. return dataArray.join("");
  4473. case "array":
  4474. return Array.prototype.concat.apply([], dataArray);
  4475. case "uint8array":
  4476. res = new Uint8Array(totalLength);
  4477. for(i = 0; i < dataArray.length; i++) {
  4478. res.set(dataArray[i], index);
  4479. index += dataArray[i].length;
  4480. }
  4481. return res;
  4482. case "nodebuffer":
  4483. return Buffer.concat(dataArray);
  4484. default:
  4485. throw new Error("concat : unsupported type '" + type + "'");
  4486. }
  4487. }
  4488. /**
  4489. * Listen a StreamHelper, accumulate its content and concatenate it into a
  4490. * complete block.
  4491. * @param {StreamHelper} helper the helper to use.
  4492. * @param {Function} updateCallback a callback called on each update. Called
  4493. * with one arg :
  4494. * - the metadata linked to the update received.
  4495. * @return Promise the promise for the accumulation.
  4496. */
  4497. function accumulate(helper, updateCallback) {
  4498. return new external.Promise(function (resolve, reject){
  4499. var dataArray = [];
  4500. var chunkType = helper._internalType,
  4501. resultType = helper._outputType,
  4502. mimeType = helper._mimeType;
  4503. helper
  4504. .on('data', function (data, meta) {
  4505. dataArray.push(data);
  4506. if(updateCallback) {
  4507. updateCallback(meta);
  4508. }
  4509. })
  4510. .on('error', function(err) {
  4511. dataArray = [];
  4512. reject(err);
  4513. })
  4514. .on('end', function (){
  4515. try {
  4516. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  4517. resolve(result);
  4518. } catch (e) {
  4519. reject(e);
  4520. }
  4521. dataArray = [];
  4522. })
  4523. .resume();
  4524. });
  4525. }
  4526. /**
  4527. * An helper to easily use workers outside of JSZip.
  4528. * @constructor
  4529. * @param {Worker} worker the worker to wrap
  4530. * @param {String} outputType the type of data expected by the use
  4531. * @param {String} mimeType the mime type of the content, if applicable.
  4532. */
  4533. function StreamHelper(worker, outputType, mimeType) {
  4534. var internalType = outputType;
  4535. switch(outputType) {
  4536. case "blob":
  4537. case "arraybuffer":
  4538. internalType = "uint8array";
  4539. break;
  4540. case "base64":
  4541. internalType = "string";
  4542. break;
  4543. }
  4544. try {
  4545. // the type used internally
  4546. this._internalType = internalType;
  4547. // the type used to output results
  4548. this._outputType = outputType;
  4549. // the mime type
  4550. this._mimeType = mimeType;
  4551. utils.checkSupport(internalType);
  4552. this._worker = worker.pipe(new ConvertWorker(internalType));
  4553. // the last workers can be rewired without issues but we need to
  4554. // prevent any updates on previous workers.
  4555. worker.lock();
  4556. } catch(e) {
  4557. this._worker = new GenericWorker("error");
  4558. this._worker.error(e);
  4559. }
  4560. }
  4561. StreamHelper.prototype = {
  4562. /**
  4563. * Listen a StreamHelper, accumulate its content and concatenate it into a
  4564. * complete block.
  4565. * @param {Function} updateCb the update callback.
  4566. * @return Promise the promise for the accumulation.
  4567. */
  4568. accumulate : function (updateCb) {
  4569. return accumulate(this, updateCb);
  4570. },
  4571. /**
  4572. * Add a listener on an event triggered on a stream.
  4573. * @param {String} evt the name of the event
  4574. * @param {Function} fn the listener
  4575. * @return {StreamHelper} the current helper.
  4576. */
  4577. on : function (evt, fn) {
  4578. var self = this;
  4579. if(evt === "data") {
  4580. this._worker.on(evt, function (chunk) {
  4581. fn.call(self, chunk.data, chunk.meta);
  4582. });
  4583. } else {
  4584. this._worker.on(evt, function () {
  4585. utils.delay(fn, arguments, self);
  4586. });
  4587. }
  4588. return this;
  4589. },
  4590. /**
  4591. * Resume the flow of chunks.
  4592. * @return {StreamHelper} the current helper.
  4593. */
  4594. resume : function () {
  4595. utils.delay(this._worker.resume, [], this._worker);
  4596. return this;
  4597. },
  4598. /**
  4599. * Pause the flow of chunks.
  4600. * @return {StreamHelper} the current helper.
  4601. */
  4602. pause : function () {
  4603. this._worker.pause();
  4604. return this;
  4605. },
  4606. /**
  4607. * Return a nodejs stream for this helper.
  4608. * @param {Function} updateCb the update callback.
  4609. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  4610. */
  4611. toNodejsStream : function (updateCb) {
  4612. utils.checkSupport("nodestream");
  4613. if (this._outputType !== "nodebuffer") {
  4614. // an object stream containing blob/arraybuffer/uint8array/string
  4615. // is strange and I don't know if it would be useful.
  4616. // I you find this comment and have a good usecase, please open a
  4617. // bug report !
  4618. throw new Error(this._outputType + " is not supported by this method");
  4619. }
  4620. return new NodejsStreamOutputAdapter(this, {
  4621. objectMode : this._outputType !== "nodebuffer"
  4622. }, updateCb);
  4623. }
  4624. };
  4625. module.exports = StreamHelper;
  4626. }).call(this,require("buffer").Buffer)
  4627. },{"../base64":12,"../external":17,"../nodejs/NodejsStreamOutputAdapter":25,"../support":41,"../utils":43,"./ConvertWorker":35,"./GenericWorker":39,"buffer":3}],41:[function(require,module,exports){
  4628. (function (Buffer){
  4629. 'use strict';
  4630. exports.base64 = true;
  4631. exports.array = true;
  4632. exports.string = true;
  4633. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  4634. exports.nodebuffer = typeof Buffer !== "undefined";
  4635. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  4636. exports.uint8array = typeof Uint8Array !== "undefined";
  4637. if (typeof ArrayBuffer === "undefined") {
  4638. exports.blob = false;
  4639. }
  4640. else {
  4641. var buffer = new ArrayBuffer(0);
  4642. try {
  4643. exports.blob = new Blob([buffer], {
  4644. type: "application/zip"
  4645. }).size === 0;
  4646. }
  4647. catch (e) {
  4648. try {
  4649. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  4650. var builder = new Builder();
  4651. builder.append(buffer);
  4652. exports.blob = builder.getBlob('application/zip').size === 0;
  4653. }
  4654. catch (e) {
  4655. exports.blob = false;
  4656. }
  4657. }
  4658. }
  4659. try {
  4660. exports.nodestream = !!require('readable-stream').Readable;
  4661. } catch(e) {
  4662. exports.nodestream = false;
  4663. }
  4664. }).call(this,require("buffer").Buffer)
  4665. },{"buffer":3,"readable-stream":27}],42:[function(require,module,exports){
  4666. 'use strict';
  4667. var utils = require('./utils');
  4668. var support = require('./support');
  4669. var nodejsUtils = require('./nodejsUtils');
  4670. var GenericWorker = require('./stream/GenericWorker');
  4671. /**
  4672. * The following functions come from pako, from pako/lib/utils/strings
  4673. * released under the MIT license, see pako https://github.com/nodeca/pako/
  4674. */
  4675. // Table with utf8 lengths (calculated by first byte of sequence)
  4676. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4677. // because max possible codepoint is 0x10ffff
  4678. var _utf8len = new Array(256);
  4679. for (var i=0; i<256; i++) {
  4680. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  4681. }
  4682. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  4683. // convert string to array (typed, when possible)
  4684. var string2buf = function (str) {
  4685. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4686. // count binary size
  4687. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4688. c = str.charCodeAt(m_pos);
  4689. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  4690. c2 = str.charCodeAt(m_pos+1);
  4691. if ((c2 & 0xfc00) === 0xdc00) {
  4692. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4693. m_pos++;
  4694. }
  4695. }
  4696. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4697. }
  4698. // allocate buffer
  4699. if (support.uint8array) {
  4700. buf = new Uint8Array(buf_len);
  4701. } else {
  4702. buf = new Array(buf_len);
  4703. }
  4704. // convert
  4705. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  4706. c = str.charCodeAt(m_pos);
  4707. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  4708. c2 = str.charCodeAt(m_pos+1);
  4709. if ((c2 & 0xfc00) === 0xdc00) {
  4710. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4711. m_pos++;
  4712. }
  4713. }
  4714. if (c < 0x80) {
  4715. /* one byte */
  4716. buf[i++] = c;
  4717. } else if (c < 0x800) {
  4718. /* two bytes */
  4719. buf[i++] = 0xC0 | (c >>> 6);
  4720. buf[i++] = 0x80 | (c & 0x3f);
  4721. } else if (c < 0x10000) {
  4722. /* three bytes */
  4723. buf[i++] = 0xE0 | (c >>> 12);
  4724. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4725. buf[i++] = 0x80 | (c & 0x3f);
  4726. } else {
  4727. /* four bytes */
  4728. buf[i++] = 0xf0 | (c >>> 18);
  4729. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  4730. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4731. buf[i++] = 0x80 | (c & 0x3f);
  4732. }
  4733. }
  4734. return buf;
  4735. };
  4736. // Calculate max possible position in utf8 buffer,
  4737. // that will not break sequence. If that's not possible
  4738. // - (very small limits) return max size as is.
  4739. //
  4740. // buf[] - utf8 bytes array
  4741. // max - length limit (mandatory);
  4742. var utf8border = function(buf, max) {
  4743. var pos;
  4744. max = max || buf.length;
  4745. if (max > buf.length) { max = buf.length; }
  4746. // go back from last position, until start of sequence found
  4747. pos = max-1;
  4748. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  4749. // Fuckup - very small and broken sequence,
  4750. // return max, because we should return something anyway.
  4751. if (pos < 0) { return max; }
  4752. // If we came to start of buffer - that means vuffer is too small,
  4753. // return max too.
  4754. if (pos === 0) { return max; }
  4755. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  4756. };
  4757. // convert array to string
  4758. var buf2string = function (buf) {
  4759. var str, i, out, c, c_len;
  4760. var len = buf.length;
  4761. // Reserve max possible length (2 words per char)
  4762. // NB: by unknown reasons, Array is significantly faster for
  4763. // String.fromCharCode.apply than Uint16Array.
  4764. var utf16buf = new Array(len*2);
  4765. for (out=0, i=0; i<len;) {
  4766. c = buf[i++];
  4767. // quick process ascii
  4768. if (c < 0x80) { utf16buf[out++] = c; continue; }
  4769. c_len = _utf8len[c];
  4770. // skip 5 & 6 byte codes
  4771. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  4772. // apply mask on first byte
  4773. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  4774. // join the rest
  4775. while (c_len > 1 && i < len) {
  4776. c = (c << 6) | (buf[i++] & 0x3f);
  4777. c_len--;
  4778. }
  4779. // terminated by end of string?
  4780. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  4781. if (c < 0x10000) {
  4782. utf16buf[out++] = c;
  4783. } else {
  4784. c -= 0x10000;
  4785. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  4786. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  4787. }
  4788. }
  4789. // shrinkBuf(utf16buf, out)
  4790. if (utf16buf.length !== out) {
  4791. if(utf16buf.subarray) {
  4792. utf16buf = utf16buf.subarray(0, out);
  4793. } else {
  4794. utf16buf.length = out;
  4795. }
  4796. }
  4797. // return String.fromCharCode.apply(null, utf16buf);
  4798. return utils.applyFromCharCode(utf16buf);
  4799. };
  4800. // That's all for the pako functions.
  4801. /**
  4802. * Transform a javascript string into an array (typed if possible) of bytes,
  4803. * UTF-8 encoded.
  4804. * @param {String} str the string to encode
  4805. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  4806. */
  4807. exports.utf8encode = function utf8encode(str) {
  4808. if (support.nodebuffer) {
  4809. return nodejsUtils.newBufferFrom(str, "utf-8");
  4810. }
  4811. return string2buf(str);
  4812. };
  4813. /**
  4814. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  4815. * string into a javascript string.
  4816. * @param {Array|Uint8Array|Buffer} buf the data de decode
  4817. * @return {String} the decoded string.
  4818. */
  4819. exports.utf8decode = function utf8decode(buf) {
  4820. if (support.nodebuffer) {
  4821. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  4822. }
  4823. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  4824. return buf2string(buf);
  4825. };
  4826. /**
  4827. * A worker to decode utf8 encoded binary chunks into string chunks.
  4828. * @constructor
  4829. */
  4830. function Utf8DecodeWorker() {
  4831. GenericWorker.call(this, "utf-8 decode");
  4832. // the last bytes if a chunk didn't end with a complete codepoint.
  4833. this.leftOver = null;
  4834. }
  4835. utils.inherits(Utf8DecodeWorker, GenericWorker);
  4836. /**
  4837. * @see GenericWorker.processChunk
  4838. */
  4839. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  4840. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  4841. // 1st step, re-use what's left of the previous chunk
  4842. if (this.leftOver && this.leftOver.length) {
  4843. if(support.uint8array) {
  4844. var previousData = data;
  4845. data = new Uint8Array(previousData.length + this.leftOver.length);
  4846. data.set(this.leftOver, 0);
  4847. data.set(previousData, this.leftOver.length);
  4848. } else {
  4849. data = this.leftOver.concat(data);
  4850. }
  4851. this.leftOver = null;
  4852. }
  4853. var nextBoundary = utf8border(data);
  4854. var usableData = data;
  4855. if (nextBoundary !== data.length) {
  4856. if (support.uint8array) {
  4857. usableData = data.subarray(0, nextBoundary);
  4858. this.leftOver = data.subarray(nextBoundary, data.length);
  4859. } else {
  4860. usableData = data.slice(0, nextBoundary);
  4861. this.leftOver = data.slice(nextBoundary, data.length);
  4862. }
  4863. }
  4864. this.push({
  4865. data : exports.utf8decode(usableData),
  4866. meta : chunk.meta
  4867. });
  4868. };
  4869. /**
  4870. * @see GenericWorker.flush
  4871. */
  4872. Utf8DecodeWorker.prototype.flush = function () {
  4873. if(this.leftOver && this.leftOver.length) {
  4874. this.push({
  4875. data : exports.utf8decode(this.leftOver),
  4876. meta : {}
  4877. });
  4878. this.leftOver = null;
  4879. }
  4880. };
  4881. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  4882. /**
  4883. * A worker to endcode string chunks into utf8 encoded binary chunks.
  4884. * @constructor
  4885. */
  4886. function Utf8EncodeWorker() {
  4887. GenericWorker.call(this, "utf-8 encode");
  4888. }
  4889. utils.inherits(Utf8EncodeWorker, GenericWorker);
  4890. /**
  4891. * @see GenericWorker.processChunk
  4892. */
  4893. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  4894. this.push({
  4895. data : exports.utf8encode(chunk.data),
  4896. meta : chunk.meta
  4897. });
  4898. };
  4899. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  4900. },{"./nodejsUtils":23,"./stream/GenericWorker":39,"./support":41,"./utils":43}],43:[function(require,module,exports){
  4901. 'use strict';
  4902. var support = require('./support');
  4903. var base64 = require('./base64');
  4904. var nodejsUtils = require('./nodejsUtils');
  4905. var setImmediate = require('set-immediate-shim');
  4906. var external = require("./external");
  4907. /**
  4908. * Convert a string that pass as a "binary string": it should represent a byte
  4909. * array but may have > 255 char codes. Be sure to take only the first byte
  4910. * and returns the byte array.
  4911. * @param {String} str the string to transform.
  4912. * @return {Array|Uint8Array} the string in a binary format.
  4913. */
  4914. function string2binary(str) {
  4915. var result = null;
  4916. if (support.uint8array) {
  4917. result = new Uint8Array(str.length);
  4918. } else {
  4919. result = new Array(str.length);
  4920. }
  4921. return stringToArrayLike(str, result);
  4922. }
  4923. /**
  4924. * Create a new blob with the given content and the given type.
  4925. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  4926. * an Uint8Array because the stock browser of android 4 won't accept it (it
  4927. * will be silently converted to a string, "[object Uint8Array]").
  4928. *
  4929. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  4930. * when a large amount of Array is used to create the Blob, the amount of
  4931. * memory consumed is nearly 100 times the original data amount.
  4932. *
  4933. * @param {String} type the mime type of the blob.
  4934. * @return {Blob} the created blob.
  4935. */
  4936. exports.newBlob = function(part, type) {
  4937. exports.checkSupport("blob");
  4938. try {
  4939. // Blob constructor
  4940. return new Blob([part], {
  4941. type: type
  4942. });
  4943. }
  4944. catch (e) {
  4945. try {
  4946. // deprecated, browser only, old way
  4947. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  4948. var builder = new Builder();
  4949. builder.append(part);
  4950. return builder.getBlob(type);
  4951. }
  4952. catch (e) {
  4953. // well, fuck ?!
  4954. throw new Error("Bug : can't construct the Blob.");
  4955. }
  4956. }
  4957. };
  4958. /**
  4959. * The identity function.
  4960. * @param {Object} input the input.
  4961. * @return {Object} the same input.
  4962. */
  4963. function identity(input) {
  4964. return input;
  4965. }
  4966. /**
  4967. * Fill in an array with a string.
  4968. * @param {String} str the string to use.
  4969. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  4970. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  4971. */
  4972. function stringToArrayLike(str, array) {
  4973. for (var i = 0; i < str.length; ++i) {
  4974. array[i] = str.charCodeAt(i) & 0xFF;
  4975. }
  4976. return array;
  4977. }
  4978. /**
  4979. * An helper for the function arrayLikeToString.
  4980. * This contains static information and functions that
  4981. * can be optimized by the browser JIT compiler.
  4982. */
  4983. var arrayToStringHelper = {
  4984. /**
  4985. * Transform an array of int into a string, chunk by chunk.
  4986. * See the performances notes on arrayLikeToString.
  4987. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  4988. * @param {String} type the type of the array.
  4989. * @param {Integer} chunk the chunk size.
  4990. * @return {String} the resulting string.
  4991. * @throws Error if the chunk is too big for the stack.
  4992. */
  4993. stringifyByChunk: function(array, type, chunk) {
  4994. var result = [], k = 0, len = array.length;
  4995. // shortcut
  4996. if (len <= chunk) {
  4997. return String.fromCharCode.apply(null, array);
  4998. }
  4999. while (k < len) {
  5000. if (type === "array" || type === "nodebuffer") {
  5001. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  5002. }
  5003. else {
  5004. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  5005. }
  5006. k += chunk;
  5007. }
  5008. return result.join("");
  5009. },
  5010. /**
  5011. * Call String.fromCharCode on every item in the array.
  5012. * This is the naive implementation, which generate A LOT of intermediate string.
  5013. * This should be used when everything else fail.
  5014. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  5015. * @return {String} the result.
  5016. */
  5017. stringifyByChar: function(array){
  5018. var resultStr = "";
  5019. for(var i = 0; i < array.length; i++) {
  5020. resultStr += String.fromCharCode(array[i]);
  5021. }
  5022. return resultStr;
  5023. },
  5024. applyCanBeUsed : {
  5025. /**
  5026. * true if the browser accepts to use String.fromCharCode on Uint8Array
  5027. */
  5028. uint8array : (function () {
  5029. try {
  5030. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  5031. } catch (e) {
  5032. return false;
  5033. }
  5034. })(),
  5035. /**
  5036. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  5037. */
  5038. nodebuffer : (function () {
  5039. try {
  5040. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  5041. } catch (e) {
  5042. return false;
  5043. }
  5044. })()
  5045. }
  5046. };
  5047. /**
  5048. * Transform an array-like object to a string.
  5049. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  5050. * @return {String} the result.
  5051. */
  5052. function arrayLikeToString(array) {
  5053. // Performances notes :
  5054. // --------------------
  5055. // String.fromCharCode.apply(null, array) is the fastest, see
  5056. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  5057. // but the stack is limited (and we can get huge arrays !).
  5058. //
  5059. // result += String.fromCharCode(array[i]); generate too many strings !
  5060. //
  5061. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  5062. // TODO : we now have workers that split the work. Do we still need that ?
  5063. var chunk = 65536,
  5064. type = exports.getTypeOf(array),
  5065. canUseApply = true;
  5066. if (type === "uint8array") {
  5067. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  5068. } else if (type === "nodebuffer") {
  5069. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  5070. }
  5071. if (canUseApply) {
  5072. while (chunk > 1) {
  5073. try {
  5074. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  5075. } catch (e) {
  5076. chunk = Math.floor(chunk / 2);
  5077. }
  5078. }
  5079. }
  5080. // no apply or chunk error : slow and painful algorithm
  5081. // default browser on android 4.*
  5082. return arrayToStringHelper.stringifyByChar(array);
  5083. }
  5084. exports.applyFromCharCode = arrayLikeToString;
  5085. /**
  5086. * Copy the data from an array-like to an other array-like.
  5087. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  5088. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  5089. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  5090. */
  5091. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  5092. for (var i = 0; i < arrayFrom.length; i++) {
  5093. arrayTo[i] = arrayFrom[i];
  5094. }
  5095. return arrayTo;
  5096. }
  5097. // a matrix containing functions to transform everything into everything.
  5098. var transform = {};
  5099. // string to ?
  5100. transform["string"] = {
  5101. "string": identity,
  5102. "array": function(input) {
  5103. return stringToArrayLike(input, new Array(input.length));
  5104. },
  5105. "arraybuffer": function(input) {
  5106. return transform["string"]["uint8array"](input).buffer;
  5107. },
  5108. "uint8array": function(input) {
  5109. return stringToArrayLike(input, new Uint8Array(input.length));
  5110. },
  5111. "nodebuffer": function(input) {
  5112. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  5113. }
  5114. };
  5115. // array to ?
  5116. transform["array"] = {
  5117. "string": arrayLikeToString,
  5118. "array": identity,
  5119. "arraybuffer": function(input) {
  5120. return (new Uint8Array(input)).buffer;
  5121. },
  5122. "uint8array": function(input) {
  5123. return new Uint8Array(input);
  5124. },
  5125. "nodebuffer": function(input) {
  5126. return nodejsUtils.newBufferFrom(input);
  5127. }
  5128. };
  5129. // arraybuffer to ?
  5130. transform["arraybuffer"] = {
  5131. "string": function(input) {
  5132. return arrayLikeToString(new Uint8Array(input));
  5133. },
  5134. "array": function(input) {
  5135. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  5136. },
  5137. "arraybuffer": identity,
  5138. "uint8array": function(input) {
  5139. return new Uint8Array(input);
  5140. },
  5141. "nodebuffer": function(input) {
  5142. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  5143. }
  5144. };
  5145. // uint8array to ?
  5146. transform["uint8array"] = {
  5147. "string": arrayLikeToString,
  5148. "array": function(input) {
  5149. return arrayLikeToArrayLike(input, new Array(input.length));
  5150. },
  5151. "arraybuffer": function(input) {
  5152. return input.buffer;
  5153. },
  5154. "uint8array": identity,
  5155. "nodebuffer": function(input) {
  5156. return nodejsUtils.newBufferFrom(input);
  5157. }
  5158. };
  5159. // nodebuffer to ?
  5160. transform["nodebuffer"] = {
  5161. "string": arrayLikeToString,
  5162. "array": function(input) {
  5163. return arrayLikeToArrayLike(input, new Array(input.length));
  5164. },
  5165. "arraybuffer": function(input) {
  5166. return transform["nodebuffer"]["uint8array"](input).buffer;
  5167. },
  5168. "uint8array": function(input) {
  5169. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  5170. },
  5171. "nodebuffer": identity
  5172. };
  5173. /**
  5174. * Transform an input into any type.
  5175. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  5176. * If no output type is specified, the unmodified input will be returned.
  5177. * @param {String} outputType the output type.
  5178. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  5179. * @throws {Error} an Error if the browser doesn't support the requested output type.
  5180. */
  5181. exports.transformTo = function(outputType, input) {
  5182. if (!input) {
  5183. // undefined, null, etc
  5184. // an empty string won't harm.
  5185. input = "";
  5186. }
  5187. if (!outputType) {
  5188. return input;
  5189. }
  5190. exports.checkSupport(outputType);
  5191. var inputType = exports.getTypeOf(input);
  5192. var result = transform[inputType][outputType](input);
  5193. return result;
  5194. };
  5195. /**
  5196. * Return the type of the input.
  5197. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  5198. * @param {Object} input the input to identify.
  5199. * @return {String} the (lowercase) type of the input.
  5200. */
  5201. exports.getTypeOf = function(input) {
  5202. if (typeof input === "string") {
  5203. return "string";
  5204. }
  5205. if (Object.prototype.toString.call(input) === "[object Array]") {
  5206. return "array";
  5207. }
  5208. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  5209. return "nodebuffer";
  5210. }
  5211. if (support.uint8array && input instanceof Uint8Array) {
  5212. return "uint8array";
  5213. }
  5214. if (support.arraybuffer && input instanceof ArrayBuffer) {
  5215. return "arraybuffer";
  5216. }
  5217. };
  5218. /**
  5219. * Throw an exception if the type is not supported.
  5220. * @param {String} type the type to check.
  5221. * @throws {Error} an Error if the browser doesn't support the requested type.
  5222. */
  5223. exports.checkSupport = function(type) {
  5224. var supported = support[type.toLowerCase()];
  5225. if (!supported) {
  5226. throw new Error(type + " is not supported by this platform");
  5227. }
  5228. };
  5229. exports.MAX_VALUE_16BITS = 65535;
  5230. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  5231. /**
  5232. * Prettify a string read as binary.
  5233. * @param {string} str the string to prettify.
  5234. * @return {string} a pretty string.
  5235. */
  5236. exports.pretty = function(str) {
  5237. var res = '',
  5238. code, i;
  5239. for (i = 0; i < (str || "").length; i++) {
  5240. code = str.charCodeAt(i);
  5241. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  5242. }
  5243. return res;
  5244. };
  5245. /**
  5246. * Defer the call of a function.
  5247. * @param {Function} callback the function to call asynchronously.
  5248. * @param {Array} args the arguments to give to the callback.
  5249. */
  5250. exports.delay = function(callback, args, self) {
  5251. setImmediate(function () {
  5252. callback.apply(self || null, args || []);
  5253. });
  5254. };
  5255. /**
  5256. * Extends a prototype with an other, without calling a constructor with
  5257. * side effects. Inspired by nodejs' `utils.inherits`
  5258. * @param {Function} ctor the constructor to augment
  5259. * @param {Function} superCtor the parent constructor to use
  5260. */
  5261. exports.inherits = function (ctor, superCtor) {
  5262. var Obj = function() {};
  5263. Obj.prototype = superCtor.prototype;
  5264. ctor.prototype = new Obj();
  5265. };
  5266. /**
  5267. * Merge the objects passed as parameters into a new one.
  5268. * @private
  5269. * @param {...Object} var_args All objects to merge.
  5270. * @return {Object} a new object with the data of the others.
  5271. */
  5272. exports.extend = function() {
  5273. var result = {}, i, attr;
  5274. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  5275. for (attr in arguments[i]) {
  5276. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  5277. result[attr] = arguments[i][attr];
  5278. }
  5279. }
  5280. }
  5281. return result;
  5282. };
  5283. /**
  5284. * Transform arbitrary content into a Promise.
  5285. * @param {String} name a name for the content being processed.
  5286. * @param {Object} inputData the content to process.
  5287. * @param {Boolean} isBinary true if the content is not an unicode string
  5288. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  5289. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  5290. * @return {Promise} a promise in a format usable by JSZip.
  5291. */
  5292. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  5293. // if inputData is already a promise, this flatten it.
  5294. var promise = external.Promise.resolve(inputData).then(function(data) {
  5295. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  5296. if (isBlob && typeof FileReader !== "undefined") {
  5297. return new external.Promise(function (resolve, reject) {
  5298. var reader = new FileReader();
  5299. reader.onload = function(e) {
  5300. resolve(e.target.result);
  5301. };
  5302. reader.onerror = function(e) {
  5303. reject(e.target.error);
  5304. };
  5305. reader.readAsArrayBuffer(data);
  5306. });
  5307. } else {
  5308. return data;
  5309. }
  5310. });
  5311. return promise.then(function(data) {
  5312. var dataType = exports.getTypeOf(data);
  5313. if (!dataType) {
  5314. return external.Promise.reject(
  5315. new Error("Can't read the data of '" + name + "'. Is it " +
  5316. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  5317. );
  5318. }
  5319. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  5320. if (dataType === "arraybuffer") {
  5321. data = exports.transformTo("uint8array", data);
  5322. } else if (dataType === "string") {
  5323. if (isBase64) {
  5324. data = base64.decode(data);
  5325. }
  5326. else if (isBinary) {
  5327. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  5328. if (isOptimizedBinaryString !== true) {
  5329. // this is a string, not in a base64 format.
  5330. // Be sure that this is a correct "binary string"
  5331. data = string2binary(data);
  5332. }
  5333. }
  5334. }
  5335. return data;
  5336. });
  5337. };
  5338. },{"./base64":12,"./external":17,"./nodejsUtils":23,"./support":41,"set-immediate-shim":80}],44:[function(require,module,exports){
  5339. 'use strict';
  5340. var readerFor = require('./reader/readerFor');
  5341. var utils = require('./utils');
  5342. var sig = require('./signature');
  5343. var ZipEntry = require('./zipEntry');
  5344. var utf8 = require('./utf8');
  5345. var support = require('./support');
  5346. // class ZipEntries {{{
  5347. /**
  5348. * All the entries in the zip file.
  5349. * @constructor
  5350. * @param {Object} loadOptions Options for loading the stream.
  5351. */
  5352. function ZipEntries(loadOptions) {
  5353. this.files = [];
  5354. this.loadOptions = loadOptions;
  5355. }
  5356. ZipEntries.prototype = {
  5357. /**
  5358. * Check that the reader is on the specified signature.
  5359. * @param {string} expectedSignature the expected signature.
  5360. * @throws {Error} if it is an other signature.
  5361. */
  5362. checkSignature: function(expectedSignature) {
  5363. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  5364. this.reader.index -= 4;
  5365. var signature = this.reader.readString(4);
  5366. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  5367. }
  5368. },
  5369. /**
  5370. * Check if the given signature is at the given index.
  5371. * @param {number} askedIndex the index to check.
  5372. * @param {string} expectedSignature the signature to expect.
  5373. * @return {boolean} true if the signature is here, false otherwise.
  5374. */
  5375. isSignature: function(askedIndex, expectedSignature) {
  5376. var currentIndex = this.reader.index;
  5377. this.reader.setIndex(askedIndex);
  5378. var signature = this.reader.readString(4);
  5379. var result = signature === expectedSignature;
  5380. this.reader.setIndex(currentIndex);
  5381. return result;
  5382. },
  5383. /**
  5384. * Read the end of the central directory.
  5385. */
  5386. readBlockEndOfCentral: function() {
  5387. this.diskNumber = this.reader.readInt(2);
  5388. this.diskWithCentralDirStart = this.reader.readInt(2);
  5389. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  5390. this.centralDirRecords = this.reader.readInt(2);
  5391. this.centralDirSize = this.reader.readInt(4);
  5392. this.centralDirOffset = this.reader.readInt(4);
  5393. this.zipCommentLength = this.reader.readInt(2);
  5394. // warning : the encoding depends of the system locale
  5395. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  5396. // On a windows machine, this field is encoded with the localized windows code page.
  5397. var zipComment = this.reader.readData(this.zipCommentLength);
  5398. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5399. // To get consistent behavior with the generation part, we will assume that
  5400. // this is utf8 encoded unless specified otherwise.
  5401. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  5402. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  5403. },
  5404. /**
  5405. * Read the end of the Zip 64 central directory.
  5406. * Not merged with the method readEndOfCentral :
  5407. * The end of central can coexist with its Zip64 brother,
  5408. * I don't want to read the wrong number of bytes !
  5409. */
  5410. readBlockZip64EndOfCentral: function() {
  5411. this.zip64EndOfCentralSize = this.reader.readInt(8);
  5412. this.reader.skip(4);
  5413. // this.versionMadeBy = this.reader.readString(2);
  5414. // this.versionNeeded = this.reader.readInt(2);
  5415. this.diskNumber = this.reader.readInt(4);
  5416. this.diskWithCentralDirStart = this.reader.readInt(4);
  5417. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  5418. this.centralDirRecords = this.reader.readInt(8);
  5419. this.centralDirSize = this.reader.readInt(8);
  5420. this.centralDirOffset = this.reader.readInt(8);
  5421. this.zip64ExtensibleData = {};
  5422. var extraDataSize = this.zip64EndOfCentralSize - 44,
  5423. index = 0,
  5424. extraFieldId,
  5425. extraFieldLength,
  5426. extraFieldValue;
  5427. while (index < extraDataSize) {
  5428. extraFieldId = this.reader.readInt(2);
  5429. extraFieldLength = this.reader.readInt(4);
  5430. extraFieldValue = this.reader.readData(extraFieldLength);
  5431. this.zip64ExtensibleData[extraFieldId] = {
  5432. id: extraFieldId,
  5433. length: extraFieldLength,
  5434. value: extraFieldValue
  5435. };
  5436. }
  5437. },
  5438. /**
  5439. * Read the end of the Zip 64 central directory locator.
  5440. */
  5441. readBlockZip64EndOfCentralLocator: function() {
  5442. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  5443. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  5444. this.disksCount = this.reader.readInt(4);
  5445. if (this.disksCount > 1) {
  5446. throw new Error("Multi-volumes zip are not supported");
  5447. }
  5448. },
  5449. /**
  5450. * Read the local files, based on the offset read in the central part.
  5451. */
  5452. readLocalFiles: function() {
  5453. var i, file;
  5454. for (i = 0; i < this.files.length; i++) {
  5455. file = this.files[i];
  5456. this.reader.setIndex(file.localHeaderOffset);
  5457. this.checkSignature(sig.LOCAL_FILE_HEADER);
  5458. file.readLocalPart(this.reader);
  5459. file.handleUTF8();
  5460. file.processAttributes();
  5461. }
  5462. },
  5463. /**
  5464. * Read the central directory.
  5465. */
  5466. readCentralDir: function() {
  5467. var file;
  5468. this.reader.setIndex(this.centralDirOffset);
  5469. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  5470. file = new ZipEntry({
  5471. zip64: this.zip64
  5472. }, this.loadOptions);
  5473. file.readCentralPart(this.reader);
  5474. this.files.push(file);
  5475. }
  5476. if (this.centralDirRecords !== this.files.length) {
  5477. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  5478. // We expected some records but couldn't find ANY.
  5479. // This is really suspicious, as if something went wrong.
  5480. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  5481. } else {
  5482. // We found some records but not all.
  5483. // Something is wrong but we got something for the user: no error here.
  5484. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  5485. }
  5486. }
  5487. },
  5488. /**
  5489. * Read the end of central directory.
  5490. */
  5491. readEndOfCentral: function() {
  5492. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  5493. if (offset < 0) {
  5494. // Check if the content is a truncated zip or complete garbage.
  5495. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  5496. // extractible zip for example) but it can give a good hint.
  5497. // If an ajax request was used without responseType, we will also
  5498. // get unreadable data.
  5499. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  5500. if (isGarbage) {
  5501. throw new Error("Can't find end of central directory : is this a zip file ? " +
  5502. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  5503. } else {
  5504. throw new Error("Corrupted zip: can't find end of central directory");
  5505. }
  5506. }
  5507. this.reader.setIndex(offset);
  5508. var endOfCentralDirOffset = offset;
  5509. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  5510. this.readBlockEndOfCentral();
  5511. /* extract from the zip spec :
  5512. 4) If one of the fields in the end of central directory
  5513. record is too small to hold required data, the field
  5514. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  5515. ZIP64 format record should be created.
  5516. 5) The end of central directory record and the
  5517. Zip64 end of central directory locator record must
  5518. reside on the same disk when splitting or spanning
  5519. an archive.
  5520. */
  5521. 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) {
  5522. this.zip64 = true;
  5523. /*
  5524. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  5525. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  5526. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  5527. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  5528. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  5529. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  5530. */
  5531. // should look for a zip64 EOCD locator
  5532. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5533. if (offset < 0) {
  5534. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  5535. }
  5536. this.reader.setIndex(offset);
  5537. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5538. this.readBlockZip64EndOfCentralLocator();
  5539. // now the zip64 EOCD record
  5540. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  5541. // console.warn("ZIP64 end of central directory not where expected.");
  5542. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5543. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  5544. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  5545. }
  5546. }
  5547. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  5548. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5549. this.readBlockZip64EndOfCentral();
  5550. }
  5551. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  5552. if (this.zip64) {
  5553. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  5554. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  5555. }
  5556. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  5557. if (extraBytes > 0) {
  5558. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  5559. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  5560. // The offsets seem wrong, but we have something at the specified offset.
  5561. // So… we keep it.
  5562. } else {
  5563. // the offset is wrong, update the "zero" of the reader
  5564. // this happens if data has been prepended (crx files for example)
  5565. this.reader.zero = extraBytes;
  5566. }
  5567. } else if (extraBytes < 0) {
  5568. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  5569. }
  5570. },
  5571. prepareReader: function(data) {
  5572. this.reader = readerFor(data);
  5573. },
  5574. /**
  5575. * Read a zip file and create ZipEntries.
  5576. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  5577. */
  5578. load: function(data) {
  5579. this.prepareReader(data);
  5580. this.readEndOfCentral();
  5581. this.readCentralDir();
  5582. this.readLocalFiles();
  5583. }
  5584. };
  5585. // }}} end of ZipEntries
  5586. module.exports = ZipEntries;
  5587. },{"./reader/readerFor":33,"./signature":34,"./support":41,"./utf8":42,"./utils":43,"./zipEntry":45}],45:[function(require,module,exports){
  5588. 'use strict';
  5589. var readerFor = require('./reader/readerFor');
  5590. var utils = require('./utils');
  5591. var CompressedObject = require('./compressedObject');
  5592. var crc32fn = require('./crc32');
  5593. var utf8 = require('./utf8');
  5594. var compressions = require('./compressions');
  5595. var support = require('./support');
  5596. var MADE_BY_DOS = 0x00;
  5597. var MADE_BY_UNIX = 0x03;
  5598. /**
  5599. * Find a compression registered in JSZip.
  5600. * @param {string} compressionMethod the method magic to find.
  5601. * @return {Object|null} the JSZip compression object, null if none found.
  5602. */
  5603. var findCompression = function(compressionMethod) {
  5604. for (var method in compressions) {
  5605. if (!compressions.hasOwnProperty(method)) {
  5606. continue;
  5607. }
  5608. if (compressions[method].magic === compressionMethod) {
  5609. return compressions[method];
  5610. }
  5611. }
  5612. return null;
  5613. };
  5614. // class ZipEntry {{{
  5615. /**
  5616. * An entry in the zip file.
  5617. * @constructor
  5618. * @param {Object} options Options of the current file.
  5619. * @param {Object} loadOptions Options for loading the stream.
  5620. */
  5621. function ZipEntry(options, loadOptions) {
  5622. this.options = options;
  5623. this.loadOptions = loadOptions;
  5624. }
  5625. ZipEntry.prototype = {
  5626. /**
  5627. * say if the file is encrypted.
  5628. * @return {boolean} true if the file is encrypted, false otherwise.
  5629. */
  5630. isEncrypted: function() {
  5631. // bit 1 is set
  5632. return (this.bitFlag & 0x0001) === 0x0001;
  5633. },
  5634. /**
  5635. * say if the file has utf-8 filename/comment.
  5636. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  5637. */
  5638. useUTF8: function() {
  5639. // bit 11 is set
  5640. return (this.bitFlag & 0x0800) === 0x0800;
  5641. },
  5642. /**
  5643. * Read the local part of a zip file and add the info in this object.
  5644. * @param {DataReader} reader the reader to use.
  5645. */
  5646. readLocalPart: function(reader) {
  5647. var compression, localExtraFieldsLength;
  5648. // we already know everything from the central dir !
  5649. // If the central dir data are false, we are doomed.
  5650. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  5651. // The less data we get here, the more reliable this should be.
  5652. // Let's skip the whole header and dash to the data !
  5653. reader.skip(22);
  5654. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  5655. // Strangely, the filename here is OK.
  5656. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  5657. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  5658. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  5659. // the internet.
  5660. //
  5661. // I think I see the logic here : the central directory is used to display
  5662. // content and the local directory is used to extract the files. Mixing / and \
  5663. // may be used to display \ to windows users and use / when extracting the files.
  5664. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  5665. this.fileNameLength = reader.readInt(2);
  5666. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  5667. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  5668. this.fileName = reader.readData(this.fileNameLength);
  5669. reader.skip(localExtraFieldsLength);
  5670. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  5671. throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  5672. }
  5673. compression = findCompression(this.compressionMethod);
  5674. if (compression === null) { // no compression found
  5675. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  5676. }
  5677. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  5678. },
  5679. /**
  5680. * Read the central part of a zip file and add the info in this object.
  5681. * @param {DataReader} reader the reader to use.
  5682. */
  5683. readCentralPart: function(reader) {
  5684. this.versionMadeBy = reader.readInt(2);
  5685. reader.skip(2);
  5686. // this.versionNeeded = reader.readInt(2);
  5687. this.bitFlag = reader.readInt(2);
  5688. this.compressionMethod = reader.readString(2);
  5689. this.date = reader.readDate();
  5690. this.crc32 = reader.readInt(4);
  5691. this.compressedSize = reader.readInt(4);
  5692. this.uncompressedSize = reader.readInt(4);
  5693. var fileNameLength = reader.readInt(2);
  5694. this.extraFieldsLength = reader.readInt(2);
  5695. this.fileCommentLength = reader.readInt(2);
  5696. this.diskNumberStart = reader.readInt(2);
  5697. this.internalFileAttributes = reader.readInt(2);
  5698. this.externalFileAttributes = reader.readInt(4);
  5699. this.localHeaderOffset = reader.readInt(4);
  5700. if (this.isEncrypted()) {
  5701. throw new Error("Encrypted zip are not supported");
  5702. }
  5703. // will be read in the local part, see the comments there
  5704. reader.skip(fileNameLength);
  5705. this.readExtraFields(reader);
  5706. this.parseZIP64ExtraField(reader);
  5707. this.fileComment = reader.readData(this.fileCommentLength);
  5708. },
  5709. /**
  5710. * Parse the external file attributes and get the unix/dos permissions.
  5711. */
  5712. processAttributes: function () {
  5713. this.unixPermissions = null;
  5714. this.dosPermissions = null;
  5715. var madeBy = this.versionMadeBy >> 8;
  5716. // Check if we have the DOS directory flag set.
  5717. // We look for it in the DOS and UNIX permissions
  5718. // but some unknown platform could set it as a compatibility flag.
  5719. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  5720. if(madeBy === MADE_BY_DOS) {
  5721. // first 6 bits (0 to 5)
  5722. this.dosPermissions = this.externalFileAttributes & 0x3F;
  5723. }
  5724. if(madeBy === MADE_BY_UNIX) {
  5725. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  5726. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  5727. }
  5728. // fail safe : if the name ends with a / it probably means a folder
  5729. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  5730. this.dir = true;
  5731. }
  5732. },
  5733. /**
  5734. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  5735. * @param {DataReader} reader the reader to use.
  5736. */
  5737. parseZIP64ExtraField: function(reader) {
  5738. if (!this.extraFields[0x0001]) {
  5739. return;
  5740. }
  5741. // should be something, preparing the extra reader
  5742. var extraReader = readerFor(this.extraFields[0x0001].value);
  5743. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  5744. // won't let us have more.
  5745. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  5746. this.uncompressedSize = extraReader.readInt(8);
  5747. }
  5748. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  5749. this.compressedSize = extraReader.readInt(8);
  5750. }
  5751. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  5752. this.localHeaderOffset = extraReader.readInt(8);
  5753. }
  5754. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  5755. this.diskNumberStart = extraReader.readInt(4);
  5756. }
  5757. },
  5758. /**
  5759. * Read the central part of a zip file and add the info in this object.
  5760. * @param {DataReader} reader the reader to use.
  5761. */
  5762. readExtraFields: function(reader) {
  5763. var end = reader.index + this.extraFieldsLength,
  5764. extraFieldId,
  5765. extraFieldLength,
  5766. extraFieldValue;
  5767. if (!this.extraFields) {
  5768. this.extraFields = {};
  5769. }
  5770. while (reader.index + 4 < end) {
  5771. extraFieldId = reader.readInt(2);
  5772. extraFieldLength = reader.readInt(2);
  5773. extraFieldValue = reader.readData(extraFieldLength);
  5774. this.extraFields[extraFieldId] = {
  5775. id: extraFieldId,
  5776. length: extraFieldLength,
  5777. value: extraFieldValue
  5778. };
  5779. }
  5780. reader.setIndex(end);
  5781. },
  5782. /**
  5783. * Apply an UTF8 transformation if needed.
  5784. */
  5785. handleUTF8: function() {
  5786. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5787. if (this.useUTF8()) {
  5788. this.fileNameStr = utf8.utf8decode(this.fileName);
  5789. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  5790. } else {
  5791. var upath = this.findExtraFieldUnicodePath();
  5792. if (upath !== null) {
  5793. this.fileNameStr = upath;
  5794. } else {
  5795. // ASCII text or unsupported code page
  5796. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  5797. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  5798. }
  5799. var ucomment = this.findExtraFieldUnicodeComment();
  5800. if (ucomment !== null) {
  5801. this.fileCommentStr = ucomment;
  5802. } else {
  5803. // ASCII text or unsupported code page
  5804. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  5805. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  5806. }
  5807. }
  5808. },
  5809. /**
  5810. * Find the unicode path declared in the extra field, if any.
  5811. * @return {String} the unicode path, null otherwise.
  5812. */
  5813. findExtraFieldUnicodePath: function() {
  5814. var upathField = this.extraFields[0x7075];
  5815. if (upathField) {
  5816. var extraReader = readerFor(upathField.value);
  5817. // wrong version
  5818. if (extraReader.readInt(1) !== 1) {
  5819. return null;
  5820. }
  5821. // the crc of the filename changed, this field is out of date.
  5822. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  5823. return null;
  5824. }
  5825. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  5826. }
  5827. return null;
  5828. },
  5829. /**
  5830. * Find the unicode comment declared in the extra field, if any.
  5831. * @return {String} the unicode comment, null otherwise.
  5832. */
  5833. findExtraFieldUnicodeComment: function() {
  5834. var ucommentField = this.extraFields[0x6375];
  5835. if (ucommentField) {
  5836. var extraReader = readerFor(ucommentField.value);
  5837. // wrong version
  5838. if (extraReader.readInt(1) !== 1) {
  5839. return null;
  5840. }
  5841. // the crc of the comment changed, this field is out of date.
  5842. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  5843. return null;
  5844. }
  5845. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  5846. }
  5847. return null;
  5848. }
  5849. };
  5850. module.exports = ZipEntry;
  5851. },{"./compressedObject":13,"./compressions":14,"./crc32":15,"./reader/readerFor":33,"./support":41,"./utf8":42,"./utils":43}],46:[function(require,module,exports){
  5852. 'use strict';
  5853. var StreamHelper = require('./stream/StreamHelper');
  5854. var DataWorker = require('./stream/DataWorker');
  5855. var utf8 = require('./utf8');
  5856. var CompressedObject = require('./compressedObject');
  5857. var GenericWorker = require('./stream/GenericWorker');
  5858. /**
  5859. * A simple object representing a file in the zip file.
  5860. * @constructor
  5861. * @param {string} name the name of the file
  5862. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  5863. * @param {Object} options the options of the file
  5864. */
  5865. var ZipObject = function(name, data, options) {
  5866. this.name = name;
  5867. this.dir = options.dir;
  5868. this.date = options.date;
  5869. this.comment = options.comment;
  5870. this.unixPermissions = options.unixPermissions;
  5871. this.dosPermissions = options.dosPermissions;
  5872. this._data = data;
  5873. this._dataBinary = options.binary;
  5874. // keep only the compression
  5875. this.options = {
  5876. compression : options.compression,
  5877. compressionOptions : options.compressionOptions
  5878. };
  5879. };
  5880. ZipObject.prototype = {
  5881. /**
  5882. * Create an internal stream for the content of this object.
  5883. * @param {String} type the type of each chunk.
  5884. * @return StreamHelper the stream.
  5885. */
  5886. internalStream: function (type) {
  5887. var result = null, outputType = "string";
  5888. try {
  5889. if (!type) {
  5890. throw new Error("No output type specified.");
  5891. }
  5892. outputType = type.toLowerCase();
  5893. var askUnicodeString = outputType === "string" || outputType === "text";
  5894. if (outputType === "binarystring" || outputType === "text") {
  5895. outputType = "string";
  5896. }
  5897. result = this._decompressWorker();
  5898. var isUnicodeString = !this._dataBinary;
  5899. if (isUnicodeString && !askUnicodeString) {
  5900. result = result.pipe(new utf8.Utf8EncodeWorker());
  5901. }
  5902. if (!isUnicodeString && askUnicodeString) {
  5903. result = result.pipe(new utf8.Utf8DecodeWorker());
  5904. }
  5905. } catch (e) {
  5906. result = new GenericWorker("error");
  5907. result.error(e);
  5908. }
  5909. return new StreamHelper(result, outputType, "");
  5910. },
  5911. /**
  5912. * Prepare the content in the asked type.
  5913. * @param {String} type the type of the result.
  5914. * @param {Function} onUpdate a function to call on each internal update.
  5915. * @return Promise the promise of the result.
  5916. */
  5917. async: function (type, onUpdate) {
  5918. return this.internalStream(type).accumulate(onUpdate);
  5919. },
  5920. /**
  5921. * Prepare the content as a nodejs stream.
  5922. * @param {String} type the type of each chunk.
  5923. * @param {Function} onUpdate a function to call on each internal update.
  5924. * @return Stream the stream.
  5925. */
  5926. nodeStream: function (type, onUpdate) {
  5927. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  5928. },
  5929. /**
  5930. * Return a worker for the compressed content.
  5931. * @private
  5932. * @param {Object} compression the compression object to use.
  5933. * @param {Object} compressionOptions the options to use when compressing.
  5934. * @return Worker the worker.
  5935. */
  5936. _compressWorker: function (compression, compressionOptions) {
  5937. if (
  5938. this._data instanceof CompressedObject &&
  5939. this._data.compression.magic === compression.magic
  5940. ) {
  5941. return this._data.getCompressedWorker();
  5942. } else {
  5943. var result = this._decompressWorker();
  5944. if(!this._dataBinary) {
  5945. result = result.pipe(new utf8.Utf8EncodeWorker());
  5946. }
  5947. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  5948. }
  5949. },
  5950. /**
  5951. * Return a worker for the decompressed content.
  5952. * @private
  5953. * @return Worker the worker.
  5954. */
  5955. _decompressWorker : function () {
  5956. if (this._data instanceof CompressedObject) {
  5957. return this._data.getContentWorker();
  5958. } else if (this._data instanceof GenericWorker) {
  5959. return this._data;
  5960. } else {
  5961. return new DataWorker(this._data);
  5962. }
  5963. }
  5964. };
  5965. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  5966. var removedFn = function () {
  5967. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  5968. };
  5969. for(var i = 0; i < removedMethods.length; i++) {
  5970. ZipObject.prototype[removedMethods[i]] = removedFn;
  5971. }
  5972. module.exports = ZipObject;
  5973. },{"./compressedObject":13,"./stream/DataWorker":38,"./stream/GenericWorker":39,"./stream/StreamHelper":40,"./utf8":42}],47:[function(require,module,exports){
  5974. 'use strict';
  5975. var immediate = require('immediate');
  5976. /* istanbul ignore next */
  5977. function INTERNAL() {}
  5978. var handlers = {};
  5979. var REJECTED = ['REJECTED'];
  5980. var FULFILLED = ['FULFILLED'];
  5981. var PENDING = ['PENDING'];
  5982. module.exports = Promise;
  5983. function Promise(resolver) {
  5984. if (typeof resolver !== 'function') {
  5985. throw new TypeError('resolver must be a function');
  5986. }
  5987. this.state = PENDING;
  5988. this.queue = [];
  5989. this.outcome = void 0;
  5990. if (resolver !== INTERNAL) {
  5991. safelyResolveThenable(this, resolver);
  5992. }
  5993. }
  5994. Promise.prototype["finally"] = function (callback) {
  5995. if (typeof callback !== 'function') {
  5996. return this;
  5997. }
  5998. var p = this.constructor;
  5999. return this.then(resolve, reject);
  6000. function resolve(value) {
  6001. function yes () {
  6002. return value;
  6003. }
  6004. return p.resolve(callback()).then(yes);
  6005. }
  6006. function reject(reason) {
  6007. function no () {
  6008. throw reason;
  6009. }
  6010. return p.resolve(callback()).then(no);
  6011. }
  6012. };
  6013. Promise.prototype["catch"] = function (onRejected) {
  6014. return this.then(null, onRejected);
  6015. };
  6016. Promise.prototype.then = function (onFulfilled, onRejected) {
  6017. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  6018. typeof onRejected !== 'function' && this.state === REJECTED) {
  6019. return this;
  6020. }
  6021. var promise = new this.constructor(INTERNAL);
  6022. if (this.state !== PENDING) {
  6023. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  6024. unwrap(promise, resolver, this.outcome);
  6025. } else {
  6026. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  6027. }
  6028. return promise;
  6029. };
  6030. function QueueItem(promise, onFulfilled, onRejected) {
  6031. this.promise = promise;
  6032. if (typeof onFulfilled === 'function') {
  6033. this.onFulfilled = onFulfilled;
  6034. this.callFulfilled = this.otherCallFulfilled;
  6035. }
  6036. if (typeof onRejected === 'function') {
  6037. this.onRejected = onRejected;
  6038. this.callRejected = this.otherCallRejected;
  6039. }
  6040. }
  6041. QueueItem.prototype.callFulfilled = function (value) {
  6042. handlers.resolve(this.promise, value);
  6043. };
  6044. QueueItem.prototype.otherCallFulfilled = function (value) {
  6045. unwrap(this.promise, this.onFulfilled, value);
  6046. };
  6047. QueueItem.prototype.callRejected = function (value) {
  6048. handlers.reject(this.promise, value);
  6049. };
  6050. QueueItem.prototype.otherCallRejected = function (value) {
  6051. unwrap(this.promise, this.onRejected, value);
  6052. };
  6053. function unwrap(promise, func, value) {
  6054. immediate(function () {
  6055. var returnValue;
  6056. try {
  6057. returnValue = func(value);
  6058. } catch (e) {
  6059. return handlers.reject(promise, e);
  6060. }
  6061. if (returnValue === promise) {
  6062. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  6063. } else {
  6064. handlers.resolve(promise, returnValue);
  6065. }
  6066. });
  6067. }
  6068. handlers.resolve = function (self, value) {
  6069. var result = tryCatch(getThen, value);
  6070. if (result.status === 'error') {
  6071. return handlers.reject(self, result.value);
  6072. }
  6073. var thenable = result.value;
  6074. if (thenable) {
  6075. safelyResolveThenable(self, thenable);
  6076. } else {
  6077. self.state = FULFILLED;
  6078. self.outcome = value;
  6079. var i = -1;
  6080. var len = self.queue.length;
  6081. while (++i < len) {
  6082. self.queue[i].callFulfilled(value);
  6083. }
  6084. }
  6085. return self;
  6086. };
  6087. handlers.reject = function (self, error) {
  6088. self.state = REJECTED;
  6089. self.outcome = error;
  6090. var i = -1;
  6091. var len = self.queue.length;
  6092. while (++i < len) {
  6093. self.queue[i].callRejected(error);
  6094. }
  6095. return self;
  6096. };
  6097. function getThen(obj) {
  6098. // Make sure we only access the accessor once as required by the spec
  6099. var then = obj && obj.then;
  6100. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  6101. return function appyThen() {
  6102. then.apply(obj, arguments);
  6103. };
  6104. }
  6105. }
  6106. function safelyResolveThenable(self, thenable) {
  6107. // Either fulfill, reject or reject with error
  6108. var called = false;
  6109. function onError(value) {
  6110. if (called) {
  6111. return;
  6112. }
  6113. called = true;
  6114. handlers.reject(self, value);
  6115. }
  6116. function onSuccess(value) {
  6117. if (called) {
  6118. return;
  6119. }
  6120. called = true;
  6121. handlers.resolve(self, value);
  6122. }
  6123. function tryToUnwrap() {
  6124. thenable(onSuccess, onError);
  6125. }
  6126. var result = tryCatch(tryToUnwrap);
  6127. if (result.status === 'error') {
  6128. onError(result.value);
  6129. }
  6130. }
  6131. function tryCatch(func, value) {
  6132. var out = {};
  6133. try {
  6134. out.value = func(value);
  6135. out.status = 'success';
  6136. } catch (e) {
  6137. out.status = 'error';
  6138. out.value = e;
  6139. }
  6140. return out;
  6141. }
  6142. Promise.resolve = resolve;
  6143. function resolve(value) {
  6144. if (value instanceof this) {
  6145. return value;
  6146. }
  6147. return handlers.resolve(new this(INTERNAL), value);
  6148. }
  6149. Promise.reject = reject;
  6150. function reject(reason) {
  6151. var promise = new this(INTERNAL);
  6152. return handlers.reject(promise, reason);
  6153. }
  6154. Promise.all = all;
  6155. function all(iterable) {
  6156. var self = this;
  6157. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  6158. return this.reject(new TypeError('must be an array'));
  6159. }
  6160. var len = iterable.length;
  6161. var called = false;
  6162. if (!len) {
  6163. return this.resolve([]);
  6164. }
  6165. var values = new Array(len);
  6166. var resolved = 0;
  6167. var i = -1;
  6168. var promise = new this(INTERNAL);
  6169. while (++i < len) {
  6170. allResolver(iterable[i], i);
  6171. }
  6172. return promise;
  6173. function allResolver(value, i) {
  6174. self.resolve(value).then(resolveFromAll, function (error) {
  6175. if (!called) {
  6176. called = true;
  6177. handlers.reject(promise, error);
  6178. }
  6179. });
  6180. function resolveFromAll(outValue) {
  6181. values[i] = outValue;
  6182. if (++resolved === len && !called) {
  6183. called = true;
  6184. handlers.resolve(promise, values);
  6185. }
  6186. }
  6187. }
  6188. }
  6189. Promise.race = race;
  6190. function race(iterable) {
  6191. var self = this;
  6192. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  6193. return this.reject(new TypeError('must be an array'));
  6194. }
  6195. var len = iterable.length;
  6196. var called = false;
  6197. if (!len) {
  6198. return this.resolve([]);
  6199. }
  6200. var i = -1;
  6201. var promise = new this(INTERNAL);
  6202. while (++i < len) {
  6203. resolver(iterable[i]);
  6204. }
  6205. return promise;
  6206. function resolver(value) {
  6207. self.resolve(value).then(function (response) {
  6208. if (!called) {
  6209. called = true;
  6210. handlers.resolve(promise, response);
  6211. }
  6212. }, function (error) {
  6213. if (!called) {
  6214. called = true;
  6215. handlers.reject(promise, error);
  6216. }
  6217. });
  6218. }
  6219. }
  6220. },{"immediate":8}],48:[function(require,module,exports){
  6221. // Top level file is just a mixin of submodules & constants
  6222. 'use strict';
  6223. var assign = require('./lib/utils/common').assign;
  6224. var deflate = require('./lib/deflate');
  6225. var inflate = require('./lib/inflate');
  6226. var constants = require('./lib/zlib/constants');
  6227. var pako = {};
  6228. assign(pako, deflate, inflate, constants);
  6229. module.exports = pako;
  6230. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  6231. 'use strict';
  6232. var zlib_deflate = require('./zlib/deflate');
  6233. var utils = require('./utils/common');
  6234. var strings = require('./utils/strings');
  6235. var msg = require('./zlib/messages');
  6236. var ZStream = require('./zlib/zstream');
  6237. var toString = Object.prototype.toString;
  6238. /* Public constants ==========================================================*/
  6239. /* ===========================================================================*/
  6240. var Z_NO_FLUSH = 0;
  6241. var Z_FINISH = 4;
  6242. var Z_OK = 0;
  6243. var Z_STREAM_END = 1;
  6244. var Z_SYNC_FLUSH = 2;
  6245. var Z_DEFAULT_COMPRESSION = -1;
  6246. var Z_DEFAULT_STRATEGY = 0;
  6247. var Z_DEFLATED = 8;
  6248. /* ===========================================================================*/
  6249. /**
  6250. * class Deflate
  6251. *
  6252. * Generic JS-style wrapper for zlib calls. If you don't need
  6253. * streaming behaviour - use more simple functions: [[deflate]],
  6254. * [[deflateRaw]] and [[gzip]].
  6255. **/
  6256. /* internal
  6257. * Deflate.chunks -> Array
  6258. *
  6259. * Chunks of output data, if [[Deflate#onData]] not overridden.
  6260. **/
  6261. /**
  6262. * Deflate.result -> Uint8Array|Array
  6263. *
  6264. * Compressed result, generated by default [[Deflate#onData]]
  6265. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  6266. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  6267. * push a chunk with explicit flush (call [[Deflate#push]] with
  6268. * `Z_SYNC_FLUSH` param).
  6269. **/
  6270. /**
  6271. * Deflate.err -> Number
  6272. *
  6273. * Error code after deflate finished. 0 (Z_OK) on success.
  6274. * You will not need it in real life, because deflate errors
  6275. * are possible only on wrong options or bad `onData` / `onEnd`
  6276. * custom handlers.
  6277. **/
  6278. /**
  6279. * Deflate.msg -> String
  6280. *
  6281. * Error message, if [[Deflate.err]] != 0
  6282. **/
  6283. /**
  6284. * new Deflate(options)
  6285. * - options (Object): zlib deflate options.
  6286. *
  6287. * Creates new deflator instance with specified params. Throws exception
  6288. * on bad params. Supported options:
  6289. *
  6290. * - `level`
  6291. * - `windowBits`
  6292. * - `memLevel`
  6293. * - `strategy`
  6294. * - `dictionary`
  6295. *
  6296. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6297. * for more information on these.
  6298. *
  6299. * Additional options, for internal needs:
  6300. *
  6301. * - `chunkSize` - size of generated data chunks (16K by default)
  6302. * - `raw` (Boolean) - do raw deflate
  6303. * - `gzip` (Boolean) - create gzip wrapper
  6304. * - `to` (String) - if equal to 'string', then result will be "binary string"
  6305. * (each char code [0..255])
  6306. * - `header` (Object) - custom header for gzip
  6307. * - `text` (Boolean) - true if compressed data believed to be text
  6308. * - `time` (Number) - modification time, unix timestamp
  6309. * - `os` (Number) - operation system code
  6310. * - `extra` (Array) - array of bytes with extra data (max 65536)
  6311. * - `name` (String) - file name (binary string)
  6312. * - `comment` (String) - comment (binary string)
  6313. * - `hcrc` (Boolean) - true if header crc should be added
  6314. *
  6315. * ##### Example:
  6316. *
  6317. * ```javascript
  6318. * var pako = require('pako')
  6319. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  6320. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  6321. *
  6322. * var deflate = new pako.Deflate({ level: 3});
  6323. *
  6324. * deflate.push(chunk1, false);
  6325. * deflate.push(chunk2, true); // true -> last chunk
  6326. *
  6327. * if (deflate.err) { throw new Error(deflate.err); }
  6328. *
  6329. * console.log(deflate.result);
  6330. * ```
  6331. **/
  6332. function Deflate(options) {
  6333. if (!(this instanceof Deflate)) return new Deflate(options);
  6334. this.options = utils.assign({
  6335. level: Z_DEFAULT_COMPRESSION,
  6336. method: Z_DEFLATED,
  6337. chunkSize: 16384,
  6338. windowBits: 15,
  6339. memLevel: 8,
  6340. strategy: Z_DEFAULT_STRATEGY,
  6341. to: ''
  6342. }, options || {});
  6343. var opt = this.options;
  6344. if (opt.raw && (opt.windowBits > 0)) {
  6345. opt.windowBits = -opt.windowBits;
  6346. }
  6347. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  6348. opt.windowBits += 16;
  6349. }
  6350. this.err = 0; // error code, if happens (0 = Z_OK)
  6351. this.msg = ''; // error message
  6352. this.ended = false; // used to avoid multiple onEnd() calls
  6353. this.chunks = []; // chunks of compressed data
  6354. this.strm = new ZStream();
  6355. this.strm.avail_out = 0;
  6356. var status = zlib_deflate.deflateInit2(
  6357. this.strm,
  6358. opt.level,
  6359. opt.method,
  6360. opt.windowBits,
  6361. opt.memLevel,
  6362. opt.strategy
  6363. );
  6364. if (status !== Z_OK) {
  6365. throw new Error(msg[status]);
  6366. }
  6367. if (opt.header) {
  6368. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  6369. }
  6370. if (opt.dictionary) {
  6371. var dict;
  6372. // Convert data if needed
  6373. if (typeof opt.dictionary === 'string') {
  6374. // If we need to compress text, change encoding to utf8.
  6375. dict = strings.string2buf(opt.dictionary);
  6376. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  6377. dict = new Uint8Array(opt.dictionary);
  6378. } else {
  6379. dict = opt.dictionary;
  6380. }
  6381. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  6382. if (status !== Z_OK) {
  6383. throw new Error(msg[status]);
  6384. }
  6385. this._dict_set = true;
  6386. }
  6387. }
  6388. /**
  6389. * Deflate#push(data[, mode]) -> Boolean
  6390. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  6391. * converted to utf8 byte sequence.
  6392. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  6393. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  6394. *
  6395. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  6396. * new compressed chunks. Returns `true` on success. The last data block must have
  6397. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  6398. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  6399. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  6400. *
  6401. * On fail call [[Deflate#onEnd]] with error code and return false.
  6402. *
  6403. * We strongly recommend to use `Uint8Array` on input for best speed (output
  6404. * array format is detected automatically). Also, don't skip last param and always
  6405. * use the same type in your code (boolean or number). That will improve JS speed.
  6406. *
  6407. * For regular `Array`-s make sure all elements are [0..255].
  6408. *
  6409. * ##### Example
  6410. *
  6411. * ```javascript
  6412. * push(chunk, false); // push one of data chunks
  6413. * ...
  6414. * push(chunk, true); // push last chunk
  6415. * ```
  6416. **/
  6417. Deflate.prototype.push = function (data, mode) {
  6418. var strm = this.strm;
  6419. var chunkSize = this.options.chunkSize;
  6420. var status, _mode;
  6421. if (this.ended) { return false; }
  6422. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  6423. // Convert data if needed
  6424. if (typeof data === 'string') {
  6425. // If we need to compress text, change encoding to utf8.
  6426. strm.input = strings.string2buf(data);
  6427. } else if (toString.call(data) === '[object ArrayBuffer]') {
  6428. strm.input = new Uint8Array(data);
  6429. } else {
  6430. strm.input = data;
  6431. }
  6432. strm.next_in = 0;
  6433. strm.avail_in = strm.input.length;
  6434. do {
  6435. if (strm.avail_out === 0) {
  6436. strm.output = new utils.Buf8(chunkSize);
  6437. strm.next_out = 0;
  6438. strm.avail_out = chunkSize;
  6439. }
  6440. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  6441. if (status !== Z_STREAM_END && status !== Z_OK) {
  6442. this.onEnd(status);
  6443. this.ended = true;
  6444. return false;
  6445. }
  6446. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  6447. if (this.options.to === 'string') {
  6448. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  6449. } else {
  6450. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  6451. }
  6452. }
  6453. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  6454. // Finalize on the last chunk.
  6455. if (_mode === Z_FINISH) {
  6456. status = zlib_deflate.deflateEnd(this.strm);
  6457. this.onEnd(status);
  6458. this.ended = true;
  6459. return status === Z_OK;
  6460. }
  6461. // callback interim results if Z_SYNC_FLUSH.
  6462. if (_mode === Z_SYNC_FLUSH) {
  6463. this.onEnd(Z_OK);
  6464. strm.avail_out = 0;
  6465. return true;
  6466. }
  6467. return true;
  6468. };
  6469. /**
  6470. * Deflate#onData(chunk) -> Void
  6471. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  6472. * on js engine support. When string output requested, each chunk
  6473. * will be string.
  6474. *
  6475. * By default, stores data blocks in `chunks[]` property and glue
  6476. * those in `onEnd`. Override this handler, if you need another behaviour.
  6477. **/
  6478. Deflate.prototype.onData = function (chunk) {
  6479. this.chunks.push(chunk);
  6480. };
  6481. /**
  6482. * Deflate#onEnd(status) -> Void
  6483. * - status (Number): deflate status. 0 (Z_OK) on success,
  6484. * other if not.
  6485. *
  6486. * Called once after you tell deflate that the input stream is
  6487. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  6488. * or if an error happened. By default - join collected chunks,
  6489. * free memory and fill `results` / `err` properties.
  6490. **/
  6491. Deflate.prototype.onEnd = function (status) {
  6492. // On success - join
  6493. if (status === Z_OK) {
  6494. if (this.options.to === 'string') {
  6495. this.result = this.chunks.join('');
  6496. } else {
  6497. this.result = utils.flattenChunks(this.chunks);
  6498. }
  6499. }
  6500. this.chunks = [];
  6501. this.err = status;
  6502. this.msg = this.strm.msg;
  6503. };
  6504. /**
  6505. * deflate(data[, options]) -> Uint8Array|Array|String
  6506. * - data (Uint8Array|Array|String): input data to compress.
  6507. * - options (Object): zlib deflate options.
  6508. *
  6509. * Compress `data` with deflate algorithm and `options`.
  6510. *
  6511. * Supported options are:
  6512. *
  6513. * - level
  6514. * - windowBits
  6515. * - memLevel
  6516. * - strategy
  6517. * - dictionary
  6518. *
  6519. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6520. * for more information on these.
  6521. *
  6522. * Sugar (options):
  6523. *
  6524. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  6525. * negative windowBits implicitly.
  6526. * - `to` (String) - if equal to 'string', then result will be "binary string"
  6527. * (each char code [0..255])
  6528. *
  6529. * ##### Example:
  6530. *
  6531. * ```javascript
  6532. * var pako = require('pako')
  6533. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  6534. *
  6535. * console.log(pako.deflate(data));
  6536. * ```
  6537. **/
  6538. function deflate(input, options) {
  6539. var deflator = new Deflate(options);
  6540. deflator.push(input, true);
  6541. // That will never happens, if you don't cheat with options :)
  6542. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  6543. return deflator.result;
  6544. }
  6545. /**
  6546. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  6547. * - data (Uint8Array|Array|String): input data to compress.
  6548. * - options (Object): zlib deflate options.
  6549. *
  6550. * The same as [[deflate]], but creates raw data, without wrapper
  6551. * (header and adler32 crc).
  6552. **/
  6553. function deflateRaw(input, options) {
  6554. options = options || {};
  6555. options.raw = true;
  6556. return deflate(input, options);
  6557. }
  6558. /**
  6559. * gzip(data[, options]) -> Uint8Array|Array|String
  6560. * - data (Uint8Array|Array|String): input data to compress.
  6561. * - options (Object): zlib deflate options.
  6562. *
  6563. * The same as [[deflate]], but create gzip wrapper instead of
  6564. * deflate one.
  6565. **/
  6566. function gzip(input, options) {
  6567. options = options || {};
  6568. options.gzip = true;
  6569. return deflate(input, options);
  6570. }
  6571. exports.Deflate = Deflate;
  6572. exports.deflate = deflate;
  6573. exports.deflateRaw = deflateRaw;
  6574. exports.gzip = gzip;
  6575. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  6576. 'use strict';
  6577. var zlib_inflate = require('./zlib/inflate');
  6578. var utils = require('./utils/common');
  6579. var strings = require('./utils/strings');
  6580. var c = require('./zlib/constants');
  6581. var msg = require('./zlib/messages');
  6582. var ZStream = require('./zlib/zstream');
  6583. var GZheader = require('./zlib/gzheader');
  6584. var toString = Object.prototype.toString;
  6585. /**
  6586. * class Inflate
  6587. *
  6588. * Generic JS-style wrapper for zlib calls. If you don't need
  6589. * streaming behaviour - use more simple functions: [[inflate]]
  6590. * and [[inflateRaw]].
  6591. **/
  6592. /* internal
  6593. * inflate.chunks -> Array
  6594. *
  6595. * Chunks of output data, if [[Inflate#onData]] not overridden.
  6596. **/
  6597. /**
  6598. * Inflate.result -> Uint8Array|Array|String
  6599. *
  6600. * Uncompressed result, generated by default [[Inflate#onData]]
  6601. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  6602. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  6603. * push a chunk with explicit flush (call [[Inflate#push]] with
  6604. * `Z_SYNC_FLUSH` param).
  6605. **/
  6606. /**
  6607. * Inflate.err -> Number
  6608. *
  6609. * Error code after inflate finished. 0 (Z_OK) on success.
  6610. * Should be checked if broken data possible.
  6611. **/
  6612. /**
  6613. * Inflate.msg -> String
  6614. *
  6615. * Error message, if [[Inflate.err]] != 0
  6616. **/
  6617. /**
  6618. * new Inflate(options)
  6619. * - options (Object): zlib inflate options.
  6620. *
  6621. * Creates new inflator instance with specified params. Throws exception
  6622. * on bad params. Supported options:
  6623. *
  6624. * - `windowBits`
  6625. * - `dictionary`
  6626. *
  6627. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6628. * for more information on these.
  6629. *
  6630. * Additional options, for internal needs:
  6631. *
  6632. * - `chunkSize` - size of generated data chunks (16K by default)
  6633. * - `raw` (Boolean) - do raw inflate
  6634. * - `to` (String) - if equal to 'string', then result will be converted
  6635. * from utf8 to utf16 (javascript) string. When string output requested,
  6636. * chunk length can differ from `chunkSize`, depending on content.
  6637. *
  6638. * By default, when no options set, autodetect deflate/gzip data format via
  6639. * wrapper header.
  6640. *
  6641. * ##### Example:
  6642. *
  6643. * ```javascript
  6644. * var pako = require('pako')
  6645. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  6646. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  6647. *
  6648. * var inflate = new pako.Inflate({ level: 3});
  6649. *
  6650. * inflate.push(chunk1, false);
  6651. * inflate.push(chunk2, true); // true -> last chunk
  6652. *
  6653. * if (inflate.err) { throw new Error(inflate.err); }
  6654. *
  6655. * console.log(inflate.result);
  6656. * ```
  6657. **/
  6658. function Inflate(options) {
  6659. if (!(this instanceof Inflate)) return new Inflate(options);
  6660. this.options = utils.assign({
  6661. chunkSize: 16384,
  6662. windowBits: 0,
  6663. to: ''
  6664. }, options || {});
  6665. var opt = this.options;
  6666. // Force window size for `raw` data, if not set directly,
  6667. // because we have no header for autodetect.
  6668. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  6669. opt.windowBits = -opt.windowBits;
  6670. if (opt.windowBits === 0) { opt.windowBits = -15; }
  6671. }
  6672. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  6673. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  6674. !(options && options.windowBits)) {
  6675. opt.windowBits += 32;
  6676. }
  6677. // Gzip header has no info about windows size, we can do autodetect only
  6678. // for deflate. So, if window size not set, force it to max when gzip possible
  6679. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  6680. // bit 3 (16) -> gzipped data
  6681. // bit 4 (32) -> autodetect gzip/deflate
  6682. if ((opt.windowBits & 15) === 0) {
  6683. opt.windowBits |= 15;
  6684. }
  6685. }
  6686. this.err = 0; // error code, if happens (0 = Z_OK)
  6687. this.msg = ''; // error message
  6688. this.ended = false; // used to avoid multiple onEnd() calls
  6689. this.chunks = []; // chunks of compressed data
  6690. this.strm = new ZStream();
  6691. this.strm.avail_out = 0;
  6692. var status = zlib_inflate.inflateInit2(
  6693. this.strm,
  6694. opt.windowBits
  6695. );
  6696. if (status !== c.Z_OK) {
  6697. throw new Error(msg[status]);
  6698. }
  6699. this.header = new GZheader();
  6700. zlib_inflate.inflateGetHeader(this.strm, this.header);
  6701. // Setup dictionary
  6702. if (opt.dictionary) {
  6703. // Convert data if needed
  6704. if (typeof opt.dictionary === 'string') {
  6705. opt.dictionary = strings.string2buf(opt.dictionary);
  6706. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  6707. opt.dictionary = new Uint8Array(opt.dictionary);
  6708. }
  6709. if (opt.raw) { //In raw mode we need to set the dictionary early
  6710. status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
  6711. if (status !== c.Z_OK) {
  6712. throw new Error(msg[status]);
  6713. }
  6714. }
  6715. }
  6716. }
  6717. /**
  6718. * Inflate#push(data[, mode]) -> Boolean
  6719. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  6720. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  6721. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  6722. *
  6723. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  6724. * new output chunks. Returns `true` on success. The last data block must have
  6725. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  6726. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  6727. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  6728. *
  6729. * On fail call [[Inflate#onEnd]] with error code and return false.
  6730. *
  6731. * We strongly recommend to use `Uint8Array` on input for best speed (output
  6732. * format is detected automatically). Also, don't skip last param and always
  6733. * use the same type in your code (boolean or number). That will improve JS speed.
  6734. *
  6735. * For regular `Array`-s make sure all elements are [0..255].
  6736. *
  6737. * ##### Example
  6738. *
  6739. * ```javascript
  6740. * push(chunk, false); // push one of data chunks
  6741. * ...
  6742. * push(chunk, true); // push last chunk
  6743. * ```
  6744. **/
  6745. Inflate.prototype.push = function (data, mode) {
  6746. var strm = this.strm;
  6747. var chunkSize = this.options.chunkSize;
  6748. var dictionary = this.options.dictionary;
  6749. var status, _mode;
  6750. var next_out_utf8, tail, utf8str;
  6751. // Flag to properly process Z_BUF_ERROR on testing inflate call
  6752. // when we check that all output data was flushed.
  6753. var allowBufError = false;
  6754. if (this.ended) { return false; }
  6755. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  6756. // Convert data if needed
  6757. if (typeof data === 'string') {
  6758. // Only binary strings can be decompressed on practice
  6759. strm.input = strings.binstring2buf(data);
  6760. } else if (toString.call(data) === '[object ArrayBuffer]') {
  6761. strm.input = new Uint8Array(data);
  6762. } else {
  6763. strm.input = data;
  6764. }
  6765. strm.next_in = 0;
  6766. strm.avail_in = strm.input.length;
  6767. do {
  6768. if (strm.avail_out === 0) {
  6769. strm.output = new utils.Buf8(chunkSize);
  6770. strm.next_out = 0;
  6771. strm.avail_out = chunkSize;
  6772. }
  6773. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  6774. if (status === c.Z_NEED_DICT && dictionary) {
  6775. status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
  6776. }
  6777. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  6778. status = c.Z_OK;
  6779. allowBufError = false;
  6780. }
  6781. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  6782. this.onEnd(status);
  6783. this.ended = true;
  6784. return false;
  6785. }
  6786. if (strm.next_out) {
  6787. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  6788. if (this.options.to === 'string') {
  6789. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  6790. tail = strm.next_out - next_out_utf8;
  6791. utf8str = strings.buf2string(strm.output, next_out_utf8);
  6792. // move tail
  6793. strm.next_out = tail;
  6794. strm.avail_out = chunkSize - tail;
  6795. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  6796. this.onData(utf8str);
  6797. } else {
  6798. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  6799. }
  6800. }
  6801. }
  6802. // When no more input data, we should check that internal inflate buffers
  6803. // are flushed. The only way to do it when avail_out = 0 - run one more
  6804. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  6805. // Here we set flag to process this error properly.
  6806. //
  6807. // NOTE. Deflate does not return error in this case and does not needs such
  6808. // logic.
  6809. if (strm.avail_in === 0 && strm.avail_out === 0) {
  6810. allowBufError = true;
  6811. }
  6812. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  6813. if (status === c.Z_STREAM_END) {
  6814. _mode = c.Z_FINISH;
  6815. }
  6816. // Finalize on the last chunk.
  6817. if (_mode === c.Z_FINISH) {
  6818. status = zlib_inflate.inflateEnd(this.strm);
  6819. this.onEnd(status);
  6820. this.ended = true;
  6821. return status === c.Z_OK;
  6822. }
  6823. // callback interim results if Z_SYNC_FLUSH.
  6824. if (_mode === c.Z_SYNC_FLUSH) {
  6825. this.onEnd(c.Z_OK);
  6826. strm.avail_out = 0;
  6827. return true;
  6828. }
  6829. return true;
  6830. };
  6831. /**
  6832. * Inflate#onData(chunk) -> Void
  6833. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  6834. * on js engine support. When string output requested, each chunk
  6835. * will be string.
  6836. *
  6837. * By default, stores data blocks in `chunks[]` property and glue
  6838. * those in `onEnd`. Override this handler, if you need another behaviour.
  6839. **/
  6840. Inflate.prototype.onData = function (chunk) {
  6841. this.chunks.push(chunk);
  6842. };
  6843. /**
  6844. * Inflate#onEnd(status) -> Void
  6845. * - status (Number): inflate status. 0 (Z_OK) on success,
  6846. * other if not.
  6847. *
  6848. * Called either after you tell inflate that the input stream is
  6849. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  6850. * or if an error happened. By default - join collected chunks,
  6851. * free memory and fill `results` / `err` properties.
  6852. **/
  6853. Inflate.prototype.onEnd = function (status) {
  6854. // On success - join
  6855. if (status === c.Z_OK) {
  6856. if (this.options.to === 'string') {
  6857. // Glue & convert here, until we teach pako to send
  6858. // utf8 aligned strings to onData
  6859. this.result = this.chunks.join('');
  6860. } else {
  6861. this.result = utils.flattenChunks(this.chunks);
  6862. }
  6863. }
  6864. this.chunks = [];
  6865. this.err = status;
  6866. this.msg = this.strm.msg;
  6867. };
  6868. /**
  6869. * inflate(data[, options]) -> Uint8Array|Array|String
  6870. * - data (Uint8Array|Array|String): input data to decompress.
  6871. * - options (Object): zlib inflate options.
  6872. *
  6873. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  6874. * format via wrapper header by default. That's why we don't provide
  6875. * separate `ungzip` method.
  6876. *
  6877. * Supported options are:
  6878. *
  6879. * - windowBits
  6880. *
  6881. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6882. * for more information.
  6883. *
  6884. * Sugar (options):
  6885. *
  6886. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  6887. * negative windowBits implicitly.
  6888. * - `to` (String) - if equal to 'string', then result will be converted
  6889. * from utf8 to utf16 (javascript) string. When string output requested,
  6890. * chunk length can differ from `chunkSize`, depending on content.
  6891. *
  6892. *
  6893. * ##### Example:
  6894. *
  6895. * ```javascript
  6896. * var pako = require('pako')
  6897. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  6898. * , output;
  6899. *
  6900. * try {
  6901. * output = pako.inflate(input);
  6902. * } catch (err)
  6903. * console.log(err);
  6904. * }
  6905. * ```
  6906. **/
  6907. function inflate(input, options) {
  6908. var inflator = new Inflate(options);
  6909. inflator.push(input, true);
  6910. // That will never happens, if you don't cheat with options :)
  6911. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  6912. return inflator.result;
  6913. }
  6914. /**
  6915. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  6916. * - data (Uint8Array|Array|String): input data to decompress.
  6917. * - options (Object): zlib inflate options.
  6918. *
  6919. * The same as [[inflate]], but creates raw data, without wrapper
  6920. * (header and adler32 crc).
  6921. **/
  6922. function inflateRaw(input, options) {
  6923. options = options || {};
  6924. options.raw = true;
  6925. return inflate(input, options);
  6926. }
  6927. /**
  6928. * ungzip(data[, options]) -> Uint8Array|Array|String
  6929. * - data (Uint8Array|Array|String): input data to decompress.
  6930. * - options (Object): zlib inflate options.
  6931. *
  6932. * Just shortcut to [[inflate]], because it autodetects format
  6933. * by header.content. Done for convenience.
  6934. **/
  6935. exports.Inflate = Inflate;
  6936. exports.inflate = inflate;
  6937. exports.inflateRaw = inflateRaw;
  6938. exports.ungzip = inflate;
  6939. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  6940. 'use strict';
  6941. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  6942. (typeof Uint16Array !== 'undefined') &&
  6943. (typeof Int32Array !== 'undefined');
  6944. function _has(obj, key) {
  6945. return Object.prototype.hasOwnProperty.call(obj, key);
  6946. }
  6947. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  6948. var sources = Array.prototype.slice.call(arguments, 1);
  6949. while (sources.length) {
  6950. var source = sources.shift();
  6951. if (!source) { continue; }
  6952. if (typeof source !== 'object') {
  6953. throw new TypeError(source + 'must be non-object');
  6954. }
  6955. for (var p in source) {
  6956. if (_has(source, p)) {
  6957. obj[p] = source[p];
  6958. }
  6959. }
  6960. }
  6961. return obj;
  6962. };
  6963. // reduce buffer size, avoiding mem copy
  6964. exports.shrinkBuf = function (buf, size) {
  6965. if (buf.length === size) { return buf; }
  6966. if (buf.subarray) { return buf.subarray(0, size); }
  6967. buf.length = size;
  6968. return buf;
  6969. };
  6970. var fnTyped = {
  6971. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6972. if (src.subarray && dest.subarray) {
  6973. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  6974. return;
  6975. }
  6976. // Fallback to ordinary array
  6977. for (var i = 0; i < len; i++) {
  6978. dest[dest_offs + i] = src[src_offs + i];
  6979. }
  6980. },
  6981. // Join array of chunks to single array.
  6982. flattenChunks: function (chunks) {
  6983. var i, l, len, pos, chunk, result;
  6984. // calculate data length
  6985. len = 0;
  6986. for (i = 0, l = chunks.length; i < l; i++) {
  6987. len += chunks[i].length;
  6988. }
  6989. // join chunks
  6990. result = new Uint8Array(len);
  6991. pos = 0;
  6992. for (i = 0, l = chunks.length; i < l; i++) {
  6993. chunk = chunks[i];
  6994. result.set(chunk, pos);
  6995. pos += chunk.length;
  6996. }
  6997. return result;
  6998. }
  6999. };
  7000. var fnUntyped = {
  7001. arraySet: function (dest, src, src_offs, len, dest_offs) {
  7002. for (var i = 0; i < len; i++) {
  7003. dest[dest_offs + i] = src[src_offs + i];
  7004. }
  7005. },
  7006. // Join array of chunks to single array.
  7007. flattenChunks: function (chunks) {
  7008. return [].concat.apply([], chunks);
  7009. }
  7010. };
  7011. // Enable/Disable typed arrays use, for testing
  7012. //
  7013. exports.setTyped = function (on) {
  7014. if (on) {
  7015. exports.Buf8 = Uint8Array;
  7016. exports.Buf16 = Uint16Array;
  7017. exports.Buf32 = Int32Array;
  7018. exports.assign(exports, fnTyped);
  7019. } else {
  7020. exports.Buf8 = Array;
  7021. exports.Buf16 = Array;
  7022. exports.Buf32 = Array;
  7023. exports.assign(exports, fnUntyped);
  7024. }
  7025. };
  7026. exports.setTyped(TYPED_OK);
  7027. },{}],52:[function(require,module,exports){
  7028. // String encode/decode helpers
  7029. 'use strict';
  7030. var utils = require('./common');
  7031. // Quick check if we can use fast array to bin string conversion
  7032. //
  7033. // - apply(Array) can fail on Android 2.2
  7034. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  7035. //
  7036. var STR_APPLY_OK = true;
  7037. var STR_APPLY_UIA_OK = true;
  7038. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  7039. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  7040. // Table with utf8 lengths (calculated by first byte of sequence)
  7041. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  7042. // because max possible codepoint is 0x10ffff
  7043. var _utf8len = new utils.Buf8(256);
  7044. for (var q = 0; q < 256; q++) {
  7045. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  7046. }
  7047. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  7048. // convert string to array (typed, when possible)
  7049. exports.string2buf = function (str) {
  7050. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  7051. // count binary size
  7052. for (m_pos = 0; m_pos < str_len; m_pos++) {
  7053. c = str.charCodeAt(m_pos);
  7054. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  7055. c2 = str.charCodeAt(m_pos + 1);
  7056. if ((c2 & 0xfc00) === 0xdc00) {
  7057. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  7058. m_pos++;
  7059. }
  7060. }
  7061. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  7062. }
  7063. // allocate buffer
  7064. buf = new utils.Buf8(buf_len);
  7065. // convert
  7066. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  7067. c = str.charCodeAt(m_pos);
  7068. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  7069. c2 = str.charCodeAt(m_pos + 1);
  7070. if ((c2 & 0xfc00) === 0xdc00) {
  7071. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  7072. m_pos++;
  7073. }
  7074. }
  7075. if (c < 0x80) {
  7076. /* one byte */
  7077. buf[i++] = c;
  7078. } else if (c < 0x800) {
  7079. /* two bytes */
  7080. buf[i++] = 0xC0 | (c >>> 6);
  7081. buf[i++] = 0x80 | (c & 0x3f);
  7082. } else if (c < 0x10000) {
  7083. /* three bytes */
  7084. buf[i++] = 0xE0 | (c >>> 12);
  7085. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  7086. buf[i++] = 0x80 | (c & 0x3f);
  7087. } else {
  7088. /* four bytes */
  7089. buf[i++] = 0xf0 | (c >>> 18);
  7090. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  7091. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  7092. buf[i++] = 0x80 | (c & 0x3f);
  7093. }
  7094. }
  7095. return buf;
  7096. };
  7097. // Helper (used in 2 places)
  7098. function buf2binstring(buf, len) {
  7099. // On Chrome, the arguments in a function call that are allowed is `65534`.
  7100. // If the length of the buffer is smaller than that, we can use this optimization,
  7101. // otherwise we will take a slower path.
  7102. if (len < 65534) {
  7103. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  7104. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  7105. }
  7106. }
  7107. var result = '';
  7108. for (var i = 0; i < len; i++) {
  7109. result += String.fromCharCode(buf[i]);
  7110. }
  7111. return result;
  7112. }
  7113. // Convert byte array to binary string
  7114. exports.buf2binstring = function (buf) {
  7115. return buf2binstring(buf, buf.length);
  7116. };
  7117. // Convert binary string (typed, when possible)
  7118. exports.binstring2buf = function (str) {
  7119. var buf = new utils.Buf8(str.length);
  7120. for (var i = 0, len = buf.length; i < len; i++) {
  7121. buf[i] = str.charCodeAt(i);
  7122. }
  7123. return buf;
  7124. };
  7125. // convert array to string
  7126. exports.buf2string = function (buf, max) {
  7127. var i, out, c, c_len;
  7128. var len = max || buf.length;
  7129. // Reserve max possible length (2 words per char)
  7130. // NB: by unknown reasons, Array is significantly faster for
  7131. // String.fromCharCode.apply than Uint16Array.
  7132. var utf16buf = new Array(len * 2);
  7133. for (out = 0, i = 0; i < len;) {
  7134. c = buf[i++];
  7135. // quick process ascii
  7136. if (c < 0x80) { utf16buf[out++] = c; continue; }
  7137. c_len = _utf8len[c];
  7138. // skip 5 & 6 byte codes
  7139. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  7140. // apply mask on first byte
  7141. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  7142. // join the rest
  7143. while (c_len > 1 && i < len) {
  7144. c = (c << 6) | (buf[i++] & 0x3f);
  7145. c_len--;
  7146. }
  7147. // terminated by end of string?
  7148. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  7149. if (c < 0x10000) {
  7150. utf16buf[out++] = c;
  7151. } else {
  7152. c -= 0x10000;
  7153. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  7154. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  7155. }
  7156. }
  7157. return buf2binstring(utf16buf, out);
  7158. };
  7159. // Calculate max possible position in utf8 buffer,
  7160. // that will not break sequence. If that's not possible
  7161. // - (very small limits) return max size as is.
  7162. //
  7163. // buf[] - utf8 bytes array
  7164. // max - length limit (mandatory);
  7165. exports.utf8border = function (buf, max) {
  7166. var pos;
  7167. max = max || buf.length;
  7168. if (max > buf.length) { max = buf.length; }
  7169. // go back from last position, until start of sequence found
  7170. pos = max - 1;
  7171. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  7172. // Very small and broken sequence,
  7173. // return max, because we should return something anyway.
  7174. if (pos < 0) { return max; }
  7175. // If we came to start of buffer - that means buffer is too small,
  7176. // return max too.
  7177. if (pos === 0) { return max; }
  7178. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  7179. };
  7180. },{"./common":51}],53:[function(require,module,exports){
  7181. 'use strict';
  7182. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  7183. // It isn't worth it to make additional optimizations as in original.
  7184. // Small size is preferable.
  7185. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7186. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7187. //
  7188. // This software is provided 'as-is', without any express or implied
  7189. // warranty. In no event will the authors be held liable for any damages
  7190. // arising from the use of this software.
  7191. //
  7192. // Permission is granted to anyone to use this software for any purpose,
  7193. // including commercial applications, and to alter it and redistribute it
  7194. // freely, subject to the following restrictions:
  7195. //
  7196. // 1. The origin of this software must not be misrepresented; you must not
  7197. // claim that you wrote the original software. If you use this software
  7198. // in a product, an acknowledgment in the product documentation would be
  7199. // appreciated but is not required.
  7200. // 2. Altered source versions must be plainly marked as such, and must not be
  7201. // misrepresented as being the original software.
  7202. // 3. This notice may not be removed or altered from any source distribution.
  7203. function adler32(adler, buf, len, pos) {
  7204. var s1 = (adler & 0xffff) |0,
  7205. s2 = ((adler >>> 16) & 0xffff) |0,
  7206. n = 0;
  7207. while (len !== 0) {
  7208. // Set limit ~ twice less than 5552, to keep
  7209. // s2 in 31-bits, because we force signed ints.
  7210. // in other case %= will fail.
  7211. n = len > 2000 ? 2000 : len;
  7212. len -= n;
  7213. do {
  7214. s1 = (s1 + buf[pos++]) |0;
  7215. s2 = (s2 + s1) |0;
  7216. } while (--n);
  7217. s1 %= 65521;
  7218. s2 %= 65521;
  7219. }
  7220. return (s1 | (s2 << 16)) |0;
  7221. }
  7222. module.exports = adler32;
  7223. },{}],54:[function(require,module,exports){
  7224. 'use strict';
  7225. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7226. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7227. //
  7228. // This software is provided 'as-is', without any express or implied
  7229. // warranty. In no event will the authors be held liable for any damages
  7230. // arising from the use of this software.
  7231. //
  7232. // Permission is granted to anyone to use this software for any purpose,
  7233. // including commercial applications, and to alter it and redistribute it
  7234. // freely, subject to the following restrictions:
  7235. //
  7236. // 1. The origin of this software must not be misrepresented; you must not
  7237. // claim that you wrote the original software. If you use this software
  7238. // in a product, an acknowledgment in the product documentation would be
  7239. // appreciated but is not required.
  7240. // 2. Altered source versions must be plainly marked as such, and must not be
  7241. // misrepresented as being the original software.
  7242. // 3. This notice may not be removed or altered from any source distribution.
  7243. module.exports = {
  7244. /* Allowed flush values; see deflate() and inflate() below for details */
  7245. Z_NO_FLUSH: 0,
  7246. Z_PARTIAL_FLUSH: 1,
  7247. Z_SYNC_FLUSH: 2,
  7248. Z_FULL_FLUSH: 3,
  7249. Z_FINISH: 4,
  7250. Z_BLOCK: 5,
  7251. Z_TREES: 6,
  7252. /* Return codes for the compression/decompression functions. Negative values
  7253. * are errors, positive values are used for special but normal events.
  7254. */
  7255. Z_OK: 0,
  7256. Z_STREAM_END: 1,
  7257. Z_NEED_DICT: 2,
  7258. Z_ERRNO: -1,
  7259. Z_STREAM_ERROR: -2,
  7260. Z_DATA_ERROR: -3,
  7261. //Z_MEM_ERROR: -4,
  7262. Z_BUF_ERROR: -5,
  7263. //Z_VERSION_ERROR: -6,
  7264. /* compression levels */
  7265. Z_NO_COMPRESSION: 0,
  7266. Z_BEST_SPEED: 1,
  7267. Z_BEST_COMPRESSION: 9,
  7268. Z_DEFAULT_COMPRESSION: -1,
  7269. Z_FILTERED: 1,
  7270. Z_HUFFMAN_ONLY: 2,
  7271. Z_RLE: 3,
  7272. Z_FIXED: 4,
  7273. Z_DEFAULT_STRATEGY: 0,
  7274. /* Possible values of the data_type field (though see inflate()) */
  7275. Z_BINARY: 0,
  7276. Z_TEXT: 1,
  7277. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  7278. Z_UNKNOWN: 2,
  7279. /* The deflate compression method */
  7280. Z_DEFLATED: 8
  7281. //Z_NULL: null // Use -1 or null inline, depending on var type
  7282. };
  7283. },{}],55:[function(require,module,exports){
  7284. 'use strict';
  7285. // Note: we can't get significant speed boost here.
  7286. // So write code to minimize size - no pregenerated tables
  7287. // and array tools dependencies.
  7288. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7289. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7290. //
  7291. // This software is provided 'as-is', without any express or implied
  7292. // warranty. In no event will the authors be held liable for any damages
  7293. // arising from the use of this software.
  7294. //
  7295. // Permission is granted to anyone to use this software for any purpose,
  7296. // including commercial applications, and to alter it and redistribute it
  7297. // freely, subject to the following restrictions:
  7298. //
  7299. // 1. The origin of this software must not be misrepresented; you must not
  7300. // claim that you wrote the original software. If you use this software
  7301. // in a product, an acknowledgment in the product documentation would be
  7302. // appreciated but is not required.
  7303. // 2. Altered source versions must be plainly marked as such, and must not be
  7304. // misrepresented as being the original software.
  7305. // 3. This notice may not be removed or altered from any source distribution.
  7306. // Use ordinary array, since untyped makes no boost here
  7307. function makeTable() {
  7308. var c, table = [];
  7309. for (var n = 0; n < 256; n++) {
  7310. c = n;
  7311. for (var k = 0; k < 8; k++) {
  7312. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  7313. }
  7314. table[n] = c;
  7315. }
  7316. return table;
  7317. }
  7318. // Create table on load. Just 255 signed longs. Not a problem.
  7319. var crcTable = makeTable();
  7320. function crc32(crc, buf, len, pos) {
  7321. var t = crcTable,
  7322. end = pos + len;
  7323. crc ^= -1;
  7324. for (var i = pos; i < end; i++) {
  7325. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  7326. }
  7327. return (crc ^ (-1)); // >>> 0;
  7328. }
  7329. module.exports = crc32;
  7330. },{}],56:[function(require,module,exports){
  7331. 'use strict';
  7332. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7333. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7334. //
  7335. // This software is provided 'as-is', without any express or implied
  7336. // warranty. In no event will the authors be held liable for any damages
  7337. // arising from the use of this software.
  7338. //
  7339. // Permission is granted to anyone to use this software for any purpose,
  7340. // including commercial applications, and to alter it and redistribute it
  7341. // freely, subject to the following restrictions:
  7342. //
  7343. // 1. The origin of this software must not be misrepresented; you must not
  7344. // claim that you wrote the original software. If you use this software
  7345. // in a product, an acknowledgment in the product documentation would be
  7346. // appreciated but is not required.
  7347. // 2. Altered source versions must be plainly marked as such, and must not be
  7348. // misrepresented as being the original software.
  7349. // 3. This notice may not be removed or altered from any source distribution.
  7350. var utils = require('../utils/common');
  7351. var trees = require('./trees');
  7352. var adler32 = require('./adler32');
  7353. var crc32 = require('./crc32');
  7354. var msg = require('./messages');
  7355. /* Public constants ==========================================================*/
  7356. /* ===========================================================================*/
  7357. /* Allowed flush values; see deflate() and inflate() below for details */
  7358. var Z_NO_FLUSH = 0;
  7359. var Z_PARTIAL_FLUSH = 1;
  7360. //var Z_SYNC_FLUSH = 2;
  7361. var Z_FULL_FLUSH = 3;
  7362. var Z_FINISH = 4;
  7363. var Z_BLOCK = 5;
  7364. //var Z_TREES = 6;
  7365. /* Return codes for the compression/decompression functions. Negative values
  7366. * are errors, positive values are used for special but normal events.
  7367. */
  7368. var Z_OK = 0;
  7369. var Z_STREAM_END = 1;
  7370. //var Z_NEED_DICT = 2;
  7371. //var Z_ERRNO = -1;
  7372. var Z_STREAM_ERROR = -2;
  7373. var Z_DATA_ERROR = -3;
  7374. //var Z_MEM_ERROR = -4;
  7375. var Z_BUF_ERROR = -5;
  7376. //var Z_VERSION_ERROR = -6;
  7377. /* compression levels */
  7378. //var Z_NO_COMPRESSION = 0;
  7379. //var Z_BEST_SPEED = 1;
  7380. //var Z_BEST_COMPRESSION = 9;
  7381. var Z_DEFAULT_COMPRESSION = -1;
  7382. var Z_FILTERED = 1;
  7383. var Z_HUFFMAN_ONLY = 2;
  7384. var Z_RLE = 3;
  7385. var Z_FIXED = 4;
  7386. var Z_DEFAULT_STRATEGY = 0;
  7387. /* Possible values of the data_type field (though see inflate()) */
  7388. //var Z_BINARY = 0;
  7389. //var Z_TEXT = 1;
  7390. //var Z_ASCII = 1; // = Z_TEXT
  7391. var Z_UNKNOWN = 2;
  7392. /* The deflate compression method */
  7393. var Z_DEFLATED = 8;
  7394. /*============================================================================*/
  7395. var MAX_MEM_LEVEL = 9;
  7396. /* Maximum value for memLevel in deflateInit2 */
  7397. var MAX_WBITS = 15;
  7398. /* 32K LZ77 window */
  7399. var DEF_MEM_LEVEL = 8;
  7400. var LENGTH_CODES = 29;
  7401. /* number of length codes, not counting the special END_BLOCK code */
  7402. var LITERALS = 256;
  7403. /* number of literal bytes 0..255 */
  7404. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  7405. /* number of Literal or Length codes, including the END_BLOCK code */
  7406. var D_CODES = 30;
  7407. /* number of distance codes */
  7408. var BL_CODES = 19;
  7409. /* number of codes used to transfer the bit lengths */
  7410. var HEAP_SIZE = 2 * L_CODES + 1;
  7411. /* maximum heap size */
  7412. var MAX_BITS = 15;
  7413. /* All codes must not exceed MAX_BITS bits */
  7414. var MIN_MATCH = 3;
  7415. var MAX_MATCH = 258;
  7416. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  7417. var PRESET_DICT = 0x20;
  7418. var INIT_STATE = 42;
  7419. var EXTRA_STATE = 69;
  7420. var NAME_STATE = 73;
  7421. var COMMENT_STATE = 91;
  7422. var HCRC_STATE = 103;
  7423. var BUSY_STATE = 113;
  7424. var FINISH_STATE = 666;
  7425. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  7426. var BS_BLOCK_DONE = 2; /* block flush performed */
  7427. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  7428. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  7429. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  7430. function err(strm, errorCode) {
  7431. strm.msg = msg[errorCode];
  7432. return errorCode;
  7433. }
  7434. function rank(f) {
  7435. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  7436. }
  7437. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  7438. /* =========================================================================
  7439. * Flush as much pending output as possible. All deflate() output goes
  7440. * through this function so some applications may wish to modify it
  7441. * to avoid allocating a large strm->output buffer and copying into it.
  7442. * (See also read_buf()).
  7443. */
  7444. function flush_pending(strm) {
  7445. var s = strm.state;
  7446. //_tr_flush_bits(s);
  7447. var len = s.pending;
  7448. if (len > strm.avail_out) {
  7449. len = strm.avail_out;
  7450. }
  7451. if (len === 0) { return; }
  7452. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  7453. strm.next_out += len;
  7454. s.pending_out += len;
  7455. strm.total_out += len;
  7456. strm.avail_out -= len;
  7457. s.pending -= len;
  7458. if (s.pending === 0) {
  7459. s.pending_out = 0;
  7460. }
  7461. }
  7462. function flush_block_only(s, last) {
  7463. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  7464. s.block_start = s.strstart;
  7465. flush_pending(s.strm);
  7466. }
  7467. function put_byte(s, b) {
  7468. s.pending_buf[s.pending++] = b;
  7469. }
  7470. /* =========================================================================
  7471. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  7472. * IN assertion: the stream state is correct and there is enough room in
  7473. * pending_buf.
  7474. */
  7475. function putShortMSB(s, b) {
  7476. // put_byte(s, (Byte)(b >> 8));
  7477. // put_byte(s, (Byte)(b & 0xff));
  7478. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  7479. s.pending_buf[s.pending++] = b & 0xff;
  7480. }
  7481. /* ===========================================================================
  7482. * Read a new buffer from the current input stream, update the adler32
  7483. * and total number of bytes read. All deflate() input goes through
  7484. * this function so some applications may wish to modify it to avoid
  7485. * allocating a large strm->input buffer and copying from it.
  7486. * (See also flush_pending()).
  7487. */
  7488. function read_buf(strm, buf, start, size) {
  7489. var len = strm.avail_in;
  7490. if (len > size) { len = size; }
  7491. if (len === 0) { return 0; }
  7492. strm.avail_in -= len;
  7493. // zmemcpy(buf, strm->next_in, len);
  7494. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  7495. if (strm.state.wrap === 1) {
  7496. strm.adler = adler32(strm.adler, buf, len, start);
  7497. }
  7498. else if (strm.state.wrap === 2) {
  7499. strm.adler = crc32(strm.adler, buf, len, start);
  7500. }
  7501. strm.next_in += len;
  7502. strm.total_in += len;
  7503. return len;
  7504. }
  7505. /* ===========================================================================
  7506. * Set match_start to the longest match starting at the given string and
  7507. * return its length. Matches shorter or equal to prev_length are discarded,
  7508. * in which case the result is equal to prev_length and match_start is
  7509. * garbage.
  7510. * IN assertions: cur_match is the head of the hash chain for the current
  7511. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  7512. * OUT assertion: the match length is not greater than s->lookahead.
  7513. */
  7514. function longest_match(s, cur_match) {
  7515. var chain_length = s.max_chain_length; /* max hash chain length */
  7516. var scan = s.strstart; /* current string */
  7517. var match; /* matched string */
  7518. var len; /* length of current match */
  7519. var best_len = s.prev_length; /* best match length so far */
  7520. var nice_match = s.nice_match; /* stop if match long enough */
  7521. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  7522. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  7523. var _win = s.window; // shortcut
  7524. var wmask = s.w_mask;
  7525. var prev = s.prev;
  7526. /* Stop when cur_match becomes <= limit. To simplify the code,
  7527. * we prevent matches with the string of window index 0.
  7528. */
  7529. var strend = s.strstart + MAX_MATCH;
  7530. var scan_end1 = _win[scan + best_len - 1];
  7531. var scan_end = _win[scan + best_len];
  7532. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  7533. * It is easy to get rid of this optimization if necessary.
  7534. */
  7535. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  7536. /* Do not waste too much time if we already have a good match: */
  7537. if (s.prev_length >= s.good_match) {
  7538. chain_length >>= 2;
  7539. }
  7540. /* Do not look for matches beyond the end of the input. This is necessary
  7541. * to make deflate deterministic.
  7542. */
  7543. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  7544. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  7545. do {
  7546. // Assert(cur_match < s->strstart, "no future");
  7547. match = cur_match;
  7548. /* Skip to next match if the match length cannot increase
  7549. * or if the match length is less than 2. Note that the checks below
  7550. * for insufficient lookahead only occur occasionally for performance
  7551. * reasons. Therefore uninitialized memory will be accessed, and
  7552. * conditional jumps will be made that depend on those values.
  7553. * However the length of the match is limited to the lookahead, so
  7554. * the output of deflate is not affected by the uninitialized values.
  7555. */
  7556. if (_win[match + best_len] !== scan_end ||
  7557. _win[match + best_len - 1] !== scan_end1 ||
  7558. _win[match] !== _win[scan] ||
  7559. _win[++match] !== _win[scan + 1]) {
  7560. continue;
  7561. }
  7562. /* The check at best_len-1 can be removed because it will be made
  7563. * again later. (This heuristic is not always a win.)
  7564. * It is not necessary to compare scan[2] and match[2] since they
  7565. * are always equal when the other bytes match, given that
  7566. * the hash keys are equal and that HASH_BITS >= 8.
  7567. */
  7568. scan += 2;
  7569. match++;
  7570. // Assert(*scan == *match, "match[2]?");
  7571. /* We check for insufficient lookahead only every 8th comparison;
  7572. * the 256th check will be made at strstart+258.
  7573. */
  7574. do {
  7575. /*jshint noempty:false*/
  7576. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7577. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7578. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7579. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7580. scan < strend);
  7581. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  7582. len = MAX_MATCH - (strend - scan);
  7583. scan = strend - MAX_MATCH;
  7584. if (len > best_len) {
  7585. s.match_start = cur_match;
  7586. best_len = len;
  7587. if (len >= nice_match) {
  7588. break;
  7589. }
  7590. scan_end1 = _win[scan + best_len - 1];
  7591. scan_end = _win[scan + best_len];
  7592. }
  7593. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  7594. if (best_len <= s.lookahead) {
  7595. return best_len;
  7596. }
  7597. return s.lookahead;
  7598. }
  7599. /* ===========================================================================
  7600. * Fill the window when the lookahead becomes insufficient.
  7601. * Updates strstart and lookahead.
  7602. *
  7603. * IN assertion: lookahead < MIN_LOOKAHEAD
  7604. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  7605. * At least one byte has been read, or avail_in == 0; reads are
  7606. * performed for at least two bytes (required for the zip translate_eol
  7607. * option -- not supported here).
  7608. */
  7609. function fill_window(s) {
  7610. var _w_size = s.w_size;
  7611. var p, n, m, more, str;
  7612. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  7613. do {
  7614. more = s.window_size - s.lookahead - s.strstart;
  7615. // JS ints have 32 bit, block below not needed
  7616. /* Deal with !@#$% 64K limit: */
  7617. //if (sizeof(int) <= 2) {
  7618. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  7619. // more = wsize;
  7620. //
  7621. // } else if (more == (unsigned)(-1)) {
  7622. // /* Very unlikely, but possible on 16 bit machine if
  7623. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  7624. // */
  7625. // more--;
  7626. // }
  7627. //}
  7628. /* If the window is almost full and there is insufficient lookahead,
  7629. * move the upper half to the lower one to make room in the upper half.
  7630. */
  7631. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  7632. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  7633. s.match_start -= _w_size;
  7634. s.strstart -= _w_size;
  7635. /* we now have strstart >= MAX_DIST */
  7636. s.block_start -= _w_size;
  7637. /* Slide the hash table (could be avoided with 32 bit values
  7638. at the expense of memory usage). We slide even when level == 0
  7639. to keep the hash table consistent if we switch back to level > 0
  7640. later. (Using level 0 permanently is not an optimal usage of
  7641. zlib, so we don't care about this pathological case.)
  7642. */
  7643. n = s.hash_size;
  7644. p = n;
  7645. do {
  7646. m = s.head[--p];
  7647. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  7648. } while (--n);
  7649. n = _w_size;
  7650. p = n;
  7651. do {
  7652. m = s.prev[--p];
  7653. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  7654. /* If n is not on any hash chain, prev[n] is garbage but
  7655. * its value will never be used.
  7656. */
  7657. } while (--n);
  7658. more += _w_size;
  7659. }
  7660. if (s.strm.avail_in === 0) {
  7661. break;
  7662. }
  7663. /* If there was no sliding:
  7664. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  7665. * more == window_size - lookahead - strstart
  7666. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  7667. * => more >= window_size - 2*WSIZE + 2
  7668. * In the BIG_MEM or MMAP case (not yet supported),
  7669. * window_size == input_size + MIN_LOOKAHEAD &&
  7670. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  7671. * Otherwise, window_size == 2*WSIZE so more >= 2.
  7672. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  7673. */
  7674. //Assert(more >= 2, "more < 2");
  7675. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  7676. s.lookahead += n;
  7677. /* Initialize the hash value now that we have some input: */
  7678. if (s.lookahead + s.insert >= MIN_MATCH) {
  7679. str = s.strstart - s.insert;
  7680. s.ins_h = s.window[str];
  7681. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  7682. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  7683. //#if MIN_MATCH != 3
  7684. // Call update_hash() MIN_MATCH-3 more times
  7685. //#endif
  7686. while (s.insert) {
  7687. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7688. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7689. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7690. s.head[s.ins_h] = str;
  7691. str++;
  7692. s.insert--;
  7693. if (s.lookahead + s.insert < MIN_MATCH) {
  7694. break;
  7695. }
  7696. }
  7697. }
  7698. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  7699. * but this is not important since only literal bytes will be emitted.
  7700. */
  7701. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  7702. /* If the WIN_INIT bytes after the end of the current data have never been
  7703. * written, then zero those bytes in order to avoid memory check reports of
  7704. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  7705. * the longest match routines. Update the high water mark for the next
  7706. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  7707. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  7708. */
  7709. // if (s.high_water < s.window_size) {
  7710. // var curr = s.strstart + s.lookahead;
  7711. // var init = 0;
  7712. //
  7713. // if (s.high_water < curr) {
  7714. // /* Previous high water mark below current data -- zero WIN_INIT
  7715. // * bytes or up to end of window, whichever is less.
  7716. // */
  7717. // init = s.window_size - curr;
  7718. // if (init > WIN_INIT)
  7719. // init = WIN_INIT;
  7720. // zmemzero(s->window + curr, (unsigned)init);
  7721. // s->high_water = curr + init;
  7722. // }
  7723. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  7724. // /* High water mark at or above current data, but below current data
  7725. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  7726. // * to end of window, whichever is less.
  7727. // */
  7728. // init = (ulg)curr + WIN_INIT - s->high_water;
  7729. // if (init > s->window_size - s->high_water)
  7730. // init = s->window_size - s->high_water;
  7731. // zmemzero(s->window + s->high_water, (unsigned)init);
  7732. // s->high_water += init;
  7733. // }
  7734. // }
  7735. //
  7736. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  7737. // "not enough room for search");
  7738. }
  7739. /* ===========================================================================
  7740. * Copy without compression as much as possible from the input stream, return
  7741. * the current block state.
  7742. * This function does not insert new strings in the dictionary since
  7743. * uncompressible data is probably not useful. This function is used
  7744. * only for the level=0 compression option.
  7745. * NOTE: this function should be optimized to avoid extra copying from
  7746. * window to pending_buf.
  7747. */
  7748. function deflate_stored(s, flush) {
  7749. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  7750. * to pending_buf_size, and each stored block has a 5 byte header:
  7751. */
  7752. var max_block_size = 0xffff;
  7753. if (max_block_size > s.pending_buf_size - 5) {
  7754. max_block_size = s.pending_buf_size - 5;
  7755. }
  7756. /* Copy as much as possible from input to output: */
  7757. for (;;) {
  7758. /* Fill the window as much as possible: */
  7759. if (s.lookahead <= 1) {
  7760. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  7761. // s->block_start >= (long)s->w_size, "slide too late");
  7762. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  7763. // s.block_start >= s.w_size)) {
  7764. // throw new Error("slide too late");
  7765. // }
  7766. fill_window(s);
  7767. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  7768. return BS_NEED_MORE;
  7769. }
  7770. if (s.lookahead === 0) {
  7771. break;
  7772. }
  7773. /* flush the current block */
  7774. }
  7775. //Assert(s->block_start >= 0L, "block gone");
  7776. // if (s.block_start < 0) throw new Error("block gone");
  7777. s.strstart += s.lookahead;
  7778. s.lookahead = 0;
  7779. /* Emit a stored block if pending_buf will be full: */
  7780. var max_start = s.block_start + max_block_size;
  7781. if (s.strstart === 0 || s.strstart >= max_start) {
  7782. /* strstart == 0 is possible when wraparound on 16-bit machine */
  7783. s.lookahead = s.strstart - max_start;
  7784. s.strstart = max_start;
  7785. /*** FLUSH_BLOCK(s, 0); ***/
  7786. flush_block_only(s, false);
  7787. if (s.strm.avail_out === 0) {
  7788. return BS_NEED_MORE;
  7789. }
  7790. /***/
  7791. }
  7792. /* Flush if we may have to slide, otherwise block_start may become
  7793. * negative and the data will be gone:
  7794. */
  7795. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  7796. /*** FLUSH_BLOCK(s, 0); ***/
  7797. flush_block_only(s, false);
  7798. if (s.strm.avail_out === 0) {
  7799. return BS_NEED_MORE;
  7800. }
  7801. /***/
  7802. }
  7803. }
  7804. s.insert = 0;
  7805. if (flush === Z_FINISH) {
  7806. /*** FLUSH_BLOCK(s, 1); ***/
  7807. flush_block_only(s, true);
  7808. if (s.strm.avail_out === 0) {
  7809. return BS_FINISH_STARTED;
  7810. }
  7811. /***/
  7812. return BS_FINISH_DONE;
  7813. }
  7814. if (s.strstart > s.block_start) {
  7815. /*** FLUSH_BLOCK(s, 0); ***/
  7816. flush_block_only(s, false);
  7817. if (s.strm.avail_out === 0) {
  7818. return BS_NEED_MORE;
  7819. }
  7820. /***/
  7821. }
  7822. return BS_NEED_MORE;
  7823. }
  7824. /* ===========================================================================
  7825. * Compress as much as possible from the input stream, return the current
  7826. * block state.
  7827. * This function does not perform lazy evaluation of matches and inserts
  7828. * new strings in the dictionary only for unmatched strings or for short
  7829. * matches. It is used only for the fast compression options.
  7830. */
  7831. function deflate_fast(s, flush) {
  7832. var hash_head; /* head of the hash chain */
  7833. var bflush; /* set if current block must be flushed */
  7834. for (;;) {
  7835. /* Make sure that we always have enough lookahead, except
  7836. * at the end of the input file. We need MAX_MATCH bytes
  7837. * for the next match, plus MIN_MATCH bytes to insert the
  7838. * string following the next match.
  7839. */
  7840. if (s.lookahead < MIN_LOOKAHEAD) {
  7841. fill_window(s);
  7842. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  7843. return BS_NEED_MORE;
  7844. }
  7845. if (s.lookahead === 0) {
  7846. break; /* flush the current block */
  7847. }
  7848. }
  7849. /* Insert the string window[strstart .. strstart+2] in the
  7850. * dictionary, and set hash_head to the head of the hash chain:
  7851. */
  7852. hash_head = 0/*NIL*/;
  7853. if (s.lookahead >= MIN_MATCH) {
  7854. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7855. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7856. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7857. s.head[s.ins_h] = s.strstart;
  7858. /***/
  7859. }
  7860. /* Find the longest match, discarding those <= prev_length.
  7861. * At this point we have always match_length < MIN_MATCH
  7862. */
  7863. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  7864. /* To simplify the code, we prevent matches with the string
  7865. * of window index 0 (in particular we have to avoid a match
  7866. * of the string with itself at the start of the input file).
  7867. */
  7868. s.match_length = longest_match(s, hash_head);
  7869. /* longest_match() sets match_start */
  7870. }
  7871. if (s.match_length >= MIN_MATCH) {
  7872. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  7873. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  7874. s.match_length - MIN_MATCH, bflush); ***/
  7875. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  7876. s.lookahead -= s.match_length;
  7877. /* Insert new strings in the hash table only if the match length
  7878. * is not too large. This saves time but degrades compression.
  7879. */
  7880. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  7881. s.match_length--; /* string at strstart already in table */
  7882. do {
  7883. s.strstart++;
  7884. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7885. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7886. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7887. s.head[s.ins_h] = s.strstart;
  7888. /***/
  7889. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  7890. * always MIN_MATCH bytes ahead.
  7891. */
  7892. } while (--s.match_length !== 0);
  7893. s.strstart++;
  7894. } else
  7895. {
  7896. s.strstart += s.match_length;
  7897. s.match_length = 0;
  7898. s.ins_h = s.window[s.strstart];
  7899. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  7900. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  7901. //#if MIN_MATCH != 3
  7902. // Call UPDATE_HASH() MIN_MATCH-3 more times
  7903. //#endif
  7904. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  7905. * matter since it will be recomputed at next deflate call.
  7906. */
  7907. }
  7908. } else {
  7909. /* No match, output a literal byte */
  7910. //Tracevv((stderr,"%c", s.window[s.strstart]));
  7911. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7912. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7913. s.lookahead--;
  7914. s.strstart++;
  7915. }
  7916. if (bflush) {
  7917. /*** FLUSH_BLOCK(s, 0); ***/
  7918. flush_block_only(s, false);
  7919. if (s.strm.avail_out === 0) {
  7920. return BS_NEED_MORE;
  7921. }
  7922. /***/
  7923. }
  7924. }
  7925. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  7926. if (flush === Z_FINISH) {
  7927. /*** FLUSH_BLOCK(s, 1); ***/
  7928. flush_block_only(s, true);
  7929. if (s.strm.avail_out === 0) {
  7930. return BS_FINISH_STARTED;
  7931. }
  7932. /***/
  7933. return BS_FINISH_DONE;
  7934. }
  7935. if (s.last_lit) {
  7936. /*** FLUSH_BLOCK(s, 0); ***/
  7937. flush_block_only(s, false);
  7938. if (s.strm.avail_out === 0) {
  7939. return BS_NEED_MORE;
  7940. }
  7941. /***/
  7942. }
  7943. return BS_BLOCK_DONE;
  7944. }
  7945. /* ===========================================================================
  7946. * Same as above, but achieves better compression. We use a lazy
  7947. * evaluation for matches: a match is finally adopted only if there is
  7948. * no better match at the next window position.
  7949. */
  7950. function deflate_slow(s, flush) {
  7951. var hash_head; /* head of hash chain */
  7952. var bflush; /* set if current block must be flushed */
  7953. var max_insert;
  7954. /* Process the input block. */
  7955. for (;;) {
  7956. /* Make sure that we always have enough lookahead, except
  7957. * at the end of the input file. We need MAX_MATCH bytes
  7958. * for the next match, plus MIN_MATCH bytes to insert the
  7959. * string following the next match.
  7960. */
  7961. if (s.lookahead < MIN_LOOKAHEAD) {
  7962. fill_window(s);
  7963. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  7964. return BS_NEED_MORE;
  7965. }
  7966. if (s.lookahead === 0) { break; } /* flush the current block */
  7967. }
  7968. /* Insert the string window[strstart .. strstart+2] in the
  7969. * dictionary, and set hash_head to the head of the hash chain:
  7970. */
  7971. hash_head = 0/*NIL*/;
  7972. if (s.lookahead >= MIN_MATCH) {
  7973. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7974. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7975. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7976. s.head[s.ins_h] = s.strstart;
  7977. /***/
  7978. }
  7979. /* Find the longest match, discarding those <= prev_length.
  7980. */
  7981. s.prev_length = s.match_length;
  7982. s.prev_match = s.match_start;
  7983. s.match_length = MIN_MATCH - 1;
  7984. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  7985. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  7986. /* To simplify the code, we prevent matches with the string
  7987. * of window index 0 (in particular we have to avoid a match
  7988. * of the string with itself at the start of the input file).
  7989. */
  7990. s.match_length = longest_match(s, hash_head);
  7991. /* longest_match() sets match_start */
  7992. if (s.match_length <= 5 &&
  7993. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  7994. /* If prev_match is also MIN_MATCH, match_start is garbage
  7995. * but we will ignore the current match anyway.
  7996. */
  7997. s.match_length = MIN_MATCH - 1;
  7998. }
  7999. }
  8000. /* If there was a match at the previous step and the current
  8001. * match is not better, output the previous match:
  8002. */
  8003. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  8004. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  8005. /* Do not insert strings in hash table beyond this. */
  8006. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  8007. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  8008. s.prev_length - MIN_MATCH, bflush);***/
  8009. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  8010. /* Insert in hash table all strings up to the end of the match.
  8011. * strstart-1 and strstart are already inserted. If there is not
  8012. * enough lookahead, the last two strings are not inserted in
  8013. * the hash table.
  8014. */
  8015. s.lookahead -= s.prev_length - 1;
  8016. s.prev_length -= 2;
  8017. do {
  8018. if (++s.strstart <= max_insert) {
  8019. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  8020. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  8021. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  8022. s.head[s.ins_h] = s.strstart;
  8023. /***/
  8024. }
  8025. } while (--s.prev_length !== 0);
  8026. s.match_available = 0;
  8027. s.match_length = MIN_MATCH - 1;
  8028. s.strstart++;
  8029. if (bflush) {
  8030. /*** FLUSH_BLOCK(s, 0); ***/
  8031. flush_block_only(s, false);
  8032. if (s.strm.avail_out === 0) {
  8033. return BS_NEED_MORE;
  8034. }
  8035. /***/
  8036. }
  8037. } else if (s.match_available) {
  8038. /* If there was no match at the previous position, output a
  8039. * single literal. If there was a match but the current match
  8040. * is longer, truncate the previous match to a single literal.
  8041. */
  8042. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  8043. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  8044. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  8045. if (bflush) {
  8046. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  8047. flush_block_only(s, false);
  8048. /***/
  8049. }
  8050. s.strstart++;
  8051. s.lookahead--;
  8052. if (s.strm.avail_out === 0) {
  8053. return BS_NEED_MORE;
  8054. }
  8055. } else {
  8056. /* There is no previous match to compare with, wait for
  8057. * the next step to decide.
  8058. */
  8059. s.match_available = 1;
  8060. s.strstart++;
  8061. s.lookahead--;
  8062. }
  8063. }
  8064. //Assert (flush != Z_NO_FLUSH, "no flush?");
  8065. if (s.match_available) {
  8066. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  8067. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  8068. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  8069. s.match_available = 0;
  8070. }
  8071. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  8072. if (flush === Z_FINISH) {
  8073. /*** FLUSH_BLOCK(s, 1); ***/
  8074. flush_block_only(s, true);
  8075. if (s.strm.avail_out === 0) {
  8076. return BS_FINISH_STARTED;
  8077. }
  8078. /***/
  8079. return BS_FINISH_DONE;
  8080. }
  8081. if (s.last_lit) {
  8082. /*** FLUSH_BLOCK(s, 0); ***/
  8083. flush_block_only(s, false);
  8084. if (s.strm.avail_out === 0) {
  8085. return BS_NEED_MORE;
  8086. }
  8087. /***/
  8088. }
  8089. return BS_BLOCK_DONE;
  8090. }
  8091. /* ===========================================================================
  8092. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  8093. * one. Do not maintain a hash table. (It will be regenerated if this run of
  8094. * deflate switches away from Z_RLE.)
  8095. */
  8096. function deflate_rle(s, flush) {
  8097. var bflush; /* set if current block must be flushed */
  8098. var prev; /* byte at distance one to match */
  8099. var scan, strend; /* scan goes up to strend for length of run */
  8100. var _win = s.window;
  8101. for (;;) {
  8102. /* Make sure that we always have enough lookahead, except
  8103. * at the end of the input file. We need MAX_MATCH bytes
  8104. * for the longest run, plus one for the unrolled loop.
  8105. */
  8106. if (s.lookahead <= MAX_MATCH) {
  8107. fill_window(s);
  8108. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  8109. return BS_NEED_MORE;
  8110. }
  8111. if (s.lookahead === 0) { break; } /* flush the current block */
  8112. }
  8113. /* See how many times the previous byte repeats */
  8114. s.match_length = 0;
  8115. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  8116. scan = s.strstart - 1;
  8117. prev = _win[scan];
  8118. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  8119. strend = s.strstart + MAX_MATCH;
  8120. do {
  8121. /*jshint noempty:false*/
  8122. } while (prev === _win[++scan] && prev === _win[++scan] &&
  8123. prev === _win[++scan] && prev === _win[++scan] &&
  8124. prev === _win[++scan] && prev === _win[++scan] &&
  8125. prev === _win[++scan] && prev === _win[++scan] &&
  8126. scan < strend);
  8127. s.match_length = MAX_MATCH - (strend - scan);
  8128. if (s.match_length > s.lookahead) {
  8129. s.match_length = s.lookahead;
  8130. }
  8131. }
  8132. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  8133. }
  8134. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  8135. if (s.match_length >= MIN_MATCH) {
  8136. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  8137. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  8138. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  8139. s.lookahead -= s.match_length;
  8140. s.strstart += s.match_length;
  8141. s.match_length = 0;
  8142. } else {
  8143. /* No match, output a literal byte */
  8144. //Tracevv((stderr,"%c", s->window[s->strstart]));
  8145. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  8146. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  8147. s.lookahead--;
  8148. s.strstart++;
  8149. }
  8150. if (bflush) {
  8151. /*** FLUSH_BLOCK(s, 0); ***/
  8152. flush_block_only(s, false);
  8153. if (s.strm.avail_out === 0) {
  8154. return BS_NEED_MORE;
  8155. }
  8156. /***/
  8157. }
  8158. }
  8159. s.insert = 0;
  8160. if (flush === Z_FINISH) {
  8161. /*** FLUSH_BLOCK(s, 1); ***/
  8162. flush_block_only(s, true);
  8163. if (s.strm.avail_out === 0) {
  8164. return BS_FINISH_STARTED;
  8165. }
  8166. /***/
  8167. return BS_FINISH_DONE;
  8168. }
  8169. if (s.last_lit) {
  8170. /*** FLUSH_BLOCK(s, 0); ***/
  8171. flush_block_only(s, false);
  8172. if (s.strm.avail_out === 0) {
  8173. return BS_NEED_MORE;
  8174. }
  8175. /***/
  8176. }
  8177. return BS_BLOCK_DONE;
  8178. }
  8179. /* ===========================================================================
  8180. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  8181. * (It will be regenerated if this run of deflate switches away from Huffman.)
  8182. */
  8183. function deflate_huff(s, flush) {
  8184. var bflush; /* set if current block must be flushed */
  8185. for (;;) {
  8186. /* Make sure that we have a literal to write. */
  8187. if (s.lookahead === 0) {
  8188. fill_window(s);
  8189. if (s.lookahead === 0) {
  8190. if (flush === Z_NO_FLUSH) {
  8191. return BS_NEED_MORE;
  8192. }
  8193. break; /* flush the current block */
  8194. }
  8195. }
  8196. /* Output a literal byte */
  8197. s.match_length = 0;
  8198. //Tracevv((stderr,"%c", s->window[s->strstart]));
  8199. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  8200. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  8201. s.lookahead--;
  8202. s.strstart++;
  8203. if (bflush) {
  8204. /*** FLUSH_BLOCK(s, 0); ***/
  8205. flush_block_only(s, false);
  8206. if (s.strm.avail_out === 0) {
  8207. return BS_NEED_MORE;
  8208. }
  8209. /***/
  8210. }
  8211. }
  8212. s.insert = 0;
  8213. if (flush === Z_FINISH) {
  8214. /*** FLUSH_BLOCK(s, 1); ***/
  8215. flush_block_only(s, true);
  8216. if (s.strm.avail_out === 0) {
  8217. return BS_FINISH_STARTED;
  8218. }
  8219. /***/
  8220. return BS_FINISH_DONE;
  8221. }
  8222. if (s.last_lit) {
  8223. /*** FLUSH_BLOCK(s, 0); ***/
  8224. flush_block_only(s, false);
  8225. if (s.strm.avail_out === 0) {
  8226. return BS_NEED_MORE;
  8227. }
  8228. /***/
  8229. }
  8230. return BS_BLOCK_DONE;
  8231. }
  8232. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  8233. * the desired pack level (0..9). The values given below have been tuned to
  8234. * exclude worst case performance for pathological files. Better values may be
  8235. * found for specific files.
  8236. */
  8237. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  8238. this.good_length = good_length;
  8239. this.max_lazy = max_lazy;
  8240. this.nice_length = nice_length;
  8241. this.max_chain = max_chain;
  8242. this.func = func;
  8243. }
  8244. var configuration_table;
  8245. configuration_table = [
  8246. /* good lazy nice chain */
  8247. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  8248. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  8249. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  8250. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  8251. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  8252. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  8253. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  8254. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  8255. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  8256. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  8257. ];
  8258. /* ===========================================================================
  8259. * Initialize the "longest match" routines for a new zlib stream
  8260. */
  8261. function lm_init(s) {
  8262. s.window_size = 2 * s.w_size;
  8263. /*** CLEAR_HASH(s); ***/
  8264. zero(s.head); // Fill with NIL (= 0);
  8265. /* Set the default configuration parameters:
  8266. */
  8267. s.max_lazy_match = configuration_table[s.level].max_lazy;
  8268. s.good_match = configuration_table[s.level].good_length;
  8269. s.nice_match = configuration_table[s.level].nice_length;
  8270. s.max_chain_length = configuration_table[s.level].max_chain;
  8271. s.strstart = 0;
  8272. s.block_start = 0;
  8273. s.lookahead = 0;
  8274. s.insert = 0;
  8275. s.match_length = s.prev_length = MIN_MATCH - 1;
  8276. s.match_available = 0;
  8277. s.ins_h = 0;
  8278. }
  8279. function DeflateState() {
  8280. this.strm = null; /* pointer back to this zlib stream */
  8281. this.status = 0; /* as the name implies */
  8282. this.pending_buf = null; /* output still pending */
  8283. this.pending_buf_size = 0; /* size of pending_buf */
  8284. this.pending_out = 0; /* next pending byte to output to the stream */
  8285. this.pending = 0; /* nb of bytes in the pending buffer */
  8286. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8287. this.gzhead = null; /* gzip header information to write */
  8288. this.gzindex = 0; /* where in extra, name, or comment */
  8289. this.method = Z_DEFLATED; /* can only be DEFLATED */
  8290. this.last_flush = -1; /* value of flush param for previous deflate call */
  8291. this.w_size = 0; /* LZ77 window size (32K by default) */
  8292. this.w_bits = 0; /* log2(w_size) (8..16) */
  8293. this.w_mask = 0; /* w_size - 1 */
  8294. this.window = null;
  8295. /* Sliding window. Input bytes are read into the second half of the window,
  8296. * and move to the first half later to keep a dictionary of at least wSize
  8297. * bytes. With this organization, matches are limited to a distance of
  8298. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  8299. * performed with a length multiple of the block size.
  8300. */
  8301. this.window_size = 0;
  8302. /* Actual size of window: 2*wSize, except when the user input buffer
  8303. * is directly used as sliding window.
  8304. */
  8305. this.prev = null;
  8306. /* Link to older string with same hash index. To limit the size of this
  8307. * array to 64K, this link is maintained only for the last 32K strings.
  8308. * An index in this array is thus a window index modulo 32K.
  8309. */
  8310. this.head = null; /* Heads of the hash chains or NIL. */
  8311. this.ins_h = 0; /* hash index of string to be inserted */
  8312. this.hash_size = 0; /* number of elements in hash table */
  8313. this.hash_bits = 0; /* log2(hash_size) */
  8314. this.hash_mask = 0; /* hash_size-1 */
  8315. this.hash_shift = 0;
  8316. /* Number of bits by which ins_h must be shifted at each input
  8317. * step. It must be such that after MIN_MATCH steps, the oldest
  8318. * byte no longer takes part in the hash key, that is:
  8319. * hash_shift * MIN_MATCH >= hash_bits
  8320. */
  8321. this.block_start = 0;
  8322. /* Window position at the beginning of the current output block. Gets
  8323. * negative when the window is moved backwards.
  8324. */
  8325. this.match_length = 0; /* length of best match */
  8326. this.prev_match = 0; /* previous match */
  8327. this.match_available = 0; /* set if previous match exists */
  8328. this.strstart = 0; /* start of string to insert */
  8329. this.match_start = 0; /* start of matching string */
  8330. this.lookahead = 0; /* number of valid bytes ahead in window */
  8331. this.prev_length = 0;
  8332. /* Length of the best match at previous step. Matches not greater than this
  8333. * are discarded. This is used in the lazy match evaluation.
  8334. */
  8335. this.max_chain_length = 0;
  8336. /* To speed up deflation, hash chains are never searched beyond this
  8337. * length. A higher limit improves compression ratio but degrades the
  8338. * speed.
  8339. */
  8340. this.max_lazy_match = 0;
  8341. /* Attempt to find a better match only when the current match is strictly
  8342. * smaller than this value. This mechanism is used only for compression
  8343. * levels >= 4.
  8344. */
  8345. // That's alias to max_lazy_match, don't use directly
  8346. //this.max_insert_length = 0;
  8347. /* Insert new strings in the hash table only if the match length is not
  8348. * greater than this length. This saves time but degrades compression.
  8349. * max_insert_length is used only for compression levels <= 3.
  8350. */
  8351. this.level = 0; /* compression level (1..9) */
  8352. this.strategy = 0; /* favor or force Huffman coding*/
  8353. this.good_match = 0;
  8354. /* Use a faster search when the previous match is longer than this */
  8355. this.nice_match = 0; /* Stop searching when current match exceeds this */
  8356. /* used by trees.c: */
  8357. /* Didn't use ct_data typedef below to suppress compiler warning */
  8358. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  8359. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  8360. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  8361. // Use flat array of DOUBLE size, with interleaved fata,
  8362. // because JS does not support effective
  8363. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  8364. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  8365. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  8366. zero(this.dyn_ltree);
  8367. zero(this.dyn_dtree);
  8368. zero(this.bl_tree);
  8369. this.l_desc = null; /* desc. for literal tree */
  8370. this.d_desc = null; /* desc. for distance tree */
  8371. this.bl_desc = null; /* desc. for bit length tree */
  8372. //ush bl_count[MAX_BITS+1];
  8373. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  8374. /* number of codes at each bit length for an optimal tree */
  8375. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  8376. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  8377. zero(this.heap);
  8378. this.heap_len = 0; /* number of elements in the heap */
  8379. this.heap_max = 0; /* element of largest frequency */
  8380. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  8381. * The same heap array is used to build all trees.
  8382. */
  8383. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  8384. zero(this.depth);
  8385. /* Depth of each subtree used as tie breaker for trees of equal frequency
  8386. */
  8387. this.l_buf = 0; /* buffer index for literals or lengths */
  8388. this.lit_bufsize = 0;
  8389. /* Size of match buffer for literals/lengths. There are 4 reasons for
  8390. * limiting lit_bufsize to 64K:
  8391. * - frequencies can be kept in 16 bit counters
  8392. * - if compression is not successful for the first block, all input
  8393. * data is still in the window so we can still emit a stored block even
  8394. * when input comes from standard input. (This can also be done for
  8395. * all blocks if lit_bufsize is not greater than 32K.)
  8396. * - if compression is not successful for a file smaller than 64K, we can
  8397. * even emit a stored file instead of a stored block (saving 5 bytes).
  8398. * This is applicable only for zip (not gzip or zlib).
  8399. * - creating new Huffman trees less frequently may not provide fast
  8400. * adaptation to changes in the input data statistics. (Take for
  8401. * example a binary file with poorly compressible code followed by
  8402. * a highly compressible string table.) Smaller buffer sizes give
  8403. * fast adaptation but have of course the overhead of transmitting
  8404. * trees more frequently.
  8405. * - I can't count above 4
  8406. */
  8407. this.last_lit = 0; /* running index in l_buf */
  8408. this.d_buf = 0;
  8409. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  8410. * the same number of elements. To use different lengths, an extra flag
  8411. * array would be necessary.
  8412. */
  8413. this.opt_len = 0; /* bit length of current block with optimal trees */
  8414. this.static_len = 0; /* bit length of current block with static trees */
  8415. this.matches = 0; /* number of string matches in current block */
  8416. this.insert = 0; /* bytes at end of window left to insert */
  8417. this.bi_buf = 0;
  8418. /* Output buffer. bits are inserted starting at the bottom (least
  8419. * significant bits).
  8420. */
  8421. this.bi_valid = 0;
  8422. /* Number of valid bits in bi_buf. All bits above the last valid bit
  8423. * are always zero.
  8424. */
  8425. // Used for window memory init. We safely ignore it for JS. That makes
  8426. // sense only for pointers and memory check tools.
  8427. //this.high_water = 0;
  8428. /* High water mark offset in window for initialized bytes -- bytes above
  8429. * this are set to zero in order to avoid memory check warnings when
  8430. * longest match routines access bytes past the input. This is then
  8431. * updated to the new high water mark.
  8432. */
  8433. }
  8434. function deflateResetKeep(strm) {
  8435. var s;
  8436. if (!strm || !strm.state) {
  8437. return err(strm, Z_STREAM_ERROR);
  8438. }
  8439. strm.total_in = strm.total_out = 0;
  8440. strm.data_type = Z_UNKNOWN;
  8441. s = strm.state;
  8442. s.pending = 0;
  8443. s.pending_out = 0;
  8444. if (s.wrap < 0) {
  8445. s.wrap = -s.wrap;
  8446. /* was made negative by deflate(..., Z_FINISH); */
  8447. }
  8448. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  8449. strm.adler = (s.wrap === 2) ?
  8450. 0 // crc32(0, Z_NULL, 0)
  8451. :
  8452. 1; // adler32(0, Z_NULL, 0)
  8453. s.last_flush = Z_NO_FLUSH;
  8454. trees._tr_init(s);
  8455. return Z_OK;
  8456. }
  8457. function deflateReset(strm) {
  8458. var ret = deflateResetKeep(strm);
  8459. if (ret === Z_OK) {
  8460. lm_init(strm.state);
  8461. }
  8462. return ret;
  8463. }
  8464. function deflateSetHeader(strm, head) {
  8465. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8466. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  8467. strm.state.gzhead = head;
  8468. return Z_OK;
  8469. }
  8470. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  8471. if (!strm) { // === Z_NULL
  8472. return Z_STREAM_ERROR;
  8473. }
  8474. var wrap = 1;
  8475. if (level === Z_DEFAULT_COMPRESSION) {
  8476. level = 6;
  8477. }
  8478. if (windowBits < 0) { /* suppress zlib wrapper */
  8479. wrap = 0;
  8480. windowBits = -windowBits;
  8481. }
  8482. else if (windowBits > 15) {
  8483. wrap = 2; /* write gzip wrapper instead */
  8484. windowBits -= 16;
  8485. }
  8486. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  8487. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  8488. strategy < 0 || strategy > Z_FIXED) {
  8489. return err(strm, Z_STREAM_ERROR);
  8490. }
  8491. if (windowBits === 8) {
  8492. windowBits = 9;
  8493. }
  8494. /* until 256-byte window bug fixed */
  8495. var s = new DeflateState();
  8496. strm.state = s;
  8497. s.strm = strm;
  8498. s.wrap = wrap;
  8499. s.gzhead = null;
  8500. s.w_bits = windowBits;
  8501. s.w_size = 1 << s.w_bits;
  8502. s.w_mask = s.w_size - 1;
  8503. s.hash_bits = memLevel + 7;
  8504. s.hash_size = 1 << s.hash_bits;
  8505. s.hash_mask = s.hash_size - 1;
  8506. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  8507. s.window = new utils.Buf8(s.w_size * 2);
  8508. s.head = new utils.Buf16(s.hash_size);
  8509. s.prev = new utils.Buf16(s.w_size);
  8510. // Don't need mem init magic for JS.
  8511. //s.high_water = 0; /* nothing written to s->window yet */
  8512. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  8513. s.pending_buf_size = s.lit_bufsize * 4;
  8514. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  8515. //s->pending_buf = (uchf *) overlay;
  8516. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  8517. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  8518. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  8519. s.d_buf = 1 * s.lit_bufsize;
  8520. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  8521. s.l_buf = (1 + 2) * s.lit_bufsize;
  8522. s.level = level;
  8523. s.strategy = strategy;
  8524. s.method = method;
  8525. return deflateReset(strm);
  8526. }
  8527. function deflateInit(strm, level) {
  8528. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  8529. }
  8530. function deflate(strm, flush) {
  8531. var old_flush, s;
  8532. var beg, val; // for gzip header write only
  8533. if (!strm || !strm.state ||
  8534. flush > Z_BLOCK || flush < 0) {
  8535. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  8536. }
  8537. s = strm.state;
  8538. if (!strm.output ||
  8539. (!strm.input && strm.avail_in !== 0) ||
  8540. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  8541. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  8542. }
  8543. s.strm = strm; /* just in case */
  8544. old_flush = s.last_flush;
  8545. s.last_flush = flush;
  8546. /* Write the header */
  8547. if (s.status === INIT_STATE) {
  8548. if (s.wrap === 2) { // GZIP header
  8549. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  8550. put_byte(s, 31);
  8551. put_byte(s, 139);
  8552. put_byte(s, 8);
  8553. if (!s.gzhead) { // s->gzhead == Z_NULL
  8554. put_byte(s, 0);
  8555. put_byte(s, 0);
  8556. put_byte(s, 0);
  8557. put_byte(s, 0);
  8558. put_byte(s, 0);
  8559. put_byte(s, s.level === 9 ? 2 :
  8560. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  8561. 4 : 0));
  8562. put_byte(s, OS_CODE);
  8563. s.status = BUSY_STATE;
  8564. }
  8565. else {
  8566. put_byte(s, (s.gzhead.text ? 1 : 0) +
  8567. (s.gzhead.hcrc ? 2 : 0) +
  8568. (!s.gzhead.extra ? 0 : 4) +
  8569. (!s.gzhead.name ? 0 : 8) +
  8570. (!s.gzhead.comment ? 0 : 16)
  8571. );
  8572. put_byte(s, s.gzhead.time & 0xff);
  8573. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  8574. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  8575. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  8576. put_byte(s, s.level === 9 ? 2 :
  8577. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  8578. 4 : 0));
  8579. put_byte(s, s.gzhead.os & 0xff);
  8580. if (s.gzhead.extra && s.gzhead.extra.length) {
  8581. put_byte(s, s.gzhead.extra.length & 0xff);
  8582. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  8583. }
  8584. if (s.gzhead.hcrc) {
  8585. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  8586. }
  8587. s.gzindex = 0;
  8588. s.status = EXTRA_STATE;
  8589. }
  8590. }
  8591. else // DEFLATE header
  8592. {
  8593. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  8594. var level_flags = -1;
  8595. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  8596. level_flags = 0;
  8597. } else if (s.level < 6) {
  8598. level_flags = 1;
  8599. } else if (s.level === 6) {
  8600. level_flags = 2;
  8601. } else {
  8602. level_flags = 3;
  8603. }
  8604. header |= (level_flags << 6);
  8605. if (s.strstart !== 0) { header |= PRESET_DICT; }
  8606. header += 31 - (header % 31);
  8607. s.status = BUSY_STATE;
  8608. putShortMSB(s, header);
  8609. /* Save the adler32 of the preset dictionary: */
  8610. if (s.strstart !== 0) {
  8611. putShortMSB(s, strm.adler >>> 16);
  8612. putShortMSB(s, strm.adler & 0xffff);
  8613. }
  8614. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  8615. }
  8616. }
  8617. //#ifdef GZIP
  8618. if (s.status === EXTRA_STATE) {
  8619. if (s.gzhead.extra/* != Z_NULL*/) {
  8620. beg = s.pending; /* start of bytes to update crc */
  8621. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  8622. if (s.pending === s.pending_buf_size) {
  8623. if (s.gzhead.hcrc && s.pending > beg) {
  8624. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8625. }
  8626. flush_pending(strm);
  8627. beg = s.pending;
  8628. if (s.pending === s.pending_buf_size) {
  8629. break;
  8630. }
  8631. }
  8632. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  8633. s.gzindex++;
  8634. }
  8635. if (s.gzhead.hcrc && s.pending > beg) {
  8636. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8637. }
  8638. if (s.gzindex === s.gzhead.extra.length) {
  8639. s.gzindex = 0;
  8640. s.status = NAME_STATE;
  8641. }
  8642. }
  8643. else {
  8644. s.status = NAME_STATE;
  8645. }
  8646. }
  8647. if (s.status === NAME_STATE) {
  8648. if (s.gzhead.name/* != Z_NULL*/) {
  8649. beg = s.pending; /* start of bytes to update crc */
  8650. //int val;
  8651. do {
  8652. if (s.pending === s.pending_buf_size) {
  8653. if (s.gzhead.hcrc && s.pending > beg) {
  8654. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8655. }
  8656. flush_pending(strm);
  8657. beg = s.pending;
  8658. if (s.pending === s.pending_buf_size) {
  8659. val = 1;
  8660. break;
  8661. }
  8662. }
  8663. // JS specific: little magic to add zero terminator to end of string
  8664. if (s.gzindex < s.gzhead.name.length) {
  8665. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  8666. } else {
  8667. val = 0;
  8668. }
  8669. put_byte(s, val);
  8670. } while (val !== 0);
  8671. if (s.gzhead.hcrc && s.pending > beg) {
  8672. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8673. }
  8674. if (val === 0) {
  8675. s.gzindex = 0;
  8676. s.status = COMMENT_STATE;
  8677. }
  8678. }
  8679. else {
  8680. s.status = COMMENT_STATE;
  8681. }
  8682. }
  8683. if (s.status === COMMENT_STATE) {
  8684. if (s.gzhead.comment/* != Z_NULL*/) {
  8685. beg = s.pending; /* start of bytes to update crc */
  8686. //int val;
  8687. do {
  8688. if (s.pending === s.pending_buf_size) {
  8689. if (s.gzhead.hcrc && s.pending > beg) {
  8690. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8691. }
  8692. flush_pending(strm);
  8693. beg = s.pending;
  8694. if (s.pending === s.pending_buf_size) {
  8695. val = 1;
  8696. break;
  8697. }
  8698. }
  8699. // JS specific: little magic to add zero terminator to end of string
  8700. if (s.gzindex < s.gzhead.comment.length) {
  8701. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  8702. } else {
  8703. val = 0;
  8704. }
  8705. put_byte(s, val);
  8706. } while (val !== 0);
  8707. if (s.gzhead.hcrc && s.pending > beg) {
  8708. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8709. }
  8710. if (val === 0) {
  8711. s.status = HCRC_STATE;
  8712. }
  8713. }
  8714. else {
  8715. s.status = HCRC_STATE;
  8716. }
  8717. }
  8718. if (s.status === HCRC_STATE) {
  8719. if (s.gzhead.hcrc) {
  8720. if (s.pending + 2 > s.pending_buf_size) {
  8721. flush_pending(strm);
  8722. }
  8723. if (s.pending + 2 <= s.pending_buf_size) {
  8724. put_byte(s, strm.adler & 0xff);
  8725. put_byte(s, (strm.adler >> 8) & 0xff);
  8726. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  8727. s.status = BUSY_STATE;
  8728. }
  8729. }
  8730. else {
  8731. s.status = BUSY_STATE;
  8732. }
  8733. }
  8734. //#endif
  8735. /* Flush as much pending output as possible */
  8736. if (s.pending !== 0) {
  8737. flush_pending(strm);
  8738. if (strm.avail_out === 0) {
  8739. /* Since avail_out is 0, deflate will be called again with
  8740. * more output space, but possibly with both pending and
  8741. * avail_in equal to zero. There won't be anything to do,
  8742. * but this is not an error situation so make sure we
  8743. * return OK instead of BUF_ERROR at next call of deflate:
  8744. */
  8745. s.last_flush = -1;
  8746. return Z_OK;
  8747. }
  8748. /* Make sure there is something to do and avoid duplicate consecutive
  8749. * flushes. For repeated and useless calls with Z_FINISH, we keep
  8750. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  8751. */
  8752. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  8753. flush !== Z_FINISH) {
  8754. return err(strm, Z_BUF_ERROR);
  8755. }
  8756. /* User must not provide more input after the first FINISH: */
  8757. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  8758. return err(strm, Z_BUF_ERROR);
  8759. }
  8760. /* Start a new block or continue the current one.
  8761. */
  8762. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  8763. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  8764. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  8765. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  8766. configuration_table[s.level].func(s, flush));
  8767. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  8768. s.status = FINISH_STATE;
  8769. }
  8770. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  8771. if (strm.avail_out === 0) {
  8772. s.last_flush = -1;
  8773. /* avoid BUF_ERROR next call, see above */
  8774. }
  8775. return Z_OK;
  8776. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  8777. * of deflate should use the same flush parameter to make sure
  8778. * that the flush is complete. So we don't have to output an
  8779. * empty block here, this will be done at next call. This also
  8780. * ensures that for a very small output buffer, we emit at most
  8781. * one empty block.
  8782. */
  8783. }
  8784. if (bstate === BS_BLOCK_DONE) {
  8785. if (flush === Z_PARTIAL_FLUSH) {
  8786. trees._tr_align(s);
  8787. }
  8788. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  8789. trees._tr_stored_block(s, 0, 0, false);
  8790. /* For a full flush, this empty block will be recognized
  8791. * as a special marker by inflate_sync().
  8792. */
  8793. if (flush === Z_FULL_FLUSH) {
  8794. /*** CLEAR_HASH(s); ***/ /* forget history */
  8795. zero(s.head); // Fill with NIL (= 0);
  8796. if (s.lookahead === 0) {
  8797. s.strstart = 0;
  8798. s.block_start = 0;
  8799. s.insert = 0;
  8800. }
  8801. }
  8802. }
  8803. flush_pending(strm);
  8804. if (strm.avail_out === 0) {
  8805. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  8806. return Z_OK;
  8807. }
  8808. }
  8809. }
  8810. //Assert(strm->avail_out > 0, "bug2");
  8811. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  8812. if (flush !== Z_FINISH) { return Z_OK; }
  8813. if (s.wrap <= 0) { return Z_STREAM_END; }
  8814. /* Write the trailer */
  8815. if (s.wrap === 2) {
  8816. put_byte(s, strm.adler & 0xff);
  8817. put_byte(s, (strm.adler >> 8) & 0xff);
  8818. put_byte(s, (strm.adler >> 16) & 0xff);
  8819. put_byte(s, (strm.adler >> 24) & 0xff);
  8820. put_byte(s, strm.total_in & 0xff);
  8821. put_byte(s, (strm.total_in >> 8) & 0xff);
  8822. put_byte(s, (strm.total_in >> 16) & 0xff);
  8823. put_byte(s, (strm.total_in >> 24) & 0xff);
  8824. }
  8825. else
  8826. {
  8827. putShortMSB(s, strm.adler >>> 16);
  8828. putShortMSB(s, strm.adler & 0xffff);
  8829. }
  8830. flush_pending(strm);
  8831. /* If avail_out is zero, the application will call deflate again
  8832. * to flush the rest.
  8833. */
  8834. if (s.wrap > 0) { s.wrap = -s.wrap; }
  8835. /* write the trailer only once! */
  8836. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  8837. }
  8838. function deflateEnd(strm) {
  8839. var status;
  8840. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8841. return Z_STREAM_ERROR;
  8842. }
  8843. status = strm.state.status;
  8844. if (status !== INIT_STATE &&
  8845. status !== EXTRA_STATE &&
  8846. status !== NAME_STATE &&
  8847. status !== COMMENT_STATE &&
  8848. status !== HCRC_STATE &&
  8849. status !== BUSY_STATE &&
  8850. status !== FINISH_STATE
  8851. ) {
  8852. return err(strm, Z_STREAM_ERROR);
  8853. }
  8854. strm.state = null;
  8855. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  8856. }
  8857. /* =========================================================================
  8858. * Initializes the compression dictionary from the given byte
  8859. * sequence without producing any compressed output.
  8860. */
  8861. function deflateSetDictionary(strm, dictionary) {
  8862. var dictLength = dictionary.length;
  8863. var s;
  8864. var str, n;
  8865. var wrap;
  8866. var avail;
  8867. var next;
  8868. var input;
  8869. var tmpDict;
  8870. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8871. return Z_STREAM_ERROR;
  8872. }
  8873. s = strm.state;
  8874. wrap = s.wrap;
  8875. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  8876. return Z_STREAM_ERROR;
  8877. }
  8878. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  8879. if (wrap === 1) {
  8880. /* adler32(strm->adler, dictionary, dictLength); */
  8881. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  8882. }
  8883. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  8884. /* if dictionary would fill window, just replace the history */
  8885. if (dictLength >= s.w_size) {
  8886. if (wrap === 0) { /* already empty otherwise */
  8887. /*** CLEAR_HASH(s); ***/
  8888. zero(s.head); // Fill with NIL (= 0);
  8889. s.strstart = 0;
  8890. s.block_start = 0;
  8891. s.insert = 0;
  8892. }
  8893. /* use the tail */
  8894. // dictionary = dictionary.slice(dictLength - s.w_size);
  8895. tmpDict = new utils.Buf8(s.w_size);
  8896. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  8897. dictionary = tmpDict;
  8898. dictLength = s.w_size;
  8899. }
  8900. /* insert dictionary into window and hash */
  8901. avail = strm.avail_in;
  8902. next = strm.next_in;
  8903. input = strm.input;
  8904. strm.avail_in = dictLength;
  8905. strm.next_in = 0;
  8906. strm.input = dictionary;
  8907. fill_window(s);
  8908. while (s.lookahead >= MIN_MATCH) {
  8909. str = s.strstart;
  8910. n = s.lookahead - (MIN_MATCH - 1);
  8911. do {
  8912. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  8913. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  8914. s.prev[str & s.w_mask] = s.head[s.ins_h];
  8915. s.head[s.ins_h] = str;
  8916. str++;
  8917. } while (--n);
  8918. s.strstart = str;
  8919. s.lookahead = MIN_MATCH - 1;
  8920. fill_window(s);
  8921. }
  8922. s.strstart += s.lookahead;
  8923. s.block_start = s.strstart;
  8924. s.insert = s.lookahead;
  8925. s.lookahead = 0;
  8926. s.match_length = s.prev_length = MIN_MATCH - 1;
  8927. s.match_available = 0;
  8928. strm.next_in = next;
  8929. strm.input = input;
  8930. strm.avail_in = avail;
  8931. s.wrap = wrap;
  8932. return Z_OK;
  8933. }
  8934. exports.deflateInit = deflateInit;
  8935. exports.deflateInit2 = deflateInit2;
  8936. exports.deflateReset = deflateReset;
  8937. exports.deflateResetKeep = deflateResetKeep;
  8938. exports.deflateSetHeader = deflateSetHeader;
  8939. exports.deflate = deflate;
  8940. exports.deflateEnd = deflateEnd;
  8941. exports.deflateSetDictionary = deflateSetDictionary;
  8942. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  8943. /* Not implemented
  8944. exports.deflateBound = deflateBound;
  8945. exports.deflateCopy = deflateCopy;
  8946. exports.deflateParams = deflateParams;
  8947. exports.deflatePending = deflatePending;
  8948. exports.deflatePrime = deflatePrime;
  8949. exports.deflateTune = deflateTune;
  8950. */
  8951. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  8952. 'use strict';
  8953. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8954. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8955. //
  8956. // This software is provided 'as-is', without any express or implied
  8957. // warranty. In no event will the authors be held liable for any damages
  8958. // arising from the use of this software.
  8959. //
  8960. // Permission is granted to anyone to use this software for any purpose,
  8961. // including commercial applications, and to alter it and redistribute it
  8962. // freely, subject to the following restrictions:
  8963. //
  8964. // 1. The origin of this software must not be misrepresented; you must not
  8965. // claim that you wrote the original software. If you use this software
  8966. // in a product, an acknowledgment in the product documentation would be
  8967. // appreciated but is not required.
  8968. // 2. Altered source versions must be plainly marked as such, and must not be
  8969. // misrepresented as being the original software.
  8970. // 3. This notice may not be removed or altered from any source distribution.
  8971. function GZheader() {
  8972. /* true if compressed data believed to be text */
  8973. this.text = 0;
  8974. /* modification time */
  8975. this.time = 0;
  8976. /* extra flags (not used when writing a gzip file) */
  8977. this.xflags = 0;
  8978. /* operating system */
  8979. this.os = 0;
  8980. /* pointer to extra field or Z_NULL if none */
  8981. this.extra = null;
  8982. /* extra field length (valid if extra != Z_NULL) */
  8983. this.extra_len = 0; // Actually, we don't need it in JS,
  8984. // but leave for few code modifications
  8985. //
  8986. // Setup limits is not necessary because in js we should not preallocate memory
  8987. // for inflate use constant limit in 65536 bytes
  8988. //
  8989. /* space at extra (only when reading header) */
  8990. // this.extra_max = 0;
  8991. /* pointer to zero-terminated file name or Z_NULL */
  8992. this.name = '';
  8993. /* space at name (only when reading header) */
  8994. // this.name_max = 0;
  8995. /* pointer to zero-terminated comment or Z_NULL */
  8996. this.comment = '';
  8997. /* space at comment (only when reading header) */
  8998. // this.comm_max = 0;
  8999. /* true if there was or will be a header crc */
  9000. this.hcrc = 0;
  9001. /* true when done reading gzip header (not used when writing a gzip file) */
  9002. this.done = false;
  9003. }
  9004. module.exports = GZheader;
  9005. },{}],58:[function(require,module,exports){
  9006. 'use strict';
  9007. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9008. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9009. //
  9010. // This software is provided 'as-is', without any express or implied
  9011. // warranty. In no event will the authors be held liable for any damages
  9012. // arising from the use of this software.
  9013. //
  9014. // Permission is granted to anyone to use this software for any purpose,
  9015. // including commercial applications, and to alter it and redistribute it
  9016. // freely, subject to the following restrictions:
  9017. //
  9018. // 1. The origin of this software must not be misrepresented; you must not
  9019. // claim that you wrote the original software. If you use this software
  9020. // in a product, an acknowledgment in the product documentation would be
  9021. // appreciated but is not required.
  9022. // 2. Altered source versions must be plainly marked as such, and must not be
  9023. // misrepresented as being the original software.
  9024. // 3. This notice may not be removed or altered from any source distribution.
  9025. // See state defs from inflate.js
  9026. var BAD = 30; /* got a data error -- remain here until reset */
  9027. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  9028. /*
  9029. Decode literal, length, and distance codes and write out the resulting
  9030. literal and match bytes until either not enough input or output is
  9031. available, an end-of-block is encountered, or a data error is encountered.
  9032. When large enough input and output buffers are supplied to inflate(), for
  9033. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  9034. inflate execution time is spent in this routine.
  9035. Entry assumptions:
  9036. state.mode === LEN
  9037. strm.avail_in >= 6
  9038. strm.avail_out >= 258
  9039. start >= strm.avail_out
  9040. state.bits < 8
  9041. On return, state.mode is one of:
  9042. LEN -- ran out of enough output space or enough available input
  9043. TYPE -- reached end of block code, inflate() to interpret next block
  9044. BAD -- error in block data
  9045. Notes:
  9046. - The maximum input bits used by a length/distance pair is 15 bits for the
  9047. length code, 5 bits for the length extra, 15 bits for the distance code,
  9048. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  9049. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  9050. checking for available input while decoding.
  9051. - The maximum bytes that a single length/distance pair can output is 258
  9052. bytes, which is the maximum length that can be coded. inflate_fast()
  9053. requires strm.avail_out >= 258 for each loop to avoid checking for
  9054. output space.
  9055. */
  9056. module.exports = function inflate_fast(strm, start) {
  9057. var state;
  9058. var _in; /* local strm.input */
  9059. var last; /* have enough input while in < last */
  9060. var _out; /* local strm.output */
  9061. var beg; /* inflate()'s initial strm.output */
  9062. var end; /* while out < end, enough space available */
  9063. //#ifdef INFLATE_STRICT
  9064. var dmax; /* maximum distance from zlib header */
  9065. //#endif
  9066. var wsize; /* window size or zero if not using window */
  9067. var whave; /* valid bytes in the window */
  9068. var wnext; /* window write index */
  9069. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  9070. var s_window; /* allocated sliding window, if wsize != 0 */
  9071. var hold; /* local strm.hold */
  9072. var bits; /* local strm.bits */
  9073. var lcode; /* local strm.lencode */
  9074. var dcode; /* local strm.distcode */
  9075. var lmask; /* mask for first level of length codes */
  9076. var dmask; /* mask for first level of distance codes */
  9077. var here; /* retrieved table entry */
  9078. var op; /* code bits, operation, extra bits, or */
  9079. /* window position, window bytes to copy */
  9080. var len; /* match length, unused bytes */
  9081. var dist; /* match distance */
  9082. var from; /* where to copy match from */
  9083. var from_source;
  9084. var input, output; // JS specific, because we have no pointers
  9085. /* copy state to local variables */
  9086. state = strm.state;
  9087. //here = state.here;
  9088. _in = strm.next_in;
  9089. input = strm.input;
  9090. last = _in + (strm.avail_in - 5);
  9091. _out = strm.next_out;
  9092. output = strm.output;
  9093. beg = _out - (start - strm.avail_out);
  9094. end = _out + (strm.avail_out - 257);
  9095. //#ifdef INFLATE_STRICT
  9096. dmax = state.dmax;
  9097. //#endif
  9098. wsize = state.wsize;
  9099. whave = state.whave;
  9100. wnext = state.wnext;
  9101. s_window = state.window;
  9102. hold = state.hold;
  9103. bits = state.bits;
  9104. lcode = state.lencode;
  9105. dcode = state.distcode;
  9106. lmask = (1 << state.lenbits) - 1;
  9107. dmask = (1 << state.distbits) - 1;
  9108. /* decode literals and length/distances until end-of-block or not enough
  9109. input data or output space */
  9110. top:
  9111. do {
  9112. if (bits < 15) {
  9113. hold += input[_in++] << bits;
  9114. bits += 8;
  9115. hold += input[_in++] << bits;
  9116. bits += 8;
  9117. }
  9118. here = lcode[hold & lmask];
  9119. dolen:
  9120. for (;;) { // Goto emulation
  9121. op = here >>> 24/*here.bits*/;
  9122. hold >>>= op;
  9123. bits -= op;
  9124. op = (here >>> 16) & 0xff/*here.op*/;
  9125. if (op === 0) { /* literal */
  9126. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9127. // "inflate: literal '%c'\n" :
  9128. // "inflate: literal 0x%02x\n", here.val));
  9129. output[_out++] = here & 0xffff/*here.val*/;
  9130. }
  9131. else if (op & 16) { /* length base */
  9132. len = here & 0xffff/*here.val*/;
  9133. op &= 15; /* number of extra bits */
  9134. if (op) {
  9135. if (bits < op) {
  9136. hold += input[_in++] << bits;
  9137. bits += 8;
  9138. }
  9139. len += hold & ((1 << op) - 1);
  9140. hold >>>= op;
  9141. bits -= op;
  9142. }
  9143. //Tracevv((stderr, "inflate: length %u\n", len));
  9144. if (bits < 15) {
  9145. hold += input[_in++] << bits;
  9146. bits += 8;
  9147. hold += input[_in++] << bits;
  9148. bits += 8;
  9149. }
  9150. here = dcode[hold & dmask];
  9151. dodist:
  9152. for (;;) { // goto emulation
  9153. op = here >>> 24/*here.bits*/;
  9154. hold >>>= op;
  9155. bits -= op;
  9156. op = (here >>> 16) & 0xff/*here.op*/;
  9157. if (op & 16) { /* distance base */
  9158. dist = here & 0xffff/*here.val*/;
  9159. op &= 15; /* number of extra bits */
  9160. if (bits < op) {
  9161. hold += input[_in++] << bits;
  9162. bits += 8;
  9163. if (bits < op) {
  9164. hold += input[_in++] << bits;
  9165. bits += 8;
  9166. }
  9167. }
  9168. dist += hold & ((1 << op) - 1);
  9169. //#ifdef INFLATE_STRICT
  9170. if (dist > dmax) {
  9171. strm.msg = 'invalid distance too far back';
  9172. state.mode = BAD;
  9173. break top;
  9174. }
  9175. //#endif
  9176. hold >>>= op;
  9177. bits -= op;
  9178. //Tracevv((stderr, "inflate: distance %u\n", dist));
  9179. op = _out - beg; /* max distance in output */
  9180. if (dist > op) { /* see if copy from window */
  9181. op = dist - op; /* distance back in window */
  9182. if (op > whave) {
  9183. if (state.sane) {
  9184. strm.msg = 'invalid distance too far back';
  9185. state.mode = BAD;
  9186. break top;
  9187. }
  9188. // (!) This block is disabled in zlib defaults,
  9189. // don't enable it for binary compatibility
  9190. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9191. // if (len <= op - whave) {
  9192. // do {
  9193. // output[_out++] = 0;
  9194. // } while (--len);
  9195. // continue top;
  9196. // }
  9197. // len -= op - whave;
  9198. // do {
  9199. // output[_out++] = 0;
  9200. // } while (--op > whave);
  9201. // if (op === 0) {
  9202. // from = _out - dist;
  9203. // do {
  9204. // output[_out++] = output[from++];
  9205. // } while (--len);
  9206. // continue top;
  9207. // }
  9208. //#endif
  9209. }
  9210. from = 0; // window index
  9211. from_source = s_window;
  9212. if (wnext === 0) { /* very common case */
  9213. from += wsize - op;
  9214. if (op < len) { /* some from window */
  9215. len -= op;
  9216. do {
  9217. output[_out++] = s_window[from++];
  9218. } while (--op);
  9219. from = _out - dist; /* rest from output */
  9220. from_source = output;
  9221. }
  9222. }
  9223. else if (wnext < op) { /* wrap around window */
  9224. from += wsize + wnext - op;
  9225. op -= wnext;
  9226. if (op < len) { /* some from end of window */
  9227. len -= op;
  9228. do {
  9229. output[_out++] = s_window[from++];
  9230. } while (--op);
  9231. from = 0;
  9232. if (wnext < len) { /* some from start of window */
  9233. op = wnext;
  9234. len -= op;
  9235. do {
  9236. output[_out++] = s_window[from++];
  9237. } while (--op);
  9238. from = _out - dist; /* rest from output */
  9239. from_source = output;
  9240. }
  9241. }
  9242. }
  9243. else { /* contiguous in window */
  9244. from += wnext - op;
  9245. if (op < len) { /* some from window */
  9246. len -= op;
  9247. do {
  9248. output[_out++] = s_window[from++];
  9249. } while (--op);
  9250. from = _out - dist; /* rest from output */
  9251. from_source = output;
  9252. }
  9253. }
  9254. while (len > 2) {
  9255. output[_out++] = from_source[from++];
  9256. output[_out++] = from_source[from++];
  9257. output[_out++] = from_source[from++];
  9258. len -= 3;
  9259. }
  9260. if (len) {
  9261. output[_out++] = from_source[from++];
  9262. if (len > 1) {
  9263. output[_out++] = from_source[from++];
  9264. }
  9265. }
  9266. }
  9267. else {
  9268. from = _out - dist; /* copy direct from output */
  9269. do { /* minimum length is three */
  9270. output[_out++] = output[from++];
  9271. output[_out++] = output[from++];
  9272. output[_out++] = output[from++];
  9273. len -= 3;
  9274. } while (len > 2);
  9275. if (len) {
  9276. output[_out++] = output[from++];
  9277. if (len > 1) {
  9278. output[_out++] = output[from++];
  9279. }
  9280. }
  9281. }
  9282. }
  9283. else if ((op & 64) === 0) { /* 2nd level distance code */
  9284. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  9285. continue dodist;
  9286. }
  9287. else {
  9288. strm.msg = 'invalid distance code';
  9289. state.mode = BAD;
  9290. break top;
  9291. }
  9292. break; // need to emulate goto via "continue"
  9293. }
  9294. }
  9295. else if ((op & 64) === 0) { /* 2nd level length code */
  9296. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  9297. continue dolen;
  9298. }
  9299. else if (op & 32) { /* end-of-block */
  9300. //Tracevv((stderr, "inflate: end of block\n"));
  9301. state.mode = TYPE;
  9302. break top;
  9303. }
  9304. else {
  9305. strm.msg = 'invalid literal/length code';
  9306. state.mode = BAD;
  9307. break top;
  9308. }
  9309. break; // need to emulate goto via "continue"
  9310. }
  9311. } while (_in < last && _out < end);
  9312. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  9313. len = bits >> 3;
  9314. _in -= len;
  9315. bits -= len << 3;
  9316. hold &= (1 << bits) - 1;
  9317. /* update state and return */
  9318. strm.next_in = _in;
  9319. strm.next_out = _out;
  9320. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  9321. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  9322. state.hold = hold;
  9323. state.bits = bits;
  9324. return;
  9325. };
  9326. },{}],59:[function(require,module,exports){
  9327. 'use strict';
  9328. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9329. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9330. //
  9331. // This software is provided 'as-is', without any express or implied
  9332. // warranty. In no event will the authors be held liable for any damages
  9333. // arising from the use of this software.
  9334. //
  9335. // Permission is granted to anyone to use this software for any purpose,
  9336. // including commercial applications, and to alter it and redistribute it
  9337. // freely, subject to the following restrictions:
  9338. //
  9339. // 1. The origin of this software must not be misrepresented; you must not
  9340. // claim that you wrote the original software. If you use this software
  9341. // in a product, an acknowledgment in the product documentation would be
  9342. // appreciated but is not required.
  9343. // 2. Altered source versions must be plainly marked as such, and must not be
  9344. // misrepresented as being the original software.
  9345. // 3. This notice may not be removed or altered from any source distribution.
  9346. var utils = require('../utils/common');
  9347. var adler32 = require('./adler32');
  9348. var crc32 = require('./crc32');
  9349. var inflate_fast = require('./inffast');
  9350. var inflate_table = require('./inftrees');
  9351. var CODES = 0;
  9352. var LENS = 1;
  9353. var DISTS = 2;
  9354. /* Public constants ==========================================================*/
  9355. /* ===========================================================================*/
  9356. /* Allowed flush values; see deflate() and inflate() below for details */
  9357. //var Z_NO_FLUSH = 0;
  9358. //var Z_PARTIAL_FLUSH = 1;
  9359. //var Z_SYNC_FLUSH = 2;
  9360. //var Z_FULL_FLUSH = 3;
  9361. var Z_FINISH = 4;
  9362. var Z_BLOCK = 5;
  9363. var Z_TREES = 6;
  9364. /* Return codes for the compression/decompression functions. Negative values
  9365. * are errors, positive values are used for special but normal events.
  9366. */
  9367. var Z_OK = 0;
  9368. var Z_STREAM_END = 1;
  9369. var Z_NEED_DICT = 2;
  9370. //var Z_ERRNO = -1;
  9371. var Z_STREAM_ERROR = -2;
  9372. var Z_DATA_ERROR = -3;
  9373. var Z_MEM_ERROR = -4;
  9374. var Z_BUF_ERROR = -5;
  9375. //var Z_VERSION_ERROR = -6;
  9376. /* The deflate compression method */
  9377. var Z_DEFLATED = 8;
  9378. /* STATES ====================================================================*/
  9379. /* ===========================================================================*/
  9380. var HEAD = 1; /* i: waiting for magic header */
  9381. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  9382. var TIME = 3; /* i: waiting for modification time (gzip) */
  9383. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  9384. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  9385. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  9386. var NAME = 7; /* i: waiting for end of file name (gzip) */
  9387. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  9388. var HCRC = 9; /* i: waiting for header crc (gzip) */
  9389. var DICTID = 10; /* i: waiting for dictionary check value */
  9390. var DICT = 11; /* waiting for inflateSetDictionary() call */
  9391. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  9392. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  9393. var STORED = 14; /* i: waiting for stored size (length and complement) */
  9394. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  9395. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  9396. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  9397. var LENLENS = 18; /* i: waiting for code length code lengths */
  9398. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  9399. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  9400. var LEN = 21; /* i: waiting for length/lit/eob code */
  9401. var LENEXT = 22; /* i: waiting for length extra bits */
  9402. var DIST = 23; /* i: waiting for distance code */
  9403. var DISTEXT = 24; /* i: waiting for distance extra bits */
  9404. var MATCH = 25; /* o: waiting for output space to copy string */
  9405. var LIT = 26; /* o: waiting for output space to write literal */
  9406. var CHECK = 27; /* i: waiting for 32-bit check value */
  9407. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  9408. var DONE = 29; /* finished check, done -- remain here until reset */
  9409. var BAD = 30; /* got a data error -- remain here until reset */
  9410. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  9411. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  9412. /* ===========================================================================*/
  9413. var ENOUGH_LENS = 852;
  9414. var ENOUGH_DISTS = 592;
  9415. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9416. var MAX_WBITS = 15;
  9417. /* 32K LZ77 window */
  9418. var DEF_WBITS = MAX_WBITS;
  9419. function zswap32(q) {
  9420. return (((q >>> 24) & 0xff) +
  9421. ((q >>> 8) & 0xff00) +
  9422. ((q & 0xff00) << 8) +
  9423. ((q & 0xff) << 24));
  9424. }
  9425. function InflateState() {
  9426. this.mode = 0; /* current inflate mode */
  9427. this.last = false; /* true if processing last block */
  9428. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  9429. this.havedict = false; /* true if dictionary provided */
  9430. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  9431. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  9432. this.check = 0; /* protected copy of check value */
  9433. this.total = 0; /* protected copy of output count */
  9434. // TODO: may be {}
  9435. this.head = null; /* where to save gzip header information */
  9436. /* sliding window */
  9437. this.wbits = 0; /* log base 2 of requested window size */
  9438. this.wsize = 0; /* window size or zero if not using window */
  9439. this.whave = 0; /* valid bytes in the window */
  9440. this.wnext = 0; /* window write index */
  9441. this.window = null; /* allocated sliding window, if needed */
  9442. /* bit accumulator */
  9443. this.hold = 0; /* input bit accumulator */
  9444. this.bits = 0; /* number of bits in "in" */
  9445. /* for string and stored block copying */
  9446. this.length = 0; /* literal or length of data to copy */
  9447. this.offset = 0; /* distance back to copy string from */
  9448. /* for table and code decoding */
  9449. this.extra = 0; /* extra bits needed */
  9450. /* fixed and dynamic code tables */
  9451. this.lencode = null; /* starting table for length/literal codes */
  9452. this.distcode = null; /* starting table for distance codes */
  9453. this.lenbits = 0; /* index bits for lencode */
  9454. this.distbits = 0; /* index bits for distcode */
  9455. /* dynamic table building */
  9456. this.ncode = 0; /* number of code length code lengths */
  9457. this.nlen = 0; /* number of length code lengths */
  9458. this.ndist = 0; /* number of distance code lengths */
  9459. this.have = 0; /* number of code lengths in lens[] */
  9460. this.next = null; /* next available space in codes[] */
  9461. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  9462. this.work = new utils.Buf16(288); /* work area for code table building */
  9463. /*
  9464. because we don't have pointers in js, we use lencode and distcode directly
  9465. as buffers so we don't need codes
  9466. */
  9467. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  9468. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  9469. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  9470. this.sane = 0; /* if false, allow invalid distance too far */
  9471. this.back = 0; /* bits back of last unprocessed length/lit */
  9472. this.was = 0; /* initial length of match */
  9473. }
  9474. function inflateResetKeep(strm) {
  9475. var state;
  9476. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9477. state = strm.state;
  9478. strm.total_in = strm.total_out = state.total = 0;
  9479. strm.msg = ''; /*Z_NULL*/
  9480. if (state.wrap) { /* to support ill-conceived Java test suite */
  9481. strm.adler = state.wrap & 1;
  9482. }
  9483. state.mode = HEAD;
  9484. state.last = 0;
  9485. state.havedict = 0;
  9486. state.dmax = 32768;
  9487. state.head = null/*Z_NULL*/;
  9488. state.hold = 0;
  9489. state.bits = 0;
  9490. //state.lencode = state.distcode = state.next = state.codes;
  9491. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  9492. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  9493. state.sane = 1;
  9494. state.back = -1;
  9495. //Tracev((stderr, "inflate: reset\n"));
  9496. return Z_OK;
  9497. }
  9498. function inflateReset(strm) {
  9499. var state;
  9500. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9501. state = strm.state;
  9502. state.wsize = 0;
  9503. state.whave = 0;
  9504. state.wnext = 0;
  9505. return inflateResetKeep(strm);
  9506. }
  9507. function inflateReset2(strm, windowBits) {
  9508. var wrap;
  9509. var state;
  9510. /* get the state */
  9511. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9512. state = strm.state;
  9513. /* extract wrap request from windowBits parameter */
  9514. if (windowBits < 0) {
  9515. wrap = 0;
  9516. windowBits = -windowBits;
  9517. }
  9518. else {
  9519. wrap = (windowBits >> 4) + 1;
  9520. if (windowBits < 48) {
  9521. windowBits &= 15;
  9522. }
  9523. }
  9524. /* set number of window bits, free window if different */
  9525. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  9526. return Z_STREAM_ERROR;
  9527. }
  9528. if (state.window !== null && state.wbits !== windowBits) {
  9529. state.window = null;
  9530. }
  9531. /* update state and reset the rest of it */
  9532. state.wrap = wrap;
  9533. state.wbits = windowBits;
  9534. return inflateReset(strm);
  9535. }
  9536. function inflateInit2(strm, windowBits) {
  9537. var ret;
  9538. var state;
  9539. if (!strm) { return Z_STREAM_ERROR; }
  9540. //strm.msg = Z_NULL; /* in case we return an error */
  9541. state = new InflateState();
  9542. //if (state === Z_NULL) return Z_MEM_ERROR;
  9543. //Tracev((stderr, "inflate: allocated\n"));
  9544. strm.state = state;
  9545. state.window = null/*Z_NULL*/;
  9546. ret = inflateReset2(strm, windowBits);
  9547. if (ret !== Z_OK) {
  9548. strm.state = null/*Z_NULL*/;
  9549. }
  9550. return ret;
  9551. }
  9552. function inflateInit(strm) {
  9553. return inflateInit2(strm, DEF_WBITS);
  9554. }
  9555. /*
  9556. Return state with length and distance decoding tables and index sizes set to
  9557. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  9558. If BUILDFIXED is defined, then instead this routine builds the tables the
  9559. first time it's called, and returns those tables the first time and
  9560. thereafter. This reduces the size of the code by about 2K bytes, in
  9561. exchange for a little execution time. However, BUILDFIXED should not be
  9562. used for threaded applications, since the rewriting of the tables and virgin
  9563. may not be thread-safe.
  9564. */
  9565. var virgin = true;
  9566. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  9567. function fixedtables(state) {
  9568. /* build fixed huffman tables if first call (may not be thread safe) */
  9569. if (virgin) {
  9570. var sym;
  9571. lenfix = new utils.Buf32(512);
  9572. distfix = new utils.Buf32(32);
  9573. /* literal/length table */
  9574. sym = 0;
  9575. while (sym < 144) { state.lens[sym++] = 8; }
  9576. while (sym < 256) { state.lens[sym++] = 9; }
  9577. while (sym < 280) { state.lens[sym++] = 7; }
  9578. while (sym < 288) { state.lens[sym++] = 8; }
  9579. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  9580. /* distance table */
  9581. sym = 0;
  9582. while (sym < 32) { state.lens[sym++] = 5; }
  9583. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  9584. /* do this just once */
  9585. virgin = false;
  9586. }
  9587. state.lencode = lenfix;
  9588. state.lenbits = 9;
  9589. state.distcode = distfix;
  9590. state.distbits = 5;
  9591. }
  9592. /*
  9593. Update the window with the last wsize (normally 32K) bytes written before
  9594. returning. If window does not exist yet, create it. This is only called
  9595. when a window is already in use, or when output has been written during this
  9596. inflate call, but the end of the deflate stream has not been reached yet.
  9597. It is also called to create a window for dictionary data when a dictionary
  9598. is loaded.
  9599. Providing output buffers larger than 32K to inflate() should provide a speed
  9600. advantage, since only the last 32K of output is copied to the sliding window
  9601. upon return from inflate(), and since all distances after the first 32K of
  9602. output will fall in the output data, making match copies simpler and faster.
  9603. The advantage may be dependent on the size of the processor's data caches.
  9604. */
  9605. function updatewindow(strm, src, end, copy) {
  9606. var dist;
  9607. var state = strm.state;
  9608. /* if it hasn't been done already, allocate space for the window */
  9609. if (state.window === null) {
  9610. state.wsize = 1 << state.wbits;
  9611. state.wnext = 0;
  9612. state.whave = 0;
  9613. state.window = new utils.Buf8(state.wsize);
  9614. }
  9615. /* copy state->wsize or less output bytes into the circular window */
  9616. if (copy >= state.wsize) {
  9617. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  9618. state.wnext = 0;
  9619. state.whave = state.wsize;
  9620. }
  9621. else {
  9622. dist = state.wsize - state.wnext;
  9623. if (dist > copy) {
  9624. dist = copy;
  9625. }
  9626. //zmemcpy(state->window + state->wnext, end - copy, dist);
  9627. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  9628. copy -= dist;
  9629. if (copy) {
  9630. //zmemcpy(state->window, end - copy, copy);
  9631. utils.arraySet(state.window, src, end - copy, copy, 0);
  9632. state.wnext = copy;
  9633. state.whave = state.wsize;
  9634. }
  9635. else {
  9636. state.wnext += dist;
  9637. if (state.wnext === state.wsize) { state.wnext = 0; }
  9638. if (state.whave < state.wsize) { state.whave += dist; }
  9639. }
  9640. }
  9641. return 0;
  9642. }
  9643. function inflate(strm, flush) {
  9644. var state;
  9645. var input, output; // input/output buffers
  9646. var next; /* next input INDEX */
  9647. var put; /* next output INDEX */
  9648. var have, left; /* available input and output */
  9649. var hold; /* bit buffer */
  9650. var bits; /* bits in bit buffer */
  9651. var _in, _out; /* save starting available input and output */
  9652. var copy; /* number of stored or match bytes to copy */
  9653. var from; /* where to copy match bytes from */
  9654. var from_source;
  9655. var here = 0; /* current decoding table entry */
  9656. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  9657. //var last; /* parent table entry */
  9658. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  9659. var len; /* length to copy for repeats, bits to drop */
  9660. var ret; /* return code */
  9661. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  9662. var opts;
  9663. var n; // temporary var for NEED_BITS
  9664. var order = /* permutation of code lengths */
  9665. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9666. if (!strm || !strm.state || !strm.output ||
  9667. (!strm.input && strm.avail_in !== 0)) {
  9668. return Z_STREAM_ERROR;
  9669. }
  9670. state = strm.state;
  9671. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  9672. //--- LOAD() ---
  9673. put = strm.next_out;
  9674. output = strm.output;
  9675. left = strm.avail_out;
  9676. next = strm.next_in;
  9677. input = strm.input;
  9678. have = strm.avail_in;
  9679. hold = state.hold;
  9680. bits = state.bits;
  9681. //---
  9682. _in = have;
  9683. _out = left;
  9684. ret = Z_OK;
  9685. inf_leave: // goto emulation
  9686. for (;;) {
  9687. switch (state.mode) {
  9688. case HEAD:
  9689. if (state.wrap === 0) {
  9690. state.mode = TYPEDO;
  9691. break;
  9692. }
  9693. //=== NEEDBITS(16);
  9694. while (bits < 16) {
  9695. if (have === 0) { break inf_leave; }
  9696. have--;
  9697. hold += input[next++] << bits;
  9698. bits += 8;
  9699. }
  9700. //===//
  9701. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  9702. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  9703. //=== CRC2(state.check, hold);
  9704. hbuf[0] = hold & 0xff;
  9705. hbuf[1] = (hold >>> 8) & 0xff;
  9706. state.check = crc32(state.check, hbuf, 2, 0);
  9707. //===//
  9708. //=== INITBITS();
  9709. hold = 0;
  9710. bits = 0;
  9711. //===//
  9712. state.mode = FLAGS;
  9713. break;
  9714. }
  9715. state.flags = 0; /* expect zlib header */
  9716. if (state.head) {
  9717. state.head.done = false;
  9718. }
  9719. if (!(state.wrap & 1) || /* check if zlib header allowed */
  9720. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  9721. strm.msg = 'incorrect header check';
  9722. state.mode = BAD;
  9723. break;
  9724. }
  9725. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  9726. strm.msg = 'unknown compression method';
  9727. state.mode = BAD;
  9728. break;
  9729. }
  9730. //--- DROPBITS(4) ---//
  9731. hold >>>= 4;
  9732. bits -= 4;
  9733. //---//
  9734. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  9735. if (state.wbits === 0) {
  9736. state.wbits = len;
  9737. }
  9738. else if (len > state.wbits) {
  9739. strm.msg = 'invalid window size';
  9740. state.mode = BAD;
  9741. break;
  9742. }
  9743. state.dmax = 1 << len;
  9744. //Tracev((stderr, "inflate: zlib header ok\n"));
  9745. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9746. state.mode = hold & 0x200 ? DICTID : TYPE;
  9747. //=== INITBITS();
  9748. hold = 0;
  9749. bits = 0;
  9750. //===//
  9751. break;
  9752. case FLAGS:
  9753. //=== NEEDBITS(16); */
  9754. while (bits < 16) {
  9755. if (have === 0) { break inf_leave; }
  9756. have--;
  9757. hold += input[next++] << bits;
  9758. bits += 8;
  9759. }
  9760. //===//
  9761. state.flags = hold;
  9762. if ((state.flags & 0xff) !== Z_DEFLATED) {
  9763. strm.msg = 'unknown compression method';
  9764. state.mode = BAD;
  9765. break;
  9766. }
  9767. if (state.flags & 0xe000) {
  9768. strm.msg = 'unknown header flags set';
  9769. state.mode = BAD;
  9770. break;
  9771. }
  9772. if (state.head) {
  9773. state.head.text = ((hold >> 8) & 1);
  9774. }
  9775. if (state.flags & 0x0200) {
  9776. //=== CRC2(state.check, hold);
  9777. hbuf[0] = hold & 0xff;
  9778. hbuf[1] = (hold >>> 8) & 0xff;
  9779. state.check = crc32(state.check, hbuf, 2, 0);
  9780. //===//
  9781. }
  9782. //=== INITBITS();
  9783. hold = 0;
  9784. bits = 0;
  9785. //===//
  9786. state.mode = TIME;
  9787. /* falls through */
  9788. case TIME:
  9789. //=== NEEDBITS(32); */
  9790. while (bits < 32) {
  9791. if (have === 0) { break inf_leave; }
  9792. have--;
  9793. hold += input[next++] << bits;
  9794. bits += 8;
  9795. }
  9796. //===//
  9797. if (state.head) {
  9798. state.head.time = hold;
  9799. }
  9800. if (state.flags & 0x0200) {
  9801. //=== CRC4(state.check, hold)
  9802. hbuf[0] = hold & 0xff;
  9803. hbuf[1] = (hold >>> 8) & 0xff;
  9804. hbuf[2] = (hold >>> 16) & 0xff;
  9805. hbuf[3] = (hold >>> 24) & 0xff;
  9806. state.check = crc32(state.check, hbuf, 4, 0);
  9807. //===
  9808. }
  9809. //=== INITBITS();
  9810. hold = 0;
  9811. bits = 0;
  9812. //===//
  9813. state.mode = OS;
  9814. /* falls through */
  9815. case OS:
  9816. //=== NEEDBITS(16); */
  9817. while (bits < 16) {
  9818. if (have === 0) { break inf_leave; }
  9819. have--;
  9820. hold += input[next++] << bits;
  9821. bits += 8;
  9822. }
  9823. //===//
  9824. if (state.head) {
  9825. state.head.xflags = (hold & 0xff);
  9826. state.head.os = (hold >> 8);
  9827. }
  9828. if (state.flags & 0x0200) {
  9829. //=== CRC2(state.check, hold);
  9830. hbuf[0] = hold & 0xff;
  9831. hbuf[1] = (hold >>> 8) & 0xff;
  9832. state.check = crc32(state.check, hbuf, 2, 0);
  9833. //===//
  9834. }
  9835. //=== INITBITS();
  9836. hold = 0;
  9837. bits = 0;
  9838. //===//
  9839. state.mode = EXLEN;
  9840. /* falls through */
  9841. case EXLEN:
  9842. if (state.flags & 0x0400) {
  9843. //=== NEEDBITS(16); */
  9844. while (bits < 16) {
  9845. if (have === 0) { break inf_leave; }
  9846. have--;
  9847. hold += input[next++] << bits;
  9848. bits += 8;
  9849. }
  9850. //===//
  9851. state.length = hold;
  9852. if (state.head) {
  9853. state.head.extra_len = hold;
  9854. }
  9855. if (state.flags & 0x0200) {
  9856. //=== CRC2(state.check, hold);
  9857. hbuf[0] = hold & 0xff;
  9858. hbuf[1] = (hold >>> 8) & 0xff;
  9859. state.check = crc32(state.check, hbuf, 2, 0);
  9860. //===//
  9861. }
  9862. //=== INITBITS();
  9863. hold = 0;
  9864. bits = 0;
  9865. //===//
  9866. }
  9867. else if (state.head) {
  9868. state.head.extra = null/*Z_NULL*/;
  9869. }
  9870. state.mode = EXTRA;
  9871. /* falls through */
  9872. case EXTRA:
  9873. if (state.flags & 0x0400) {
  9874. copy = state.length;
  9875. if (copy > have) { copy = have; }
  9876. if (copy) {
  9877. if (state.head) {
  9878. len = state.head.extra_len - state.length;
  9879. if (!state.head.extra) {
  9880. // Use untyped array for more convenient processing later
  9881. state.head.extra = new Array(state.head.extra_len);
  9882. }
  9883. utils.arraySet(
  9884. state.head.extra,
  9885. input,
  9886. next,
  9887. // extra field is limited to 65536 bytes
  9888. // - no need for additional size check
  9889. copy,
  9890. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  9891. len
  9892. );
  9893. //zmemcpy(state.head.extra + len, next,
  9894. // len + copy > state.head.extra_max ?
  9895. // state.head.extra_max - len : copy);
  9896. }
  9897. if (state.flags & 0x0200) {
  9898. state.check = crc32(state.check, input, copy, next);
  9899. }
  9900. have -= copy;
  9901. next += copy;
  9902. state.length -= copy;
  9903. }
  9904. if (state.length) { break inf_leave; }
  9905. }
  9906. state.length = 0;
  9907. state.mode = NAME;
  9908. /* falls through */
  9909. case NAME:
  9910. if (state.flags & 0x0800) {
  9911. if (have === 0) { break inf_leave; }
  9912. copy = 0;
  9913. do {
  9914. // TODO: 2 or 1 bytes?
  9915. len = input[next + copy++];
  9916. /* use constant limit because in js we should not preallocate memory */
  9917. if (state.head && len &&
  9918. (state.length < 65536 /*state.head.name_max*/)) {
  9919. state.head.name += String.fromCharCode(len);
  9920. }
  9921. } while (len && copy < have);
  9922. if (state.flags & 0x0200) {
  9923. state.check = crc32(state.check, input, copy, next);
  9924. }
  9925. have -= copy;
  9926. next += copy;
  9927. if (len) { break inf_leave; }
  9928. }
  9929. else if (state.head) {
  9930. state.head.name = null;
  9931. }
  9932. state.length = 0;
  9933. state.mode = COMMENT;
  9934. /* falls through */
  9935. case COMMENT:
  9936. if (state.flags & 0x1000) {
  9937. if (have === 0) { break inf_leave; }
  9938. copy = 0;
  9939. do {
  9940. len = input[next + copy++];
  9941. /* use constant limit because in js we should not preallocate memory */
  9942. if (state.head && len &&
  9943. (state.length < 65536 /*state.head.comm_max*/)) {
  9944. state.head.comment += String.fromCharCode(len);
  9945. }
  9946. } while (len && copy < have);
  9947. if (state.flags & 0x0200) {
  9948. state.check = crc32(state.check, input, copy, next);
  9949. }
  9950. have -= copy;
  9951. next += copy;
  9952. if (len) { break inf_leave; }
  9953. }
  9954. else if (state.head) {
  9955. state.head.comment = null;
  9956. }
  9957. state.mode = HCRC;
  9958. /* falls through */
  9959. case HCRC:
  9960. if (state.flags & 0x0200) {
  9961. //=== NEEDBITS(16); */
  9962. while (bits < 16) {
  9963. if (have === 0) { break inf_leave; }
  9964. have--;
  9965. hold += input[next++] << bits;
  9966. bits += 8;
  9967. }
  9968. //===//
  9969. if (hold !== (state.check & 0xffff)) {
  9970. strm.msg = 'header crc mismatch';
  9971. state.mode = BAD;
  9972. break;
  9973. }
  9974. //=== INITBITS();
  9975. hold = 0;
  9976. bits = 0;
  9977. //===//
  9978. }
  9979. if (state.head) {
  9980. state.head.hcrc = ((state.flags >> 9) & 1);
  9981. state.head.done = true;
  9982. }
  9983. strm.adler = state.check = 0;
  9984. state.mode = TYPE;
  9985. break;
  9986. case DICTID:
  9987. //=== NEEDBITS(32); */
  9988. while (bits < 32) {
  9989. if (have === 0) { break inf_leave; }
  9990. have--;
  9991. hold += input[next++] << bits;
  9992. bits += 8;
  9993. }
  9994. //===//
  9995. strm.adler = state.check = zswap32(hold);
  9996. //=== INITBITS();
  9997. hold = 0;
  9998. bits = 0;
  9999. //===//
  10000. state.mode = DICT;
  10001. /* falls through */
  10002. case DICT:
  10003. if (state.havedict === 0) {
  10004. //--- RESTORE() ---
  10005. strm.next_out = put;
  10006. strm.avail_out = left;
  10007. strm.next_in = next;
  10008. strm.avail_in = have;
  10009. state.hold = hold;
  10010. state.bits = bits;
  10011. //---
  10012. return Z_NEED_DICT;
  10013. }
  10014. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  10015. state.mode = TYPE;
  10016. /* falls through */
  10017. case TYPE:
  10018. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  10019. /* falls through */
  10020. case TYPEDO:
  10021. if (state.last) {
  10022. //--- BYTEBITS() ---//
  10023. hold >>>= bits & 7;
  10024. bits -= bits & 7;
  10025. //---//
  10026. state.mode = CHECK;
  10027. break;
  10028. }
  10029. //=== NEEDBITS(3); */
  10030. while (bits < 3) {
  10031. if (have === 0) { break inf_leave; }
  10032. have--;
  10033. hold += input[next++] << bits;
  10034. bits += 8;
  10035. }
  10036. //===//
  10037. state.last = (hold & 0x01)/*BITS(1)*/;
  10038. //--- DROPBITS(1) ---//
  10039. hold >>>= 1;
  10040. bits -= 1;
  10041. //---//
  10042. switch ((hold & 0x03)/*BITS(2)*/) {
  10043. case 0: /* stored block */
  10044. //Tracev((stderr, "inflate: stored block%s\n",
  10045. // state.last ? " (last)" : ""));
  10046. state.mode = STORED;
  10047. break;
  10048. case 1: /* fixed block */
  10049. fixedtables(state);
  10050. //Tracev((stderr, "inflate: fixed codes block%s\n",
  10051. // state.last ? " (last)" : ""));
  10052. state.mode = LEN_; /* decode codes */
  10053. if (flush === Z_TREES) {
  10054. //--- DROPBITS(2) ---//
  10055. hold >>>= 2;
  10056. bits -= 2;
  10057. //---//
  10058. break inf_leave;
  10059. }
  10060. break;
  10061. case 2: /* dynamic block */
  10062. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  10063. // state.last ? " (last)" : ""));
  10064. state.mode = TABLE;
  10065. break;
  10066. case 3:
  10067. strm.msg = 'invalid block type';
  10068. state.mode = BAD;
  10069. }
  10070. //--- DROPBITS(2) ---//
  10071. hold >>>= 2;
  10072. bits -= 2;
  10073. //---//
  10074. break;
  10075. case STORED:
  10076. //--- BYTEBITS() ---// /* go to byte boundary */
  10077. hold >>>= bits & 7;
  10078. bits -= bits & 7;
  10079. //---//
  10080. //=== NEEDBITS(32); */
  10081. while (bits < 32) {
  10082. if (have === 0) { break inf_leave; }
  10083. have--;
  10084. hold += input[next++] << bits;
  10085. bits += 8;
  10086. }
  10087. //===//
  10088. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  10089. strm.msg = 'invalid stored block lengths';
  10090. state.mode = BAD;
  10091. break;
  10092. }
  10093. state.length = hold & 0xffff;
  10094. //Tracev((stderr, "inflate: stored length %u\n",
  10095. // state.length));
  10096. //=== INITBITS();
  10097. hold = 0;
  10098. bits = 0;
  10099. //===//
  10100. state.mode = COPY_;
  10101. if (flush === Z_TREES) { break inf_leave; }
  10102. /* falls through */
  10103. case COPY_:
  10104. state.mode = COPY;
  10105. /* falls through */
  10106. case COPY:
  10107. copy = state.length;
  10108. if (copy) {
  10109. if (copy > have) { copy = have; }
  10110. if (copy > left) { copy = left; }
  10111. if (copy === 0) { break inf_leave; }
  10112. //--- zmemcpy(put, next, copy); ---
  10113. utils.arraySet(output, input, next, copy, put);
  10114. //---//
  10115. have -= copy;
  10116. next += copy;
  10117. left -= copy;
  10118. put += copy;
  10119. state.length -= copy;
  10120. break;
  10121. }
  10122. //Tracev((stderr, "inflate: stored end\n"));
  10123. state.mode = TYPE;
  10124. break;
  10125. case TABLE:
  10126. //=== NEEDBITS(14); */
  10127. while (bits < 14) {
  10128. if (have === 0) { break inf_leave; }
  10129. have--;
  10130. hold += input[next++] << bits;
  10131. bits += 8;
  10132. }
  10133. //===//
  10134. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  10135. //--- DROPBITS(5) ---//
  10136. hold >>>= 5;
  10137. bits -= 5;
  10138. //---//
  10139. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  10140. //--- DROPBITS(5) ---//
  10141. hold >>>= 5;
  10142. bits -= 5;
  10143. //---//
  10144. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  10145. //--- DROPBITS(4) ---//
  10146. hold >>>= 4;
  10147. bits -= 4;
  10148. //---//
  10149. //#ifndef PKZIP_BUG_WORKAROUND
  10150. if (state.nlen > 286 || state.ndist > 30) {
  10151. strm.msg = 'too many length or distance symbols';
  10152. state.mode = BAD;
  10153. break;
  10154. }
  10155. //#endif
  10156. //Tracev((stderr, "inflate: table sizes ok\n"));
  10157. state.have = 0;
  10158. state.mode = LENLENS;
  10159. /* falls through */
  10160. case LENLENS:
  10161. while (state.have < state.ncode) {
  10162. //=== NEEDBITS(3);
  10163. while (bits < 3) {
  10164. if (have === 0) { break inf_leave; }
  10165. have--;
  10166. hold += input[next++] << bits;
  10167. bits += 8;
  10168. }
  10169. //===//
  10170. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  10171. //--- DROPBITS(3) ---//
  10172. hold >>>= 3;
  10173. bits -= 3;
  10174. //---//
  10175. }
  10176. while (state.have < 19) {
  10177. state.lens[order[state.have++]] = 0;
  10178. }
  10179. // We have separate tables & no pointers. 2 commented lines below not needed.
  10180. //state.next = state.codes;
  10181. //state.lencode = state.next;
  10182. // Switch to use dynamic table
  10183. state.lencode = state.lendyn;
  10184. state.lenbits = 7;
  10185. opts = { bits: state.lenbits };
  10186. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  10187. state.lenbits = opts.bits;
  10188. if (ret) {
  10189. strm.msg = 'invalid code lengths set';
  10190. state.mode = BAD;
  10191. break;
  10192. }
  10193. //Tracev((stderr, "inflate: code lengths ok\n"));
  10194. state.have = 0;
  10195. state.mode = CODELENS;
  10196. /* falls through */
  10197. case CODELENS:
  10198. while (state.have < state.nlen + state.ndist) {
  10199. for (;;) {
  10200. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  10201. here_bits = here >>> 24;
  10202. here_op = (here >>> 16) & 0xff;
  10203. here_val = here & 0xffff;
  10204. if ((here_bits) <= bits) { break; }
  10205. //--- PULLBYTE() ---//
  10206. if (have === 0) { break inf_leave; }
  10207. have--;
  10208. hold += input[next++] << bits;
  10209. bits += 8;
  10210. //---//
  10211. }
  10212. if (here_val < 16) {
  10213. //--- DROPBITS(here.bits) ---//
  10214. hold >>>= here_bits;
  10215. bits -= here_bits;
  10216. //---//
  10217. state.lens[state.have++] = here_val;
  10218. }
  10219. else {
  10220. if (here_val === 16) {
  10221. //=== NEEDBITS(here.bits + 2);
  10222. n = here_bits + 2;
  10223. while (bits < n) {
  10224. if (have === 0) { break inf_leave; }
  10225. have--;
  10226. hold += input[next++] << bits;
  10227. bits += 8;
  10228. }
  10229. //===//
  10230. //--- DROPBITS(here.bits) ---//
  10231. hold >>>= here_bits;
  10232. bits -= here_bits;
  10233. //---//
  10234. if (state.have === 0) {
  10235. strm.msg = 'invalid bit length repeat';
  10236. state.mode = BAD;
  10237. break;
  10238. }
  10239. len = state.lens[state.have - 1];
  10240. copy = 3 + (hold & 0x03);//BITS(2);
  10241. //--- DROPBITS(2) ---//
  10242. hold >>>= 2;
  10243. bits -= 2;
  10244. //---//
  10245. }
  10246. else if (here_val === 17) {
  10247. //=== NEEDBITS(here.bits + 3);
  10248. n = here_bits + 3;
  10249. while (bits < n) {
  10250. if (have === 0) { break inf_leave; }
  10251. have--;
  10252. hold += input[next++] << bits;
  10253. bits += 8;
  10254. }
  10255. //===//
  10256. //--- DROPBITS(here.bits) ---//
  10257. hold >>>= here_bits;
  10258. bits -= here_bits;
  10259. //---//
  10260. len = 0;
  10261. copy = 3 + (hold & 0x07);//BITS(3);
  10262. //--- DROPBITS(3) ---//
  10263. hold >>>= 3;
  10264. bits -= 3;
  10265. //---//
  10266. }
  10267. else {
  10268. //=== NEEDBITS(here.bits + 7);
  10269. n = here_bits + 7;
  10270. while (bits < n) {
  10271. if (have === 0) { break inf_leave; }
  10272. have--;
  10273. hold += input[next++] << bits;
  10274. bits += 8;
  10275. }
  10276. //===//
  10277. //--- DROPBITS(here.bits) ---//
  10278. hold >>>= here_bits;
  10279. bits -= here_bits;
  10280. //---//
  10281. len = 0;
  10282. copy = 11 + (hold & 0x7f);//BITS(7);
  10283. //--- DROPBITS(7) ---//
  10284. hold >>>= 7;
  10285. bits -= 7;
  10286. //---//
  10287. }
  10288. if (state.have + copy > state.nlen + state.ndist) {
  10289. strm.msg = 'invalid bit length repeat';
  10290. state.mode = BAD;
  10291. break;
  10292. }
  10293. while (copy--) {
  10294. state.lens[state.have++] = len;
  10295. }
  10296. }
  10297. }
  10298. /* handle error breaks in while */
  10299. if (state.mode === BAD) { break; }
  10300. /* check for end-of-block code (better have one) */
  10301. if (state.lens[256] === 0) {
  10302. strm.msg = 'invalid code -- missing end-of-block';
  10303. state.mode = BAD;
  10304. break;
  10305. }
  10306. /* build code tables -- note: do not change the lenbits or distbits
  10307. values here (9 and 6) without reading the comments in inftrees.h
  10308. concerning the ENOUGH constants, which depend on those values */
  10309. state.lenbits = 9;
  10310. opts = { bits: state.lenbits };
  10311. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  10312. // We have separate tables & no pointers. 2 commented lines below not needed.
  10313. // state.next_index = opts.table_index;
  10314. state.lenbits = opts.bits;
  10315. // state.lencode = state.next;
  10316. if (ret) {
  10317. strm.msg = 'invalid literal/lengths set';
  10318. state.mode = BAD;
  10319. break;
  10320. }
  10321. state.distbits = 6;
  10322. //state.distcode.copy(state.codes);
  10323. // Switch to use dynamic table
  10324. state.distcode = state.distdyn;
  10325. opts = { bits: state.distbits };
  10326. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  10327. // We have separate tables & no pointers. 2 commented lines below not needed.
  10328. // state.next_index = opts.table_index;
  10329. state.distbits = opts.bits;
  10330. // state.distcode = state.next;
  10331. if (ret) {
  10332. strm.msg = 'invalid distances set';
  10333. state.mode = BAD;
  10334. break;
  10335. }
  10336. //Tracev((stderr, 'inflate: codes ok\n'));
  10337. state.mode = LEN_;
  10338. if (flush === Z_TREES) { break inf_leave; }
  10339. /* falls through */
  10340. case LEN_:
  10341. state.mode = LEN;
  10342. /* falls through */
  10343. case LEN:
  10344. if (have >= 6 && left >= 258) {
  10345. //--- RESTORE() ---
  10346. strm.next_out = put;
  10347. strm.avail_out = left;
  10348. strm.next_in = next;
  10349. strm.avail_in = have;
  10350. state.hold = hold;
  10351. state.bits = bits;
  10352. //---
  10353. inflate_fast(strm, _out);
  10354. //--- LOAD() ---
  10355. put = strm.next_out;
  10356. output = strm.output;
  10357. left = strm.avail_out;
  10358. next = strm.next_in;
  10359. input = strm.input;
  10360. have = strm.avail_in;
  10361. hold = state.hold;
  10362. bits = state.bits;
  10363. //---
  10364. if (state.mode === TYPE) {
  10365. state.back = -1;
  10366. }
  10367. break;
  10368. }
  10369. state.back = 0;
  10370. for (;;) {
  10371. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  10372. here_bits = here >>> 24;
  10373. here_op = (here >>> 16) & 0xff;
  10374. here_val = here & 0xffff;
  10375. if (here_bits <= bits) { break; }
  10376. //--- PULLBYTE() ---//
  10377. if (have === 0) { break inf_leave; }
  10378. have--;
  10379. hold += input[next++] << bits;
  10380. bits += 8;
  10381. //---//
  10382. }
  10383. if (here_op && (here_op & 0xf0) === 0) {
  10384. last_bits = here_bits;
  10385. last_op = here_op;
  10386. last_val = here_val;
  10387. for (;;) {
  10388. here = state.lencode[last_val +
  10389. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  10390. here_bits = here >>> 24;
  10391. here_op = (here >>> 16) & 0xff;
  10392. here_val = here & 0xffff;
  10393. if ((last_bits + here_bits) <= bits) { break; }
  10394. //--- PULLBYTE() ---//
  10395. if (have === 0) { break inf_leave; }
  10396. have--;
  10397. hold += input[next++] << bits;
  10398. bits += 8;
  10399. //---//
  10400. }
  10401. //--- DROPBITS(last.bits) ---//
  10402. hold >>>= last_bits;
  10403. bits -= last_bits;
  10404. //---//
  10405. state.back += last_bits;
  10406. }
  10407. //--- DROPBITS(here.bits) ---//
  10408. hold >>>= here_bits;
  10409. bits -= here_bits;
  10410. //---//
  10411. state.back += here_bits;
  10412. state.length = here_val;
  10413. if (here_op === 0) {
  10414. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  10415. // "inflate: literal '%c'\n" :
  10416. // "inflate: literal 0x%02x\n", here.val));
  10417. state.mode = LIT;
  10418. break;
  10419. }
  10420. if (here_op & 32) {
  10421. //Tracevv((stderr, "inflate: end of block\n"));
  10422. state.back = -1;
  10423. state.mode = TYPE;
  10424. break;
  10425. }
  10426. if (here_op & 64) {
  10427. strm.msg = 'invalid literal/length code';
  10428. state.mode = BAD;
  10429. break;
  10430. }
  10431. state.extra = here_op & 15;
  10432. state.mode = LENEXT;
  10433. /* falls through */
  10434. case LENEXT:
  10435. if (state.extra) {
  10436. //=== NEEDBITS(state.extra);
  10437. n = state.extra;
  10438. while (bits < n) {
  10439. if (have === 0) { break inf_leave; }
  10440. have--;
  10441. hold += input[next++] << bits;
  10442. bits += 8;
  10443. }
  10444. //===//
  10445. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  10446. //--- DROPBITS(state.extra) ---//
  10447. hold >>>= state.extra;
  10448. bits -= state.extra;
  10449. //---//
  10450. state.back += state.extra;
  10451. }
  10452. //Tracevv((stderr, "inflate: length %u\n", state.length));
  10453. state.was = state.length;
  10454. state.mode = DIST;
  10455. /* falls through */
  10456. case DIST:
  10457. for (;;) {
  10458. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  10459. here_bits = here >>> 24;
  10460. here_op = (here >>> 16) & 0xff;
  10461. here_val = here & 0xffff;
  10462. if ((here_bits) <= bits) { break; }
  10463. //--- PULLBYTE() ---//
  10464. if (have === 0) { break inf_leave; }
  10465. have--;
  10466. hold += input[next++] << bits;
  10467. bits += 8;
  10468. //---//
  10469. }
  10470. if ((here_op & 0xf0) === 0) {
  10471. last_bits = here_bits;
  10472. last_op = here_op;
  10473. last_val = here_val;
  10474. for (;;) {
  10475. here = state.distcode[last_val +
  10476. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  10477. here_bits = here >>> 24;
  10478. here_op = (here >>> 16) & 0xff;
  10479. here_val = here & 0xffff;
  10480. if ((last_bits + here_bits) <= bits) { break; }
  10481. //--- PULLBYTE() ---//
  10482. if (have === 0) { break inf_leave; }
  10483. have--;
  10484. hold += input[next++] << bits;
  10485. bits += 8;
  10486. //---//
  10487. }
  10488. //--- DROPBITS(last.bits) ---//
  10489. hold >>>= last_bits;
  10490. bits -= last_bits;
  10491. //---//
  10492. state.back += last_bits;
  10493. }
  10494. //--- DROPBITS(here.bits) ---//
  10495. hold >>>= here_bits;
  10496. bits -= here_bits;
  10497. //---//
  10498. state.back += here_bits;
  10499. if (here_op & 64) {
  10500. strm.msg = 'invalid distance code';
  10501. state.mode = BAD;
  10502. break;
  10503. }
  10504. state.offset = here_val;
  10505. state.extra = (here_op) & 15;
  10506. state.mode = DISTEXT;
  10507. /* falls through */
  10508. case DISTEXT:
  10509. if (state.extra) {
  10510. //=== NEEDBITS(state.extra);
  10511. n = state.extra;
  10512. while (bits < n) {
  10513. if (have === 0) { break inf_leave; }
  10514. have--;
  10515. hold += input[next++] << bits;
  10516. bits += 8;
  10517. }
  10518. //===//
  10519. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  10520. //--- DROPBITS(state.extra) ---//
  10521. hold >>>= state.extra;
  10522. bits -= state.extra;
  10523. //---//
  10524. state.back += state.extra;
  10525. }
  10526. //#ifdef INFLATE_STRICT
  10527. if (state.offset > state.dmax) {
  10528. strm.msg = 'invalid distance too far back';
  10529. state.mode = BAD;
  10530. break;
  10531. }
  10532. //#endif
  10533. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  10534. state.mode = MATCH;
  10535. /* falls through */
  10536. case MATCH:
  10537. if (left === 0) { break inf_leave; }
  10538. copy = _out - left;
  10539. if (state.offset > copy) { /* copy from window */
  10540. copy = state.offset - copy;
  10541. if (copy > state.whave) {
  10542. if (state.sane) {
  10543. strm.msg = 'invalid distance too far back';
  10544. state.mode = BAD;
  10545. break;
  10546. }
  10547. // (!) This block is disabled in zlib defaults,
  10548. // don't enable it for binary compatibility
  10549. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  10550. // Trace((stderr, "inflate.c too far\n"));
  10551. // copy -= state.whave;
  10552. // if (copy > state.length) { copy = state.length; }
  10553. // if (copy > left) { copy = left; }
  10554. // left -= copy;
  10555. // state.length -= copy;
  10556. // do {
  10557. // output[put++] = 0;
  10558. // } while (--copy);
  10559. // if (state.length === 0) { state.mode = LEN; }
  10560. // break;
  10561. //#endif
  10562. }
  10563. if (copy > state.wnext) {
  10564. copy -= state.wnext;
  10565. from = state.wsize - copy;
  10566. }
  10567. else {
  10568. from = state.wnext - copy;
  10569. }
  10570. if (copy > state.length) { copy = state.length; }
  10571. from_source = state.window;
  10572. }
  10573. else { /* copy from output */
  10574. from_source = output;
  10575. from = put - state.offset;
  10576. copy = state.length;
  10577. }
  10578. if (copy > left) { copy = left; }
  10579. left -= copy;
  10580. state.length -= copy;
  10581. do {
  10582. output[put++] = from_source[from++];
  10583. } while (--copy);
  10584. if (state.length === 0) { state.mode = LEN; }
  10585. break;
  10586. case LIT:
  10587. if (left === 0) { break inf_leave; }
  10588. output[put++] = state.length;
  10589. left--;
  10590. state.mode = LEN;
  10591. break;
  10592. case CHECK:
  10593. if (state.wrap) {
  10594. //=== NEEDBITS(32);
  10595. while (bits < 32) {
  10596. if (have === 0) { break inf_leave; }
  10597. have--;
  10598. // Use '|' instead of '+' to make sure that result is signed
  10599. hold |= input[next++] << bits;
  10600. bits += 8;
  10601. }
  10602. //===//
  10603. _out -= left;
  10604. strm.total_out += _out;
  10605. state.total += _out;
  10606. if (_out) {
  10607. strm.adler = state.check =
  10608. /*UPDATE(state.check, put - _out, _out);*/
  10609. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  10610. }
  10611. _out = left;
  10612. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  10613. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  10614. strm.msg = 'incorrect data check';
  10615. state.mode = BAD;
  10616. break;
  10617. }
  10618. //=== INITBITS();
  10619. hold = 0;
  10620. bits = 0;
  10621. //===//
  10622. //Tracev((stderr, "inflate: check matches trailer\n"));
  10623. }
  10624. state.mode = LENGTH;
  10625. /* falls through */
  10626. case LENGTH:
  10627. if (state.wrap && state.flags) {
  10628. //=== NEEDBITS(32);
  10629. while (bits < 32) {
  10630. if (have === 0) { break inf_leave; }
  10631. have--;
  10632. hold += input[next++] << bits;
  10633. bits += 8;
  10634. }
  10635. //===//
  10636. if (hold !== (state.total & 0xffffffff)) {
  10637. strm.msg = 'incorrect length check';
  10638. state.mode = BAD;
  10639. break;
  10640. }
  10641. //=== INITBITS();
  10642. hold = 0;
  10643. bits = 0;
  10644. //===//
  10645. //Tracev((stderr, "inflate: length matches trailer\n"));
  10646. }
  10647. state.mode = DONE;
  10648. /* falls through */
  10649. case DONE:
  10650. ret = Z_STREAM_END;
  10651. break inf_leave;
  10652. case BAD:
  10653. ret = Z_DATA_ERROR;
  10654. break inf_leave;
  10655. case MEM:
  10656. return Z_MEM_ERROR;
  10657. case SYNC:
  10658. /* falls through */
  10659. default:
  10660. return Z_STREAM_ERROR;
  10661. }
  10662. }
  10663. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  10664. /*
  10665. Return from inflate(), updating the total counts and the check value.
  10666. If there was no progress during the inflate() call, return a buffer
  10667. error. Call updatewindow() to create and/or update the window state.
  10668. Note: a memory error from inflate() is non-recoverable.
  10669. */
  10670. //--- RESTORE() ---
  10671. strm.next_out = put;
  10672. strm.avail_out = left;
  10673. strm.next_in = next;
  10674. strm.avail_in = have;
  10675. state.hold = hold;
  10676. state.bits = bits;
  10677. //---
  10678. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  10679. (state.mode < CHECK || flush !== Z_FINISH))) {
  10680. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  10681. state.mode = MEM;
  10682. return Z_MEM_ERROR;
  10683. }
  10684. }
  10685. _in -= strm.avail_in;
  10686. _out -= strm.avail_out;
  10687. strm.total_in += _in;
  10688. strm.total_out += _out;
  10689. state.total += _out;
  10690. if (state.wrap && _out) {
  10691. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  10692. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  10693. }
  10694. strm.data_type = state.bits + (state.last ? 64 : 0) +
  10695. (state.mode === TYPE ? 128 : 0) +
  10696. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  10697. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  10698. ret = Z_BUF_ERROR;
  10699. }
  10700. return ret;
  10701. }
  10702. function inflateEnd(strm) {
  10703. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  10704. return Z_STREAM_ERROR;
  10705. }
  10706. var state = strm.state;
  10707. if (state.window) {
  10708. state.window = null;
  10709. }
  10710. strm.state = null;
  10711. return Z_OK;
  10712. }
  10713. function inflateGetHeader(strm, head) {
  10714. var state;
  10715. /* check state */
  10716. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  10717. state = strm.state;
  10718. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  10719. /* save header structure */
  10720. state.head = head;
  10721. head.done = false;
  10722. return Z_OK;
  10723. }
  10724. function inflateSetDictionary(strm, dictionary) {
  10725. var dictLength = dictionary.length;
  10726. var state;
  10727. var dictid;
  10728. var ret;
  10729. /* check state */
  10730. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  10731. state = strm.state;
  10732. if (state.wrap !== 0 && state.mode !== DICT) {
  10733. return Z_STREAM_ERROR;
  10734. }
  10735. /* check for correct dictionary identifier */
  10736. if (state.mode === DICT) {
  10737. dictid = 1; /* adler32(0, null, 0)*/
  10738. /* dictid = adler32(dictid, dictionary, dictLength); */
  10739. dictid = adler32(dictid, dictionary, dictLength, 0);
  10740. if (dictid !== state.check) {
  10741. return Z_DATA_ERROR;
  10742. }
  10743. }
  10744. /* copy dictionary to window using updatewindow(), which will amend the
  10745. existing dictionary if appropriate */
  10746. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  10747. if (ret) {
  10748. state.mode = MEM;
  10749. return Z_MEM_ERROR;
  10750. }
  10751. state.havedict = 1;
  10752. // Tracev((stderr, "inflate: dictionary set\n"));
  10753. return Z_OK;
  10754. }
  10755. exports.inflateReset = inflateReset;
  10756. exports.inflateReset2 = inflateReset2;
  10757. exports.inflateResetKeep = inflateResetKeep;
  10758. exports.inflateInit = inflateInit;
  10759. exports.inflateInit2 = inflateInit2;
  10760. exports.inflate = inflate;
  10761. exports.inflateEnd = inflateEnd;
  10762. exports.inflateGetHeader = inflateGetHeader;
  10763. exports.inflateSetDictionary = inflateSetDictionary;
  10764. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  10765. /* Not implemented
  10766. exports.inflateCopy = inflateCopy;
  10767. exports.inflateGetDictionary = inflateGetDictionary;
  10768. exports.inflateMark = inflateMark;
  10769. exports.inflatePrime = inflatePrime;
  10770. exports.inflateSync = inflateSync;
  10771. exports.inflateSyncPoint = inflateSyncPoint;
  10772. exports.inflateUndermine = inflateUndermine;
  10773. */
  10774. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  10775. 'use strict';
  10776. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10777. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10778. //
  10779. // This software is provided 'as-is', without any express or implied
  10780. // warranty. In no event will the authors be held liable for any damages
  10781. // arising from the use of this software.
  10782. //
  10783. // Permission is granted to anyone to use this software for any purpose,
  10784. // including commercial applications, and to alter it and redistribute it
  10785. // freely, subject to the following restrictions:
  10786. //
  10787. // 1. The origin of this software must not be misrepresented; you must not
  10788. // claim that you wrote the original software. If you use this software
  10789. // in a product, an acknowledgment in the product documentation would be
  10790. // appreciated but is not required.
  10791. // 2. Altered source versions must be plainly marked as such, and must not be
  10792. // misrepresented as being the original software.
  10793. // 3. This notice may not be removed or altered from any source distribution.
  10794. var utils = require('../utils/common');
  10795. var MAXBITS = 15;
  10796. var ENOUGH_LENS = 852;
  10797. var ENOUGH_DISTS = 592;
  10798. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  10799. var CODES = 0;
  10800. var LENS = 1;
  10801. var DISTS = 2;
  10802. var lbase = [ /* Length codes 257..285 base */
  10803. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  10804. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  10805. ];
  10806. var lext = [ /* Length codes 257..285 extra */
  10807. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  10808. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  10809. ];
  10810. var dbase = [ /* Distance codes 0..29 base */
  10811. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  10812. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  10813. 8193, 12289, 16385, 24577, 0, 0
  10814. ];
  10815. var dext = [ /* Distance codes 0..29 extra */
  10816. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  10817. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  10818. 28, 28, 29, 29, 64, 64
  10819. ];
  10820. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  10821. {
  10822. var bits = opts.bits;
  10823. //here = opts.here; /* table entry for duplication */
  10824. var len = 0; /* a code's length in bits */
  10825. var sym = 0; /* index of code symbols */
  10826. var min = 0, max = 0; /* minimum and maximum code lengths */
  10827. var root = 0; /* number of index bits for root table */
  10828. var curr = 0; /* number of index bits for current table */
  10829. var drop = 0; /* code bits to drop for sub-table */
  10830. var left = 0; /* number of prefix codes available */
  10831. var used = 0; /* code entries in table used */
  10832. var huff = 0; /* Huffman code */
  10833. var incr; /* for incrementing code, index */
  10834. var fill; /* index for replicating entries */
  10835. var low; /* low bits for current root entry */
  10836. var mask; /* mask for low root bits */
  10837. var next; /* next available space in table */
  10838. var base = null; /* base value table to use */
  10839. var base_index = 0;
  10840. // var shoextra; /* extra bits table to use */
  10841. var end; /* use base and extra for symbol > end */
  10842. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  10843. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  10844. var extra = null;
  10845. var extra_index = 0;
  10846. var here_bits, here_op, here_val;
  10847. /*
  10848. Process a set of code lengths to create a canonical Huffman code. The
  10849. code lengths are lens[0..codes-1]. Each length corresponds to the
  10850. symbols 0..codes-1. The Huffman code is generated by first sorting the
  10851. symbols by length from short to long, and retaining the symbol order
  10852. for codes with equal lengths. Then the code starts with all zero bits
  10853. for the first code of the shortest length, and the codes are integer
  10854. increments for the same length, and zeros are appended as the length
  10855. increases. For the deflate format, these bits are stored backwards
  10856. from their more natural integer increment ordering, and so when the
  10857. decoding tables are built in the large loop below, the integer codes
  10858. are incremented backwards.
  10859. This routine assumes, but does not check, that all of the entries in
  10860. lens[] are in the range 0..MAXBITS. The caller must assure this.
  10861. 1..MAXBITS is interpreted as that code length. zero means that that
  10862. symbol does not occur in this code.
  10863. The codes are sorted by computing a count of codes for each length,
  10864. creating from that a table of starting indices for each length in the
  10865. sorted table, and then entering the symbols in order in the sorted
  10866. table. The sorted table is work[], with that space being provided by
  10867. the caller.
  10868. The length counts are used for other purposes as well, i.e. finding
  10869. the minimum and maximum length codes, determining if there are any
  10870. codes at all, checking for a valid set of lengths, and looking ahead
  10871. at length counts to determine sub-table sizes when building the
  10872. decoding tables.
  10873. */
  10874. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  10875. for (len = 0; len <= MAXBITS; len++) {
  10876. count[len] = 0;
  10877. }
  10878. for (sym = 0; sym < codes; sym++) {
  10879. count[lens[lens_index + sym]]++;
  10880. }
  10881. /* bound code lengths, force root to be within code lengths */
  10882. root = bits;
  10883. for (max = MAXBITS; max >= 1; max--) {
  10884. if (count[max] !== 0) { break; }
  10885. }
  10886. if (root > max) {
  10887. root = max;
  10888. }
  10889. if (max === 0) { /* no symbols to code at all */
  10890. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  10891. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  10892. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  10893. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10894. //table.op[opts.table_index] = 64;
  10895. //table.bits[opts.table_index] = 1;
  10896. //table.val[opts.table_index++] = 0;
  10897. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10898. opts.bits = 1;
  10899. return 0; /* no symbols, but wait for decoding to report error */
  10900. }
  10901. for (min = 1; min < max; min++) {
  10902. if (count[min] !== 0) { break; }
  10903. }
  10904. if (root < min) {
  10905. root = min;
  10906. }
  10907. /* check for an over-subscribed or incomplete set of lengths */
  10908. left = 1;
  10909. for (len = 1; len <= MAXBITS; len++) {
  10910. left <<= 1;
  10911. left -= count[len];
  10912. if (left < 0) {
  10913. return -1;
  10914. } /* over-subscribed */
  10915. }
  10916. if (left > 0 && (type === CODES || max !== 1)) {
  10917. return -1; /* incomplete set */
  10918. }
  10919. /* generate offsets into symbol table for each length for sorting */
  10920. offs[1] = 0;
  10921. for (len = 1; len < MAXBITS; len++) {
  10922. offs[len + 1] = offs[len] + count[len];
  10923. }
  10924. /* sort symbols by length, by symbol order within each length */
  10925. for (sym = 0; sym < codes; sym++) {
  10926. if (lens[lens_index + sym] !== 0) {
  10927. work[offs[lens[lens_index + sym]]++] = sym;
  10928. }
  10929. }
  10930. /*
  10931. Create and fill in decoding tables. In this loop, the table being
  10932. filled is at next and has curr index bits. The code being used is huff
  10933. with length len. That code is converted to an index by dropping drop
  10934. bits off of the bottom. For codes where len is less than drop + curr,
  10935. those top drop + curr - len bits are incremented through all values to
  10936. fill the table with replicated entries.
  10937. root is the number of index bits for the root table. When len exceeds
  10938. root, sub-tables are created pointed to by the root entry with an index
  10939. of the low root bits of huff. This is saved in low to check for when a
  10940. new sub-table should be started. drop is zero when the root table is
  10941. being filled, and drop is root when sub-tables are being filled.
  10942. When a new sub-table is needed, it is necessary to look ahead in the
  10943. code lengths to determine what size sub-table is needed. The length
  10944. counts are used for this, and so count[] is decremented as codes are
  10945. entered in the tables.
  10946. used keeps track of how many table entries have been allocated from the
  10947. provided *table space. It is checked for LENS and DIST tables against
  10948. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  10949. the initial root table size constants. See the comments in inftrees.h
  10950. for more information.
  10951. sym increments through all symbols, and the loop terminates when
  10952. all codes of length max, i.e. all codes, have been processed. This
  10953. routine permits incomplete codes, so another loop after this one fills
  10954. in the rest of the decoding tables with invalid code markers.
  10955. */
  10956. /* set up for code type */
  10957. // poor man optimization - use if-else instead of switch,
  10958. // to avoid deopts in old v8
  10959. if (type === CODES) {
  10960. base = extra = work; /* dummy value--not used */
  10961. end = 19;
  10962. } else if (type === LENS) {
  10963. base = lbase;
  10964. base_index -= 257;
  10965. extra = lext;
  10966. extra_index -= 257;
  10967. end = 256;
  10968. } else { /* DISTS */
  10969. base = dbase;
  10970. extra = dext;
  10971. end = -1;
  10972. }
  10973. /* initialize opts for loop */
  10974. huff = 0; /* starting code */
  10975. sym = 0; /* starting code symbol */
  10976. len = min; /* starting code length */
  10977. next = table_index; /* current table to fill in */
  10978. curr = root; /* current table index bits */
  10979. drop = 0; /* current bits to drop from code for index */
  10980. low = -1; /* trigger new sub-table when len > root */
  10981. used = 1 << root; /* use root table entries */
  10982. mask = used - 1; /* mask for comparing low */
  10983. /* check available table space */
  10984. if ((type === LENS && used > ENOUGH_LENS) ||
  10985. (type === DISTS && used > ENOUGH_DISTS)) {
  10986. return 1;
  10987. }
  10988. /* process all codes and make table entries */
  10989. for (;;) {
  10990. /* create table entry */
  10991. here_bits = len - drop;
  10992. if (work[sym] < end) {
  10993. here_op = 0;
  10994. here_val = work[sym];
  10995. }
  10996. else if (work[sym] > end) {
  10997. here_op = extra[extra_index + work[sym]];
  10998. here_val = base[base_index + work[sym]];
  10999. }
  11000. else {
  11001. here_op = 32 + 64; /* end of block */
  11002. here_val = 0;
  11003. }
  11004. /* replicate for those indices with low len bits equal to huff */
  11005. incr = 1 << (len - drop);
  11006. fill = 1 << curr;
  11007. min = fill; /* save offset to next table */
  11008. do {
  11009. fill -= incr;
  11010. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  11011. } while (fill !== 0);
  11012. /* backwards increment the len-bit code huff */
  11013. incr = 1 << (len - 1);
  11014. while (huff & incr) {
  11015. incr >>= 1;
  11016. }
  11017. if (incr !== 0) {
  11018. huff &= incr - 1;
  11019. huff += incr;
  11020. } else {
  11021. huff = 0;
  11022. }
  11023. /* go to next symbol, update count, len */
  11024. sym++;
  11025. if (--count[len] === 0) {
  11026. if (len === max) { break; }
  11027. len = lens[lens_index + work[sym]];
  11028. }
  11029. /* create new sub-table if needed */
  11030. if (len > root && (huff & mask) !== low) {
  11031. /* if first time, transition to sub-tables */
  11032. if (drop === 0) {
  11033. drop = root;
  11034. }
  11035. /* increment past last table */
  11036. next += min; /* here min is 1 << curr */
  11037. /* determine length of next table */
  11038. curr = len - drop;
  11039. left = 1 << curr;
  11040. while (curr + drop < max) {
  11041. left -= count[curr + drop];
  11042. if (left <= 0) { break; }
  11043. curr++;
  11044. left <<= 1;
  11045. }
  11046. /* check for enough space */
  11047. used += 1 << curr;
  11048. if ((type === LENS && used > ENOUGH_LENS) ||
  11049. (type === DISTS && used > ENOUGH_DISTS)) {
  11050. return 1;
  11051. }
  11052. /* point entry in root table to sub-table */
  11053. low = huff & mask;
  11054. /*table.op[low] = curr;
  11055. table.bits[low] = root;
  11056. table.val[low] = next - opts.table_index;*/
  11057. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  11058. }
  11059. }
  11060. /* fill in remaining table entry if code is incomplete (guaranteed to have
  11061. at most one remaining entry, since if the code is incomplete, the
  11062. maximum code length that was allowed to get this far is one bit) */
  11063. if (huff !== 0) {
  11064. //table.op[next + huff] = 64; /* invalid code marker */
  11065. //table.bits[next + huff] = len - drop;
  11066. //table.val[next + huff] = 0;
  11067. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  11068. }
  11069. /* set return parameters */
  11070. //opts.table_index += used;
  11071. opts.bits = root;
  11072. return 0;
  11073. };
  11074. },{"../utils/common":51}],61:[function(require,module,exports){
  11075. 'use strict';
  11076. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11077. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11078. //
  11079. // This software is provided 'as-is', without any express or implied
  11080. // warranty. In no event will the authors be held liable for any damages
  11081. // arising from the use of this software.
  11082. //
  11083. // Permission is granted to anyone to use this software for any purpose,
  11084. // including commercial applications, and to alter it and redistribute it
  11085. // freely, subject to the following restrictions:
  11086. //
  11087. // 1. The origin of this software must not be misrepresented; you must not
  11088. // claim that you wrote the original software. If you use this software
  11089. // in a product, an acknowledgment in the product documentation would be
  11090. // appreciated but is not required.
  11091. // 2. Altered source versions must be plainly marked as such, and must not be
  11092. // misrepresented as being the original software.
  11093. // 3. This notice may not be removed or altered from any source distribution.
  11094. module.exports = {
  11095. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  11096. 1: 'stream end', /* Z_STREAM_END 1 */
  11097. 0: '', /* Z_OK 0 */
  11098. '-1': 'file error', /* Z_ERRNO (-1) */
  11099. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  11100. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  11101. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  11102. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  11103. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  11104. };
  11105. },{}],62:[function(require,module,exports){
  11106. 'use strict';
  11107. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11108. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11109. //
  11110. // This software is provided 'as-is', without any express or implied
  11111. // warranty. In no event will the authors be held liable for any damages
  11112. // arising from the use of this software.
  11113. //
  11114. // Permission is granted to anyone to use this software for any purpose,
  11115. // including commercial applications, and to alter it and redistribute it
  11116. // freely, subject to the following restrictions:
  11117. //
  11118. // 1. The origin of this software must not be misrepresented; you must not
  11119. // claim that you wrote the original software. If you use this software
  11120. // in a product, an acknowledgment in the product documentation would be
  11121. // appreciated but is not required.
  11122. // 2. Altered source versions must be plainly marked as such, and must not be
  11123. // misrepresented as being the original software.
  11124. // 3. This notice may not be removed or altered from any source distribution.
  11125. /* eslint-disable space-unary-ops */
  11126. var utils = require('../utils/common');
  11127. /* Public constants ==========================================================*/
  11128. /* ===========================================================================*/
  11129. //var Z_FILTERED = 1;
  11130. //var Z_HUFFMAN_ONLY = 2;
  11131. //var Z_RLE = 3;
  11132. var Z_FIXED = 4;
  11133. //var Z_DEFAULT_STRATEGY = 0;
  11134. /* Possible values of the data_type field (though see inflate()) */
  11135. var Z_BINARY = 0;
  11136. var Z_TEXT = 1;
  11137. //var Z_ASCII = 1; // = Z_TEXT
  11138. var Z_UNKNOWN = 2;
  11139. /*============================================================================*/
  11140. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11141. // From zutil.h
  11142. var STORED_BLOCK = 0;
  11143. var STATIC_TREES = 1;
  11144. var DYN_TREES = 2;
  11145. /* The three kinds of block type */
  11146. var MIN_MATCH = 3;
  11147. var MAX_MATCH = 258;
  11148. /* The minimum and maximum match lengths */
  11149. // From deflate.h
  11150. /* ===========================================================================
  11151. * Internal compression state.
  11152. */
  11153. var LENGTH_CODES = 29;
  11154. /* number of length codes, not counting the special END_BLOCK code */
  11155. var LITERALS = 256;
  11156. /* number of literal bytes 0..255 */
  11157. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11158. /* number of Literal or Length codes, including the END_BLOCK code */
  11159. var D_CODES = 30;
  11160. /* number of distance codes */
  11161. var BL_CODES = 19;
  11162. /* number of codes used to transfer the bit lengths */
  11163. var HEAP_SIZE = 2 * L_CODES + 1;
  11164. /* maximum heap size */
  11165. var MAX_BITS = 15;
  11166. /* All codes must not exceed MAX_BITS bits */
  11167. var Buf_size = 16;
  11168. /* size of bit buffer in bi_buf */
  11169. /* ===========================================================================
  11170. * Constants
  11171. */
  11172. var MAX_BL_BITS = 7;
  11173. /* Bit length codes must not exceed MAX_BL_BITS bits */
  11174. var END_BLOCK = 256;
  11175. /* end of block literal code */
  11176. var REP_3_6 = 16;
  11177. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  11178. var REPZ_3_10 = 17;
  11179. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  11180. var REPZ_11_138 = 18;
  11181. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  11182. /* eslint-disable comma-spacing,array-bracket-spacing */
  11183. var extra_lbits = /* extra bits for each length code */
  11184. [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];
  11185. var extra_dbits = /* extra bits for each distance code */
  11186. [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];
  11187. var extra_blbits = /* extra bits for each bit length code */
  11188. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  11189. var bl_order =
  11190. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  11191. /* eslint-enable comma-spacing,array-bracket-spacing */
  11192. /* The lengths of the bit length codes are sent in order of decreasing
  11193. * probability, to avoid transmitting the lengths for unused bit length codes.
  11194. */
  11195. /* ===========================================================================
  11196. * Local data. These are initialized only once.
  11197. */
  11198. // We pre-fill arrays with 0 to avoid uninitialized gaps
  11199. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  11200. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  11201. var static_ltree = new Array((L_CODES + 2) * 2);
  11202. zero(static_ltree);
  11203. /* The static literal tree. Since the bit lengths are imposed, there is no
  11204. * need for the L_CODES extra codes used during heap construction. However
  11205. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  11206. * below).
  11207. */
  11208. var static_dtree = new Array(D_CODES * 2);
  11209. zero(static_dtree);
  11210. /* The static distance tree. (Actually a trivial tree since all codes use
  11211. * 5 bits.)
  11212. */
  11213. var _dist_code = new Array(DIST_CODE_LEN);
  11214. zero(_dist_code);
  11215. /* Distance codes. The first 256 values correspond to the distances
  11216. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  11217. * the 15 bit distances.
  11218. */
  11219. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  11220. zero(_length_code);
  11221. /* length code for each normalized match length (0 == MIN_MATCH) */
  11222. var base_length = new Array(LENGTH_CODES);
  11223. zero(base_length);
  11224. /* First normalized length for each code (0 = MIN_MATCH) */
  11225. var base_dist = new Array(D_CODES);
  11226. zero(base_dist);
  11227. /* First normalized distance for each code (0 = distance of 1) */
  11228. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  11229. this.static_tree = static_tree; /* static tree or NULL */
  11230. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  11231. this.extra_base = extra_base; /* base index for extra_bits */
  11232. this.elems = elems; /* max number of elements in the tree */
  11233. this.max_length = max_length; /* max bit length for the codes */
  11234. // show if `static_tree` has data or dummy - needed for monomorphic objects
  11235. this.has_stree = static_tree && static_tree.length;
  11236. }
  11237. var static_l_desc;
  11238. var static_d_desc;
  11239. var static_bl_desc;
  11240. function TreeDesc(dyn_tree, stat_desc) {
  11241. this.dyn_tree = dyn_tree; /* the dynamic tree */
  11242. this.max_code = 0; /* largest code with non zero frequency */
  11243. this.stat_desc = stat_desc; /* the corresponding static tree */
  11244. }
  11245. function d_code(dist) {
  11246. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  11247. }
  11248. /* ===========================================================================
  11249. * Output a short LSB first on the stream.
  11250. * IN assertion: there is enough room in pendingBuf.
  11251. */
  11252. function put_short(s, w) {
  11253. // put_byte(s, (uch)((w) & 0xff));
  11254. // put_byte(s, (uch)((ush)(w) >> 8));
  11255. s.pending_buf[s.pending++] = (w) & 0xff;
  11256. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  11257. }
  11258. /* ===========================================================================
  11259. * Send a value on a given number of bits.
  11260. * IN assertion: length <= 16 and value fits in length bits.
  11261. */
  11262. function send_bits(s, value, length) {
  11263. if (s.bi_valid > (Buf_size - length)) {
  11264. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  11265. put_short(s, s.bi_buf);
  11266. s.bi_buf = value >> (Buf_size - s.bi_valid);
  11267. s.bi_valid += length - Buf_size;
  11268. } else {
  11269. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  11270. s.bi_valid += length;
  11271. }
  11272. }
  11273. function send_code(s, c, tree) {
  11274. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  11275. }
  11276. /* ===========================================================================
  11277. * Reverse the first len bits of a code, using straightforward code (a faster
  11278. * method would use a table)
  11279. * IN assertion: 1 <= len <= 15
  11280. */
  11281. function bi_reverse(code, len) {
  11282. var res = 0;
  11283. do {
  11284. res |= code & 1;
  11285. code >>>= 1;
  11286. res <<= 1;
  11287. } while (--len > 0);
  11288. return res >>> 1;
  11289. }
  11290. /* ===========================================================================
  11291. * Flush the bit buffer, keeping at most 7 bits in it.
  11292. */
  11293. function bi_flush(s) {
  11294. if (s.bi_valid === 16) {
  11295. put_short(s, s.bi_buf);
  11296. s.bi_buf = 0;
  11297. s.bi_valid = 0;
  11298. } else if (s.bi_valid >= 8) {
  11299. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  11300. s.bi_buf >>= 8;
  11301. s.bi_valid -= 8;
  11302. }
  11303. }
  11304. /* ===========================================================================
  11305. * Compute the optimal bit lengths for a tree and update the total bit length
  11306. * for the current block.
  11307. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  11308. * above are the tree nodes sorted by increasing frequency.
  11309. * OUT assertions: the field len is set to the optimal bit length, the
  11310. * array bl_count contains the frequencies for each bit length.
  11311. * The length opt_len is updated; static_len is also updated if stree is
  11312. * not null.
  11313. */
  11314. function gen_bitlen(s, desc)
  11315. // deflate_state *s;
  11316. // tree_desc *desc; /* the tree descriptor */
  11317. {
  11318. var tree = desc.dyn_tree;
  11319. var max_code = desc.max_code;
  11320. var stree = desc.stat_desc.static_tree;
  11321. var has_stree = desc.stat_desc.has_stree;
  11322. var extra = desc.stat_desc.extra_bits;
  11323. var base = desc.stat_desc.extra_base;
  11324. var max_length = desc.stat_desc.max_length;
  11325. var h; /* heap index */
  11326. var n, m; /* iterate over the tree elements */
  11327. var bits; /* bit length */
  11328. var xbits; /* extra bits */
  11329. var f; /* frequency */
  11330. var overflow = 0; /* number of elements with bit length too large */
  11331. for (bits = 0; bits <= MAX_BITS; bits++) {
  11332. s.bl_count[bits] = 0;
  11333. }
  11334. /* In a first pass, compute the optimal bit lengths (which may
  11335. * overflow in the case of the bit length tree).
  11336. */
  11337. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  11338. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  11339. n = s.heap[h];
  11340. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  11341. if (bits > max_length) {
  11342. bits = max_length;
  11343. overflow++;
  11344. }
  11345. tree[n * 2 + 1]/*.Len*/ = bits;
  11346. /* We overwrite tree[n].Dad which is no longer needed */
  11347. if (n > max_code) { continue; } /* not a leaf node */
  11348. s.bl_count[bits]++;
  11349. xbits = 0;
  11350. if (n >= base) {
  11351. xbits = extra[n - base];
  11352. }
  11353. f = tree[n * 2]/*.Freq*/;
  11354. s.opt_len += f * (bits + xbits);
  11355. if (has_stree) {
  11356. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  11357. }
  11358. }
  11359. if (overflow === 0) { return; }
  11360. // Trace((stderr,"\nbit length overflow\n"));
  11361. /* This happens for example on obj2 and pic of the Calgary corpus */
  11362. /* Find the first bit length which could increase: */
  11363. do {
  11364. bits = max_length - 1;
  11365. while (s.bl_count[bits] === 0) { bits--; }
  11366. s.bl_count[bits]--; /* move one leaf down the tree */
  11367. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  11368. s.bl_count[max_length]--;
  11369. /* The brother of the overflow item also moves one step up,
  11370. * but this does not affect bl_count[max_length]
  11371. */
  11372. overflow -= 2;
  11373. } while (overflow > 0);
  11374. /* Now recompute all bit lengths, scanning in increasing frequency.
  11375. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  11376. * lengths instead of fixing only the wrong ones. This idea is taken
  11377. * from 'ar' written by Haruhiko Okumura.)
  11378. */
  11379. for (bits = max_length; bits !== 0; bits--) {
  11380. n = s.bl_count[bits];
  11381. while (n !== 0) {
  11382. m = s.heap[--h];
  11383. if (m > max_code) { continue; }
  11384. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  11385. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  11386. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  11387. tree[m * 2 + 1]/*.Len*/ = bits;
  11388. }
  11389. n--;
  11390. }
  11391. }
  11392. }
  11393. /* ===========================================================================
  11394. * Generate the codes for a given tree and bit counts (which need not be
  11395. * optimal).
  11396. * IN assertion: the array bl_count contains the bit length statistics for
  11397. * the given tree and the field len is set for all tree elements.
  11398. * OUT assertion: the field code is set for all tree elements of non
  11399. * zero code length.
  11400. */
  11401. function gen_codes(tree, max_code, bl_count)
  11402. // ct_data *tree; /* the tree to decorate */
  11403. // int max_code; /* largest code with non zero frequency */
  11404. // ushf *bl_count; /* number of codes at each bit length */
  11405. {
  11406. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  11407. var code = 0; /* running code value */
  11408. var bits; /* bit index */
  11409. var n; /* code index */
  11410. /* The distribution counts are first used to generate the code values
  11411. * without bit reversal.
  11412. */
  11413. for (bits = 1; bits <= MAX_BITS; bits++) {
  11414. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  11415. }
  11416. /* Check that the bit counts in bl_count are consistent. The last code
  11417. * must be all ones.
  11418. */
  11419. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  11420. // "inconsistent bit counts");
  11421. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  11422. for (n = 0; n <= max_code; n++) {
  11423. var len = tree[n * 2 + 1]/*.Len*/;
  11424. if (len === 0) { continue; }
  11425. /* Now reverse the bits */
  11426. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  11427. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  11428. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  11429. }
  11430. }
  11431. /* ===========================================================================
  11432. * Initialize the various 'constant' tables.
  11433. */
  11434. function tr_static_init() {
  11435. var n; /* iterates over tree elements */
  11436. var bits; /* bit counter */
  11437. var length; /* length value */
  11438. var code; /* code value */
  11439. var dist; /* distance index */
  11440. var bl_count = new Array(MAX_BITS + 1);
  11441. /* number of codes at each bit length for an optimal tree */
  11442. // do check in _tr_init()
  11443. //if (static_init_done) return;
  11444. /* For some embedded targets, global variables are not initialized: */
  11445. /*#ifdef NO_INIT_GLOBAL_POINTERS
  11446. static_l_desc.static_tree = static_ltree;
  11447. static_l_desc.extra_bits = extra_lbits;
  11448. static_d_desc.static_tree = static_dtree;
  11449. static_d_desc.extra_bits = extra_dbits;
  11450. static_bl_desc.extra_bits = extra_blbits;
  11451. #endif*/
  11452. /* Initialize the mapping length (0..255) -> length code (0..28) */
  11453. length = 0;
  11454. for (code = 0; code < LENGTH_CODES - 1; code++) {
  11455. base_length[code] = length;
  11456. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  11457. _length_code[length++] = code;
  11458. }
  11459. }
  11460. //Assert (length == 256, "tr_static_init: length != 256");
  11461. /* Note that the length 255 (match length 258) can be represented
  11462. * in two different ways: code 284 + 5 bits or code 285, so we
  11463. * overwrite length_code[255] to use the best encoding:
  11464. */
  11465. _length_code[length - 1] = code;
  11466. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  11467. dist = 0;
  11468. for (code = 0; code < 16; code++) {
  11469. base_dist[code] = dist;
  11470. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  11471. _dist_code[dist++] = code;
  11472. }
  11473. }
  11474. //Assert (dist == 256, "tr_static_init: dist != 256");
  11475. dist >>= 7; /* from now on, all distances are divided by 128 */
  11476. for (; code < D_CODES; code++) {
  11477. base_dist[code] = dist << 7;
  11478. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  11479. _dist_code[256 + dist++] = code;
  11480. }
  11481. }
  11482. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  11483. /* Construct the codes of the static literal tree */
  11484. for (bits = 0; bits <= MAX_BITS; bits++) {
  11485. bl_count[bits] = 0;
  11486. }
  11487. n = 0;
  11488. while (n <= 143) {
  11489. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11490. n++;
  11491. bl_count[8]++;
  11492. }
  11493. while (n <= 255) {
  11494. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  11495. n++;
  11496. bl_count[9]++;
  11497. }
  11498. while (n <= 279) {
  11499. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  11500. n++;
  11501. bl_count[7]++;
  11502. }
  11503. while (n <= 287) {
  11504. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11505. n++;
  11506. bl_count[8]++;
  11507. }
  11508. /* Codes 286 and 287 do not exist, but we must include them in the
  11509. * tree construction to get a canonical Huffman tree (longest code
  11510. * all ones)
  11511. */
  11512. gen_codes(static_ltree, L_CODES + 1, bl_count);
  11513. /* The static distance tree is trivial: */
  11514. for (n = 0; n < D_CODES; n++) {
  11515. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  11516. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  11517. }
  11518. // Now data ready and we can init static trees
  11519. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  11520. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  11521. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  11522. //static_init_done = true;
  11523. }
  11524. /* ===========================================================================
  11525. * Initialize a new block.
  11526. */
  11527. function init_block(s) {
  11528. var n; /* iterates over tree elements */
  11529. /* Initialize the trees. */
  11530. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  11531. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  11532. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  11533. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  11534. s.opt_len = s.static_len = 0;
  11535. s.last_lit = s.matches = 0;
  11536. }
  11537. /* ===========================================================================
  11538. * Flush the bit buffer and align the output on a byte boundary
  11539. */
  11540. function bi_windup(s)
  11541. {
  11542. if (s.bi_valid > 8) {
  11543. put_short(s, s.bi_buf);
  11544. } else if (s.bi_valid > 0) {
  11545. //put_byte(s, (Byte)s->bi_buf);
  11546. s.pending_buf[s.pending++] = s.bi_buf;
  11547. }
  11548. s.bi_buf = 0;
  11549. s.bi_valid = 0;
  11550. }
  11551. /* ===========================================================================
  11552. * Copy a stored block, storing first the length and its
  11553. * one's complement if requested.
  11554. */
  11555. function copy_block(s, buf, len, header)
  11556. //DeflateState *s;
  11557. //charf *buf; /* the input data */
  11558. //unsigned len; /* its length */
  11559. //int header; /* true if block header must be written */
  11560. {
  11561. bi_windup(s); /* align on byte boundary */
  11562. if (header) {
  11563. put_short(s, len);
  11564. put_short(s, ~len);
  11565. }
  11566. // while (len--) {
  11567. // put_byte(s, *buf++);
  11568. // }
  11569. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  11570. s.pending += len;
  11571. }
  11572. /* ===========================================================================
  11573. * Compares to subtrees, using the tree depth as tie breaker when
  11574. * the subtrees have equal frequency. This minimizes the worst case length.
  11575. */
  11576. function smaller(tree, n, m, depth) {
  11577. var _n2 = n * 2;
  11578. var _m2 = m * 2;
  11579. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  11580. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  11581. }
  11582. /* ===========================================================================
  11583. * Restore the heap property by moving down the tree starting at node k,
  11584. * exchanging a node with the smallest of its two sons if necessary, stopping
  11585. * when the heap property is re-established (each father smaller than its
  11586. * two sons).
  11587. */
  11588. function pqdownheap(s, tree, k)
  11589. // deflate_state *s;
  11590. // ct_data *tree; /* the tree to restore */
  11591. // int k; /* node to move down */
  11592. {
  11593. var v = s.heap[k];
  11594. var j = k << 1; /* left son of k */
  11595. while (j <= s.heap_len) {
  11596. /* Set j to the smallest of the two sons: */
  11597. if (j < s.heap_len &&
  11598. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  11599. j++;
  11600. }
  11601. /* Exit if v is smaller than both sons */
  11602. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  11603. /* Exchange v with the smallest son */
  11604. s.heap[k] = s.heap[j];
  11605. k = j;
  11606. /* And continue down the tree, setting j to the left son of k */
  11607. j <<= 1;
  11608. }
  11609. s.heap[k] = v;
  11610. }
  11611. // inlined manually
  11612. // var SMALLEST = 1;
  11613. /* ===========================================================================
  11614. * Send the block data compressed using the given Huffman trees
  11615. */
  11616. function compress_block(s, ltree, dtree)
  11617. // deflate_state *s;
  11618. // const ct_data *ltree; /* literal tree */
  11619. // const ct_data *dtree; /* distance tree */
  11620. {
  11621. var dist; /* distance of matched string */
  11622. var lc; /* match length or unmatched char (if dist == 0) */
  11623. var lx = 0; /* running index in l_buf */
  11624. var code; /* the code to send */
  11625. var extra; /* number of extra bits to send */
  11626. if (s.last_lit !== 0) {
  11627. do {
  11628. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  11629. lc = s.pending_buf[s.l_buf + lx];
  11630. lx++;
  11631. if (dist === 0) {
  11632. send_code(s, lc, ltree); /* send a literal byte */
  11633. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  11634. } else {
  11635. /* Here, lc is the match length - MIN_MATCH */
  11636. code = _length_code[lc];
  11637. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  11638. extra = extra_lbits[code];
  11639. if (extra !== 0) {
  11640. lc -= base_length[code];
  11641. send_bits(s, lc, extra); /* send the extra length bits */
  11642. }
  11643. dist--; /* dist is now the match distance - 1 */
  11644. code = d_code(dist);
  11645. //Assert (code < D_CODES, "bad d_code");
  11646. send_code(s, code, dtree); /* send the distance code */
  11647. extra = extra_dbits[code];
  11648. if (extra !== 0) {
  11649. dist -= base_dist[code];
  11650. send_bits(s, dist, extra); /* send the extra distance bits */
  11651. }
  11652. } /* literal or match pair ? */
  11653. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  11654. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  11655. // "pendingBuf overflow");
  11656. } while (lx < s.last_lit);
  11657. }
  11658. send_code(s, END_BLOCK, ltree);
  11659. }
  11660. /* ===========================================================================
  11661. * Construct one Huffman tree and assigns the code bit strings and lengths.
  11662. * Update the total bit length for the current block.
  11663. * IN assertion: the field freq is set for all tree elements.
  11664. * OUT assertions: the fields len and code are set to the optimal bit length
  11665. * and corresponding code. The length opt_len is updated; static_len is
  11666. * also updated if stree is not null. The field max_code is set.
  11667. */
  11668. function build_tree(s, desc)
  11669. // deflate_state *s;
  11670. // tree_desc *desc; /* the tree descriptor */
  11671. {
  11672. var tree = desc.dyn_tree;
  11673. var stree = desc.stat_desc.static_tree;
  11674. var has_stree = desc.stat_desc.has_stree;
  11675. var elems = desc.stat_desc.elems;
  11676. var n, m; /* iterate over heap elements */
  11677. var max_code = -1; /* largest code with non zero frequency */
  11678. var node; /* new node being created */
  11679. /* Construct the initial heap, with least frequent element in
  11680. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  11681. * heap[0] is not used.
  11682. */
  11683. s.heap_len = 0;
  11684. s.heap_max = HEAP_SIZE;
  11685. for (n = 0; n < elems; n++) {
  11686. if (tree[n * 2]/*.Freq*/ !== 0) {
  11687. s.heap[++s.heap_len] = max_code = n;
  11688. s.depth[n] = 0;
  11689. } else {
  11690. tree[n * 2 + 1]/*.Len*/ = 0;
  11691. }
  11692. }
  11693. /* The pkzip format requires that at least one distance code exists,
  11694. * and that at least one bit should be sent even if there is only one
  11695. * possible code. So to avoid special checks later on we force at least
  11696. * two codes of non zero frequency.
  11697. */
  11698. while (s.heap_len < 2) {
  11699. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  11700. tree[node * 2]/*.Freq*/ = 1;
  11701. s.depth[node] = 0;
  11702. s.opt_len--;
  11703. if (has_stree) {
  11704. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  11705. }
  11706. /* node is 0 or 1 so it does not have extra bits */
  11707. }
  11708. desc.max_code = max_code;
  11709. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  11710. * establish sub-heaps of increasing lengths:
  11711. */
  11712. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  11713. /* Construct the Huffman tree by repeatedly combining the least two
  11714. * frequent nodes.
  11715. */
  11716. node = elems; /* next internal node of the tree */
  11717. do {
  11718. //pqremove(s, tree, n); /* n = node of least frequency */
  11719. /*** pqremove ***/
  11720. n = s.heap[1/*SMALLEST*/];
  11721. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  11722. pqdownheap(s, tree, 1/*SMALLEST*/);
  11723. /***/
  11724. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  11725. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  11726. s.heap[--s.heap_max] = m;
  11727. /* Create a new node father of n and m */
  11728. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  11729. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  11730. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  11731. /* and insert the new node in the heap */
  11732. s.heap[1/*SMALLEST*/] = node++;
  11733. pqdownheap(s, tree, 1/*SMALLEST*/);
  11734. } while (s.heap_len >= 2);
  11735. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  11736. /* At this point, the fields freq and dad are set. We can now
  11737. * generate the bit lengths.
  11738. */
  11739. gen_bitlen(s, desc);
  11740. /* The field len is now set, we can generate the bit codes */
  11741. gen_codes(tree, max_code, s.bl_count);
  11742. }
  11743. /* ===========================================================================
  11744. * Scan a literal or distance tree to determine the frequencies of the codes
  11745. * in the bit length tree.
  11746. */
  11747. function scan_tree(s, tree, max_code)
  11748. // deflate_state *s;
  11749. // ct_data *tree; /* the tree to be scanned */
  11750. // int max_code; /* and its largest code of non zero frequency */
  11751. {
  11752. var n; /* iterates over all tree elements */
  11753. var prevlen = -1; /* last emitted length */
  11754. var curlen; /* length of current code */
  11755. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11756. var count = 0; /* repeat count of the current code */
  11757. var max_count = 7; /* max repeat count */
  11758. var min_count = 4; /* min repeat count */
  11759. if (nextlen === 0) {
  11760. max_count = 138;
  11761. min_count = 3;
  11762. }
  11763. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11764. for (n = 0; n <= max_code; n++) {
  11765. curlen = nextlen;
  11766. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11767. if (++count < max_count && curlen === nextlen) {
  11768. continue;
  11769. } else if (count < min_count) {
  11770. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11771. } else if (curlen !== 0) {
  11772. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11773. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11774. } else if (count <= 10) {
  11775. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11776. } else {
  11777. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11778. }
  11779. count = 0;
  11780. prevlen = curlen;
  11781. if (nextlen === 0) {
  11782. max_count = 138;
  11783. min_count = 3;
  11784. } else if (curlen === nextlen) {
  11785. max_count = 6;
  11786. min_count = 3;
  11787. } else {
  11788. max_count = 7;
  11789. min_count = 4;
  11790. }
  11791. }
  11792. }
  11793. /* ===========================================================================
  11794. * Send a literal or distance tree in compressed form, using the codes in
  11795. * bl_tree.
  11796. */
  11797. function send_tree(s, tree, max_code)
  11798. // deflate_state *s;
  11799. // ct_data *tree; /* the tree to be scanned */
  11800. // int max_code; /* and its largest code of non zero frequency */
  11801. {
  11802. var n; /* iterates over all tree elements */
  11803. var prevlen = -1; /* last emitted length */
  11804. var curlen; /* length of current code */
  11805. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11806. var count = 0; /* repeat count of the current code */
  11807. var max_count = 7; /* max repeat count */
  11808. var min_count = 4; /* min repeat count */
  11809. /* tree[max_code+1].Len = -1; */ /* guard already set */
  11810. if (nextlen === 0) {
  11811. max_count = 138;
  11812. min_count = 3;
  11813. }
  11814. for (n = 0; n <= max_code; n++) {
  11815. curlen = nextlen;
  11816. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11817. if (++count < max_count && curlen === nextlen) {
  11818. continue;
  11819. } else if (count < min_count) {
  11820. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11821. } else if (curlen !== 0) {
  11822. if (curlen !== prevlen) {
  11823. send_code(s, curlen, s.bl_tree);
  11824. count--;
  11825. }
  11826. //Assert(count >= 3 && count <= 6, " 3_6?");
  11827. send_code(s, REP_3_6, s.bl_tree);
  11828. send_bits(s, count - 3, 2);
  11829. } else if (count <= 10) {
  11830. send_code(s, REPZ_3_10, s.bl_tree);
  11831. send_bits(s, count - 3, 3);
  11832. } else {
  11833. send_code(s, REPZ_11_138, s.bl_tree);
  11834. send_bits(s, count - 11, 7);
  11835. }
  11836. count = 0;
  11837. prevlen = curlen;
  11838. if (nextlen === 0) {
  11839. max_count = 138;
  11840. min_count = 3;
  11841. } else if (curlen === nextlen) {
  11842. max_count = 6;
  11843. min_count = 3;
  11844. } else {
  11845. max_count = 7;
  11846. min_count = 4;
  11847. }
  11848. }
  11849. }
  11850. /* ===========================================================================
  11851. * Construct the Huffman tree for the bit lengths and return the index in
  11852. * bl_order of the last bit length code to send.
  11853. */
  11854. function build_bl_tree(s) {
  11855. var max_blindex; /* index of last bit length code of non zero freq */
  11856. /* Determine the bit length frequencies for literal and distance trees */
  11857. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11858. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11859. /* Build the bit length tree: */
  11860. build_tree(s, s.bl_desc);
  11861. /* opt_len now includes the length of the tree representations, except
  11862. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11863. */
  11864. /* Determine the number of bit length codes to send. The pkzip format
  11865. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11866. * 3 but the actual value used is 4.)
  11867. */
  11868. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11869. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11870. break;
  11871. }
  11872. }
  11873. /* Update opt_len to include the bit length tree and counts */
  11874. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11875. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11876. // s->opt_len, s->static_len));
  11877. return max_blindex;
  11878. }
  11879. /* ===========================================================================
  11880. * Send the header for a block using dynamic Huffman trees: the counts, the
  11881. * lengths of the bit length codes, the literal tree and the distance tree.
  11882. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11883. */
  11884. function send_all_trees(s, lcodes, dcodes, blcodes)
  11885. // deflate_state *s;
  11886. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11887. {
  11888. var rank; /* index in bl_order */
  11889. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11890. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11891. // "too many codes");
  11892. //Tracev((stderr, "\nbl counts: "));
  11893. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11894. send_bits(s, dcodes - 1, 5);
  11895. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11896. for (rank = 0; rank < blcodes; rank++) {
  11897. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11898. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11899. }
  11900. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11901. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11902. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11903. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11904. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11905. }
  11906. /* ===========================================================================
  11907. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11908. * - TEXT if the two conditions below are satisfied:
  11909. * a) There are no non-portable control characters belonging to the
  11910. * "black list" (0..6, 14..25, 28..31).
  11911. * b) There is at least one printable character belonging to the
  11912. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11913. * - BINARY otherwise.
  11914. * - The following partially-portable control characters form a
  11915. * "gray list" that is ignored in this detection algorithm:
  11916. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11917. * IN assertion: the fields Freq of dyn_ltree are set.
  11918. */
  11919. function detect_data_type(s) {
  11920. /* black_mask is the bit mask of black-listed bytes
  11921. * set bits 0..6, 14..25, and 28..31
  11922. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11923. */
  11924. var black_mask = 0xf3ffc07f;
  11925. var n;
  11926. /* Check for non-textual ("black-listed") bytes. */
  11927. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11928. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11929. return Z_BINARY;
  11930. }
  11931. }
  11932. /* Check for textual ("white-listed") bytes. */
  11933. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11934. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11935. return Z_TEXT;
  11936. }
  11937. for (n = 32; n < LITERALS; n++) {
  11938. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11939. return Z_TEXT;
  11940. }
  11941. }
  11942. /* There are no "black-listed" or "white-listed" bytes:
  11943. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11944. */
  11945. return Z_BINARY;
  11946. }
  11947. var static_init_done = false;
  11948. /* ===========================================================================
  11949. * Initialize the tree data structures for a new zlib stream.
  11950. */
  11951. function _tr_init(s)
  11952. {
  11953. if (!static_init_done) {
  11954. tr_static_init();
  11955. static_init_done = true;
  11956. }
  11957. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11958. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11959. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11960. s.bi_buf = 0;
  11961. s.bi_valid = 0;
  11962. /* Initialize the first block of the first file: */
  11963. init_block(s);
  11964. }
  11965. /* ===========================================================================
  11966. * Send a stored block
  11967. */
  11968. function _tr_stored_block(s, buf, stored_len, last)
  11969. //DeflateState *s;
  11970. //charf *buf; /* input block */
  11971. //ulg stored_len; /* length of input block */
  11972. //int last; /* one if this is the last block for a file */
  11973. {
  11974. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11975. copy_block(s, buf, stored_len, true); /* with header */
  11976. }
  11977. /* ===========================================================================
  11978. * Send one empty static block to give enough lookahead for inflate.
  11979. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11980. */
  11981. function _tr_align(s) {
  11982. send_bits(s, STATIC_TREES << 1, 3);
  11983. send_code(s, END_BLOCK, static_ltree);
  11984. bi_flush(s);
  11985. }
  11986. /* ===========================================================================
  11987. * Determine the best encoding for the current block: dynamic trees, static
  11988. * trees or store, and output the encoded block to the zip file.
  11989. */
  11990. function _tr_flush_block(s, buf, stored_len, last)
  11991. //DeflateState *s;
  11992. //charf *buf; /* input block, or NULL if too old */
  11993. //ulg stored_len; /* length of input block */
  11994. //int last; /* one if this is the last block for a file */
  11995. {
  11996. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11997. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11998. /* Build the Huffman trees unless a stored block is forced */
  11999. if (s.level > 0) {
  12000. /* Check if the file is binary or text */
  12001. if (s.strm.data_type === Z_UNKNOWN) {
  12002. s.strm.data_type = detect_data_type(s);
  12003. }
  12004. /* Construct the literal and distance trees */
  12005. build_tree(s, s.l_desc);
  12006. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  12007. // s->static_len));
  12008. build_tree(s, s.d_desc);
  12009. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  12010. // s->static_len));
  12011. /* At this point, opt_len and static_len are the total bit lengths of
  12012. * the compressed block data, excluding the tree representations.
  12013. */
  12014. /* Build the bit length tree for the above two trees, and get the index
  12015. * in bl_order of the last bit length code to send.
  12016. */
  12017. max_blindex = build_bl_tree(s);
  12018. /* Determine the best encoding. Compute the block lengths in bytes. */
  12019. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  12020. static_lenb = (s.static_len + 3 + 7) >>> 3;
  12021. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  12022. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  12023. // s->last_lit));
  12024. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  12025. } else {
  12026. // Assert(buf != (char*)0, "lost buf");
  12027. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  12028. }
  12029. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  12030. /* 4: two words for the lengths */
  12031. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  12032. * Otherwise we can't have processed more than WSIZE input bytes since
  12033. * the last block flush, because compression would have been
  12034. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  12035. * transform a block into a stored block.
  12036. */
  12037. _tr_stored_block(s, buf, stored_len, last);
  12038. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  12039. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  12040. compress_block(s, static_ltree, static_dtree);
  12041. } else {
  12042. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  12043. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  12044. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  12045. }
  12046. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  12047. /* The above check is made mod 2^32, for files larger than 512 MB
  12048. * and uLong implemented on 32 bits.
  12049. */
  12050. init_block(s);
  12051. if (last) {
  12052. bi_windup(s);
  12053. }
  12054. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  12055. // s->compressed_len-7*last));
  12056. }
  12057. /* ===========================================================================
  12058. * Save the match info and tally the frequency counts. Return true if
  12059. * the current block must be flushed.
  12060. */
  12061. function _tr_tally(s, dist, lc)
  12062. // deflate_state *s;
  12063. // unsigned dist; /* distance of matched string */
  12064. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  12065. {
  12066. //var out_length, in_length, dcode;
  12067. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  12068. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  12069. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  12070. s.last_lit++;
  12071. if (dist === 0) {
  12072. /* lc is the unmatched char */
  12073. s.dyn_ltree[lc * 2]/*.Freq*/++;
  12074. } else {
  12075. s.matches++;
  12076. /* Here, lc is the match length - MIN_MATCH */
  12077. dist--; /* dist = match distance - 1 */
  12078. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  12079. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  12080. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  12081. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  12082. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  12083. }
  12084. // (!) This block is disabled in zlib defaults,
  12085. // don't enable it for binary compatibility
  12086. //#ifdef TRUNCATE_BLOCK
  12087. // /* Try to guess if it is profitable to stop the current block here */
  12088. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  12089. // /* Compute an upper bound for the compressed length */
  12090. // out_length = s.last_lit*8;
  12091. // in_length = s.strstart - s.block_start;
  12092. //
  12093. // for (dcode = 0; dcode < D_CODES; dcode++) {
  12094. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  12095. // }
  12096. // out_length >>>= 3;
  12097. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  12098. // // s->last_lit, in_length, out_length,
  12099. // // 100L - out_length*100L/in_length));
  12100. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  12101. // return true;
  12102. // }
  12103. // }
  12104. //#endif
  12105. return (s.last_lit === s.lit_bufsize - 1);
  12106. /* We avoid equality with lit_bufsize because of wraparound at 64K
  12107. * on 16 bit machines and because stored blocks are restricted to
  12108. * 64K-1 bytes.
  12109. */
  12110. }
  12111. exports._tr_init = _tr_init;
  12112. exports._tr_stored_block = _tr_stored_block;
  12113. exports._tr_flush_block = _tr_flush_block;
  12114. exports._tr_tally = _tr_tally;
  12115. exports._tr_align = _tr_align;
  12116. },{"../utils/common":51}],63:[function(require,module,exports){
  12117. 'use strict';
  12118. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  12119. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  12120. //
  12121. // This software is provided 'as-is', without any express or implied
  12122. // warranty. In no event will the authors be held liable for any damages
  12123. // arising from the use of this software.
  12124. //
  12125. // Permission is granted to anyone to use this software for any purpose,
  12126. // including commercial applications, and to alter it and redistribute it
  12127. // freely, subject to the following restrictions:
  12128. //
  12129. // 1. The origin of this software must not be misrepresented; you must not
  12130. // claim that you wrote the original software. If you use this software
  12131. // in a product, an acknowledgment in the product documentation would be
  12132. // appreciated but is not required.
  12133. // 2. Altered source versions must be plainly marked as such, and must not be
  12134. // misrepresented as being the original software.
  12135. // 3. This notice may not be removed or altered from any source distribution.
  12136. function ZStream() {
  12137. /* next input byte */
  12138. this.input = null; // JS specific, because we have no pointers
  12139. this.next_in = 0;
  12140. /* number of bytes available at input */
  12141. this.avail_in = 0;
  12142. /* total number of input bytes read so far */
  12143. this.total_in = 0;
  12144. /* next output byte should be put there */
  12145. this.output = null; // JS specific, because we have no pointers
  12146. this.next_out = 0;
  12147. /* remaining free space at output */
  12148. this.avail_out = 0;
  12149. /* total number of bytes output so far */
  12150. this.total_out = 0;
  12151. /* last error message, NULL if no error */
  12152. this.msg = ''/*Z_NULL*/;
  12153. /* not visible by applications */
  12154. this.state = null;
  12155. /* best guess about the data type: binary or text */
  12156. this.data_type = 2/*Z_UNKNOWN*/;
  12157. /* adler32 value of the uncompressed data */
  12158. this.adler = 0;
  12159. }
  12160. module.exports = ZStream;
  12161. },{}],64:[function(require,module,exports){
  12162. (function (process){
  12163. 'use strict';
  12164. if (typeof process === 'undefined' ||
  12165. !process.version ||
  12166. process.version.indexOf('v0.') === 0 ||
  12167. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  12168. module.exports = { nextTick: nextTick };
  12169. } else {
  12170. module.exports = process
  12171. }
  12172. function nextTick(fn, arg1, arg2, arg3) {
  12173. if (typeof fn !== 'function') {
  12174. throw new TypeError('"callback" argument must be a function');
  12175. }
  12176. var len = arguments.length;
  12177. var args, i;
  12178. switch (len) {
  12179. case 0:
  12180. case 1:
  12181. return process.nextTick(fn);
  12182. case 2:
  12183. return process.nextTick(function afterTickOne() {
  12184. fn.call(null, arg1);
  12185. });
  12186. case 3:
  12187. return process.nextTick(function afterTickTwo() {
  12188. fn.call(null, arg1, arg2);
  12189. });
  12190. case 4:
  12191. return process.nextTick(function afterTickThree() {
  12192. fn.call(null, arg1, arg2, arg3);
  12193. });
  12194. default:
  12195. args = new Array(len - 1);
  12196. i = 0;
  12197. while (i < args.length) {
  12198. args[i++] = arguments[i];
  12199. }
  12200. return process.nextTick(function afterTick() {
  12201. fn.apply(null, args);
  12202. });
  12203. }
  12204. }
  12205. }).call(this,require('_process'))
  12206. },{"_process":65}],65:[function(require,module,exports){
  12207. // shim for using process in browser
  12208. var process = module.exports = {};
  12209. // cached from whatever global is present so that test runners that stub it
  12210. // don't break things. But we need to wrap it in a try catch in case it is
  12211. // wrapped in strict mode code which doesn't define any globals. It's inside a
  12212. // function because try/catches deoptimize in certain engines.
  12213. var cachedSetTimeout;
  12214. var cachedClearTimeout;
  12215. function defaultSetTimout() {
  12216. throw new Error('setTimeout has not been defined');
  12217. }
  12218. function defaultClearTimeout () {
  12219. throw new Error('clearTimeout has not been defined');
  12220. }
  12221. (function () {
  12222. try {
  12223. if (typeof setTimeout === 'function') {
  12224. cachedSetTimeout = setTimeout;
  12225. } else {
  12226. cachedSetTimeout = defaultSetTimout;
  12227. }
  12228. } catch (e) {
  12229. cachedSetTimeout = defaultSetTimout;
  12230. }
  12231. try {
  12232. if (typeof clearTimeout === 'function') {
  12233. cachedClearTimeout = clearTimeout;
  12234. } else {
  12235. cachedClearTimeout = defaultClearTimeout;
  12236. }
  12237. } catch (e) {
  12238. cachedClearTimeout = defaultClearTimeout;
  12239. }
  12240. } ())
  12241. function runTimeout(fun) {
  12242. if (cachedSetTimeout === setTimeout) {
  12243. //normal enviroments in sane situations
  12244. return setTimeout(fun, 0);
  12245. }
  12246. // if setTimeout wasn't available but was latter defined
  12247. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12248. cachedSetTimeout = setTimeout;
  12249. return setTimeout(fun, 0);
  12250. }
  12251. try {
  12252. // when when somebody has screwed with setTimeout but no I.E. maddness
  12253. return cachedSetTimeout(fun, 0);
  12254. } catch(e){
  12255. try {
  12256. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12257. return cachedSetTimeout.call(null, fun, 0);
  12258. } catch(e){
  12259. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  12260. return cachedSetTimeout.call(this, fun, 0);
  12261. }
  12262. }
  12263. }
  12264. function runClearTimeout(marker) {
  12265. if (cachedClearTimeout === clearTimeout) {
  12266. //normal enviroments in sane situations
  12267. return clearTimeout(marker);
  12268. }
  12269. // if clearTimeout wasn't available but was latter defined
  12270. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12271. cachedClearTimeout = clearTimeout;
  12272. return clearTimeout(marker);
  12273. }
  12274. try {
  12275. // when when somebody has screwed with setTimeout but no I.E. maddness
  12276. return cachedClearTimeout(marker);
  12277. } catch (e){
  12278. try {
  12279. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12280. return cachedClearTimeout.call(null, marker);
  12281. } catch (e){
  12282. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  12283. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  12284. return cachedClearTimeout.call(this, marker);
  12285. }
  12286. }
  12287. }
  12288. var queue = [];
  12289. var draining = false;
  12290. var currentQueue;
  12291. var queueIndex = -1;
  12292. function cleanUpNextTick() {
  12293. if (!draining || !currentQueue) {
  12294. return;
  12295. }
  12296. draining = false;
  12297. if (currentQueue.length) {
  12298. queue = currentQueue.concat(queue);
  12299. } else {
  12300. queueIndex = -1;
  12301. }
  12302. if (queue.length) {
  12303. drainQueue();
  12304. }
  12305. }
  12306. function drainQueue() {
  12307. if (draining) {
  12308. return;
  12309. }
  12310. var timeout = runTimeout(cleanUpNextTick);
  12311. draining = true;
  12312. var len = queue.length;
  12313. while(len) {
  12314. currentQueue = queue;
  12315. queue = [];
  12316. while (++queueIndex < len) {
  12317. if (currentQueue) {
  12318. currentQueue[queueIndex].run();
  12319. }
  12320. }
  12321. queueIndex = -1;
  12322. len = queue.length;
  12323. }
  12324. currentQueue = null;
  12325. draining = false;
  12326. runClearTimeout(timeout);
  12327. }
  12328. process.nextTick = function (fun) {
  12329. var args = new Array(arguments.length - 1);
  12330. if (arguments.length > 1) {
  12331. for (var i = 1; i < arguments.length; i++) {
  12332. args[i - 1] = arguments[i];
  12333. }
  12334. }
  12335. queue.push(new Item(fun, args));
  12336. if (queue.length === 1 && !draining) {
  12337. runTimeout(drainQueue);
  12338. }
  12339. };
  12340. // v8 likes predictible objects
  12341. function Item(fun, array) {
  12342. this.fun = fun;
  12343. this.array = array;
  12344. }
  12345. Item.prototype.run = function () {
  12346. this.fun.apply(null, this.array);
  12347. };
  12348. process.title = 'browser';
  12349. process.browser = true;
  12350. process.env = {};
  12351. process.argv = [];
  12352. process.version = ''; // empty string to avoid regexp issues
  12353. process.versions = {};
  12354. function noop() {}
  12355. process.on = noop;
  12356. process.addListener = noop;
  12357. process.once = noop;
  12358. process.off = noop;
  12359. process.removeListener = noop;
  12360. process.removeAllListeners = noop;
  12361. process.emit = noop;
  12362. process.prependListener = noop;
  12363. process.prependOnceListener = noop;
  12364. process.listeners = function (name) { return [] }
  12365. process.binding = function (name) {
  12366. throw new Error('process.binding is not supported');
  12367. };
  12368. process.cwd = function () { return '/' };
  12369. process.chdir = function (dir) {
  12370. throw new Error('process.chdir is not supported');
  12371. };
  12372. process.umask = function() { return 0; };
  12373. },{}],66:[function(require,module,exports){
  12374. module.exports = require('./lib/_stream_duplex.js');
  12375. },{"./lib/_stream_duplex.js":67}],67:[function(require,module,exports){
  12376. // Copyright Joyent, Inc. and other Node contributors.
  12377. //
  12378. // Permission is hereby granted, free of charge, to any person obtaining a
  12379. // copy of this software and associated documentation files (the
  12380. // "Software"), to deal in the Software without restriction, including
  12381. // without limitation the rights to use, copy, modify, merge, publish,
  12382. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12383. // persons to whom the Software is furnished to do so, subject to the
  12384. // following conditions:
  12385. //
  12386. // The above copyright notice and this permission notice shall be included
  12387. // in all copies or substantial portions of the Software.
  12388. //
  12389. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12390. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12391. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12392. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12393. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12394. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12395. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12396. // a duplex stream is just a stream that is both readable and writable.
  12397. // Since JS doesn't have multiple prototypal inheritance, this class
  12398. // prototypally inherits from Readable, and then parasitically from
  12399. // Writable.
  12400. 'use strict';
  12401. /*<replacement>*/
  12402. var pna = require('process-nextick-args');
  12403. /*</replacement>*/
  12404. /*<replacement>*/
  12405. var objectKeys = Object.keys || function (obj) {
  12406. var keys = [];
  12407. for (var key in obj) {
  12408. keys.push(key);
  12409. }return keys;
  12410. };
  12411. /*</replacement>*/
  12412. module.exports = Duplex;
  12413. /*<replacement>*/
  12414. var util = Object.create(require('core-util-is'));
  12415. util.inherits = require('inherits');
  12416. /*</replacement>*/
  12417. var Readable = require('./_stream_readable');
  12418. var Writable = require('./_stream_writable');
  12419. util.inherits(Duplex, Readable);
  12420. {
  12421. // avoid scope creep, the keys array can then be collected
  12422. var keys = objectKeys(Writable.prototype);
  12423. for (var v = 0; v < keys.length; v++) {
  12424. var method = keys[v];
  12425. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  12426. }
  12427. }
  12428. function Duplex(options) {
  12429. if (!(this instanceof Duplex)) return new Duplex(options);
  12430. Readable.call(this, options);
  12431. Writable.call(this, options);
  12432. if (options && options.readable === false) this.readable = false;
  12433. if (options && options.writable === false) this.writable = false;
  12434. this.allowHalfOpen = true;
  12435. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  12436. this.once('end', onend);
  12437. }
  12438. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  12439. // making it explicit this property is not enumerable
  12440. // because otherwise some prototype manipulation in
  12441. // userland will fail
  12442. enumerable: false,
  12443. get: function () {
  12444. return this._writableState.highWaterMark;
  12445. }
  12446. });
  12447. // the no-half-open enforcer
  12448. function onend() {
  12449. // if we allow half-open state, or if the writable side ended,
  12450. // then we're ok.
  12451. if (this.allowHalfOpen || this._writableState.ended) return;
  12452. // no more data can be written.
  12453. // But allow more writes to happen in this tick.
  12454. pna.nextTick(onEndNT, this);
  12455. }
  12456. function onEndNT(self) {
  12457. self.end();
  12458. }
  12459. Object.defineProperty(Duplex.prototype, 'destroyed', {
  12460. get: function () {
  12461. if (this._readableState === undefined || this._writableState === undefined) {
  12462. return false;
  12463. }
  12464. return this._readableState.destroyed && this._writableState.destroyed;
  12465. },
  12466. set: function (value) {
  12467. // we ignore the value if the stream
  12468. // has not been initialized yet
  12469. if (this._readableState === undefined || this._writableState === undefined) {
  12470. return;
  12471. }
  12472. // backward compatibility, the user is explicitly
  12473. // managing destroyed
  12474. this._readableState.destroyed = value;
  12475. this._writableState.destroyed = value;
  12476. }
  12477. });
  12478. Duplex.prototype._destroy = function (err, cb) {
  12479. this.push(null);
  12480. this.end();
  12481. pna.nextTick(cb, err);
  12482. };
  12483. },{"./_stream_readable":69,"./_stream_writable":71,"core-util-is":4,"inherits":9,"process-nextick-args":64}],68:[function(require,module,exports){
  12484. // Copyright Joyent, Inc. and other Node contributors.
  12485. //
  12486. // Permission is hereby granted, free of charge, to any person obtaining a
  12487. // copy of this software and associated documentation files (the
  12488. // "Software"), to deal in the Software without restriction, including
  12489. // without limitation the rights to use, copy, modify, merge, publish,
  12490. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12491. // persons to whom the Software is furnished to do so, subject to the
  12492. // following conditions:
  12493. //
  12494. // The above copyright notice and this permission notice shall be included
  12495. // in all copies or substantial portions of the Software.
  12496. //
  12497. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12498. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12499. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12500. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12501. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12502. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12503. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12504. // a passthrough stream.
  12505. // basically just the most minimal sort of Transform stream.
  12506. // Every written chunk gets output as-is.
  12507. 'use strict';
  12508. module.exports = PassThrough;
  12509. var Transform = require('./_stream_transform');
  12510. /*<replacement>*/
  12511. var util = Object.create(require('core-util-is'));
  12512. util.inherits = require('inherits');
  12513. /*</replacement>*/
  12514. util.inherits(PassThrough, Transform);
  12515. function PassThrough(options) {
  12516. if (!(this instanceof PassThrough)) return new PassThrough(options);
  12517. Transform.call(this, options);
  12518. }
  12519. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  12520. cb(null, chunk);
  12521. };
  12522. },{"./_stream_transform":70,"core-util-is":4,"inherits":9}],69:[function(require,module,exports){
  12523. (function (process,global){
  12524. // Copyright Joyent, Inc. and other Node contributors.
  12525. //
  12526. // Permission is hereby granted, free of charge, to any person obtaining a
  12527. // copy of this software and associated documentation files (the
  12528. // "Software"), to deal in the Software without restriction, including
  12529. // without limitation the rights to use, copy, modify, merge, publish,
  12530. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12531. // persons to whom the Software is furnished to do so, subject to the
  12532. // following conditions:
  12533. //
  12534. // The above copyright notice and this permission notice shall be included
  12535. // in all copies or substantial portions of the Software.
  12536. //
  12537. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12538. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12539. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12540. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12541. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12542. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12543. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12544. 'use strict';
  12545. /*<replacement>*/
  12546. var pna = require('process-nextick-args');
  12547. /*</replacement>*/
  12548. module.exports = Readable;
  12549. /*<replacement>*/
  12550. var isArray = require('isarray');
  12551. /*</replacement>*/
  12552. /*<replacement>*/
  12553. var Duplex;
  12554. /*</replacement>*/
  12555. Readable.ReadableState = ReadableState;
  12556. /*<replacement>*/
  12557. var EE = require('events').EventEmitter;
  12558. var EElistenerCount = function (emitter, type) {
  12559. return emitter.listeners(type).length;
  12560. };
  12561. /*</replacement>*/
  12562. /*<replacement>*/
  12563. var Stream = require('./internal/streams/stream');
  12564. /*</replacement>*/
  12565. /*<replacement>*/
  12566. var Buffer = require('safe-buffer').Buffer;
  12567. var OurUint8Array = global.Uint8Array || function () {};
  12568. function _uint8ArrayToBuffer(chunk) {
  12569. return Buffer.from(chunk);
  12570. }
  12571. function _isUint8Array(obj) {
  12572. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12573. }
  12574. /*</replacement>*/
  12575. /*<replacement>*/
  12576. var util = Object.create(require('core-util-is'));
  12577. util.inherits = require('inherits');
  12578. /*</replacement>*/
  12579. /*<replacement>*/
  12580. var debugUtil = require('util');
  12581. var debug = void 0;
  12582. if (debugUtil && debugUtil.debuglog) {
  12583. debug = debugUtil.debuglog('stream');
  12584. } else {
  12585. debug = function () {};
  12586. }
  12587. /*</replacement>*/
  12588. var BufferList = require('./internal/streams/BufferList');
  12589. var destroyImpl = require('./internal/streams/destroy');
  12590. var StringDecoder;
  12591. util.inherits(Readable, Stream);
  12592. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  12593. function prependListener(emitter, event, fn) {
  12594. // Sadly this is not cacheable as some libraries bundle their own
  12595. // event emitter implementation with them.
  12596. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  12597. // This is a hack to make sure that our error handler is attached before any
  12598. // userland ones. NEVER DO THIS. This is here only because this code needs
  12599. // to continue to work with older versions of Node.js that do not include
  12600. // the prependListener() method. The goal is to eventually remove this hack.
  12601. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  12602. }
  12603. function ReadableState(options, stream) {
  12604. Duplex = Duplex || require('./_stream_duplex');
  12605. options = options || {};
  12606. // Duplex streams are both readable and writable, but share
  12607. // the same options object.
  12608. // However, some cases require setting options to different
  12609. // values for the readable and the writable sides of the duplex stream.
  12610. // These options can be provided separately as readableXXX and writableXXX.
  12611. var isDuplex = stream instanceof Duplex;
  12612. // object stream flag. Used to make read(n) ignore n and to
  12613. // make all the buffer merging and length checks go away
  12614. this.objectMode = !!options.objectMode;
  12615. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  12616. // the point at which it stops calling _read() to fill the buffer
  12617. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  12618. var hwm = options.highWaterMark;
  12619. var readableHwm = options.readableHighWaterMark;
  12620. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  12621. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  12622. // cast to ints.
  12623. this.highWaterMark = Math.floor(this.highWaterMark);
  12624. // A linked list is used to store data chunks instead of an array because the
  12625. // linked list can remove elements from the beginning faster than
  12626. // array.shift()
  12627. this.buffer = new BufferList();
  12628. this.length = 0;
  12629. this.pipes = null;
  12630. this.pipesCount = 0;
  12631. this.flowing = null;
  12632. this.ended = false;
  12633. this.endEmitted = false;
  12634. this.reading = false;
  12635. // a flag to be able to tell if the event 'readable'/'data' is emitted
  12636. // immediately, or on a later tick. We set this to true at first, because
  12637. // any actions that shouldn't happen until "later" should generally also
  12638. // not happen before the first read call.
  12639. this.sync = true;
  12640. // whenever we return null, then we set a flag to say
  12641. // that we're awaiting a 'readable' event emission.
  12642. this.needReadable = false;
  12643. this.emittedReadable = false;
  12644. this.readableListening = false;
  12645. this.resumeScheduled = false;
  12646. // has it been destroyed
  12647. this.destroyed = false;
  12648. // Crypto is kind of old and crusty. Historically, its default string
  12649. // encoding is 'binary' so we have to make this configurable.
  12650. // Everything else in the universe uses 'utf8', though.
  12651. this.defaultEncoding = options.defaultEncoding || 'utf8';
  12652. // the number of writers that are awaiting a drain event in .pipe()s
  12653. this.awaitDrain = 0;
  12654. // if true, a maybeReadMore has been scheduled
  12655. this.readingMore = false;
  12656. this.decoder = null;
  12657. this.encoding = null;
  12658. if (options.encoding) {
  12659. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12660. this.decoder = new StringDecoder(options.encoding);
  12661. this.encoding = options.encoding;
  12662. }
  12663. }
  12664. function Readable(options) {
  12665. Duplex = Duplex || require('./_stream_duplex');
  12666. if (!(this instanceof Readable)) return new Readable(options);
  12667. this._readableState = new ReadableState(options, this);
  12668. // legacy
  12669. this.readable = true;
  12670. if (options) {
  12671. if (typeof options.read === 'function') this._read = options.read;
  12672. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12673. }
  12674. Stream.call(this);
  12675. }
  12676. Object.defineProperty(Readable.prototype, 'destroyed', {
  12677. get: function () {
  12678. if (this._readableState === undefined) {
  12679. return false;
  12680. }
  12681. return this._readableState.destroyed;
  12682. },
  12683. set: function (value) {
  12684. // we ignore the value if the stream
  12685. // has not been initialized yet
  12686. if (!this._readableState) {
  12687. return;
  12688. }
  12689. // backward compatibility, the user is explicitly
  12690. // managing destroyed
  12691. this._readableState.destroyed = value;
  12692. }
  12693. });
  12694. Readable.prototype.destroy = destroyImpl.destroy;
  12695. Readable.prototype._undestroy = destroyImpl.undestroy;
  12696. Readable.prototype._destroy = function (err, cb) {
  12697. this.push(null);
  12698. cb(err);
  12699. };
  12700. // Manually shove something into the read() buffer.
  12701. // This returns true if the highWaterMark has not been hit yet,
  12702. // similar to how Writable.write() returns true if you should
  12703. // write() some more.
  12704. Readable.prototype.push = function (chunk, encoding) {
  12705. var state = this._readableState;
  12706. var skipChunkCheck;
  12707. if (!state.objectMode) {
  12708. if (typeof chunk === 'string') {
  12709. encoding = encoding || state.defaultEncoding;
  12710. if (encoding !== state.encoding) {
  12711. chunk = Buffer.from(chunk, encoding);
  12712. encoding = '';
  12713. }
  12714. skipChunkCheck = true;
  12715. }
  12716. } else {
  12717. skipChunkCheck = true;
  12718. }
  12719. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  12720. };
  12721. // Unshift should *always* be something directly out of read()
  12722. Readable.prototype.unshift = function (chunk) {
  12723. return readableAddChunk(this, chunk, null, true, false);
  12724. };
  12725. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  12726. var state = stream._readableState;
  12727. if (chunk === null) {
  12728. state.reading = false;
  12729. onEofChunk(stream, state);
  12730. } else {
  12731. var er;
  12732. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  12733. if (er) {
  12734. stream.emit('error', er);
  12735. } else if (state.objectMode || chunk && chunk.length > 0) {
  12736. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  12737. chunk = _uint8ArrayToBuffer(chunk);
  12738. }
  12739. if (addToFront) {
  12740. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  12741. } else if (state.ended) {
  12742. stream.emit('error', new Error('stream.push() after EOF'));
  12743. } else {
  12744. state.reading = false;
  12745. if (state.decoder && !encoding) {
  12746. chunk = state.decoder.write(chunk);
  12747. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  12748. } else {
  12749. addChunk(stream, state, chunk, false);
  12750. }
  12751. }
  12752. } else if (!addToFront) {
  12753. state.reading = false;
  12754. }
  12755. }
  12756. return needMoreData(state);
  12757. }
  12758. function addChunk(stream, state, chunk, addToFront) {
  12759. if (state.flowing && state.length === 0 && !state.sync) {
  12760. stream.emit('data', chunk);
  12761. stream.read(0);
  12762. } else {
  12763. // update the buffer info.
  12764. state.length += state.objectMode ? 1 : chunk.length;
  12765. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  12766. if (state.needReadable) emitReadable(stream);
  12767. }
  12768. maybeReadMore(stream, state);
  12769. }
  12770. function chunkInvalid(state, chunk) {
  12771. var er;
  12772. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12773. er = new TypeError('Invalid non-string/buffer chunk');
  12774. }
  12775. return er;
  12776. }
  12777. // if it's past the high water mark, we can push in some more.
  12778. // Also, if we have no data yet, we can stand some
  12779. // more bytes. This is to work around cases where hwm=0,
  12780. // such as the repl. Also, if the push() triggered a
  12781. // readable event, and the user called read(largeNumber) such that
  12782. // needReadable was set, then we ought to push more, so that another
  12783. // 'readable' event will be triggered.
  12784. function needMoreData(state) {
  12785. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  12786. }
  12787. Readable.prototype.isPaused = function () {
  12788. return this._readableState.flowing === false;
  12789. };
  12790. // backwards compatibility.
  12791. Readable.prototype.setEncoding = function (enc) {
  12792. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12793. this._readableState.decoder = new StringDecoder(enc);
  12794. this._readableState.encoding = enc;
  12795. return this;
  12796. };
  12797. // Don't raise the hwm > 8MB
  12798. var MAX_HWM = 0x800000;
  12799. function computeNewHighWaterMark(n) {
  12800. if (n >= MAX_HWM) {
  12801. n = MAX_HWM;
  12802. } else {
  12803. // Get the next highest power of 2 to prevent increasing hwm excessively in
  12804. // tiny amounts
  12805. n--;
  12806. n |= n >>> 1;
  12807. n |= n >>> 2;
  12808. n |= n >>> 4;
  12809. n |= n >>> 8;
  12810. n |= n >>> 16;
  12811. n++;
  12812. }
  12813. return n;
  12814. }
  12815. // This function is designed to be inlinable, so please take care when making
  12816. // changes to the function body.
  12817. function howMuchToRead(n, state) {
  12818. if (n <= 0 || state.length === 0 && state.ended) return 0;
  12819. if (state.objectMode) return 1;
  12820. if (n !== n) {
  12821. // Only flow one buffer at a time
  12822. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  12823. }
  12824. // If we're asking for more than the current hwm, then raise the hwm.
  12825. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  12826. if (n <= state.length) return n;
  12827. // Don't have enough
  12828. if (!state.ended) {
  12829. state.needReadable = true;
  12830. return 0;
  12831. }
  12832. return state.length;
  12833. }
  12834. // you can override either this method, or the async _read(n) below.
  12835. Readable.prototype.read = function (n) {
  12836. debug('read', n);
  12837. n = parseInt(n, 10);
  12838. var state = this._readableState;
  12839. var nOrig = n;
  12840. if (n !== 0) state.emittedReadable = false;
  12841. // if we're doing read(0) to trigger a readable event, but we
  12842. // already have a bunch of data in the buffer, then just trigger
  12843. // the 'readable' event and move on.
  12844. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  12845. debug('read: emitReadable', state.length, state.ended);
  12846. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  12847. return null;
  12848. }
  12849. n = howMuchToRead(n, state);
  12850. // if we've ended, and we're now clear, then finish it up.
  12851. if (n === 0 && state.ended) {
  12852. if (state.length === 0) endReadable(this);
  12853. return null;
  12854. }
  12855. // All the actual chunk generation logic needs to be
  12856. // *below* the call to _read. The reason is that in certain
  12857. // synthetic stream cases, such as passthrough streams, _read
  12858. // may be a completely synchronous operation which may change
  12859. // the state of the read buffer, providing enough data when
  12860. // before there was *not* enough.
  12861. //
  12862. // So, the steps are:
  12863. // 1. Figure out what the state of things will be after we do
  12864. // a read from the buffer.
  12865. //
  12866. // 2. If that resulting state will trigger a _read, then call _read.
  12867. // Note that this may be asynchronous, or synchronous. Yes, it is
  12868. // deeply ugly to write APIs this way, but that still doesn't mean
  12869. // that the Readable class should behave improperly, as streams are
  12870. // designed to be sync/async agnostic.
  12871. // Take note if the _read call is sync or async (ie, if the read call
  12872. // has returned yet), so that we know whether or not it's safe to emit
  12873. // 'readable' etc.
  12874. //
  12875. // 3. Actually pull the requested chunks out of the buffer and return.
  12876. // if we need a readable event, then we need to do some reading.
  12877. var doRead = state.needReadable;
  12878. debug('need readable', doRead);
  12879. // if we currently have less than the highWaterMark, then also read some
  12880. if (state.length === 0 || state.length - n < state.highWaterMark) {
  12881. doRead = true;
  12882. debug('length less than watermark', doRead);
  12883. }
  12884. // however, if we've ended, then there's no point, and if we're already
  12885. // reading, then it's unnecessary.
  12886. if (state.ended || state.reading) {
  12887. doRead = false;
  12888. debug('reading or ended', doRead);
  12889. } else if (doRead) {
  12890. debug('do read');
  12891. state.reading = true;
  12892. state.sync = true;
  12893. // if the length is currently zero, then we *need* a readable event.
  12894. if (state.length === 0) state.needReadable = true;
  12895. // call internal read method
  12896. this._read(state.highWaterMark);
  12897. state.sync = false;
  12898. // If _read pushed data synchronously, then `reading` will be false,
  12899. // and we need to re-evaluate how much data we can return to the user.
  12900. if (!state.reading) n = howMuchToRead(nOrig, state);
  12901. }
  12902. var ret;
  12903. if (n > 0) ret = fromList(n, state);else ret = null;
  12904. if (ret === null) {
  12905. state.needReadable = true;
  12906. n = 0;
  12907. } else {
  12908. state.length -= n;
  12909. }
  12910. if (state.length === 0) {
  12911. // If we have nothing in the buffer, then we want to know
  12912. // as soon as we *do* get something into the buffer.
  12913. if (!state.ended) state.needReadable = true;
  12914. // If we tried to read() past the EOF, then emit end on the next tick.
  12915. if (nOrig !== n && state.ended) endReadable(this);
  12916. }
  12917. if (ret !== null) this.emit('data', ret);
  12918. return ret;
  12919. };
  12920. function onEofChunk(stream, state) {
  12921. if (state.ended) return;
  12922. if (state.decoder) {
  12923. var chunk = state.decoder.end();
  12924. if (chunk && chunk.length) {
  12925. state.buffer.push(chunk);
  12926. state.length += state.objectMode ? 1 : chunk.length;
  12927. }
  12928. }
  12929. state.ended = true;
  12930. // emit 'readable' now to make sure it gets picked up.
  12931. emitReadable(stream);
  12932. }
  12933. // Don't emit readable right away in sync mode, because this can trigger
  12934. // another read() call => stack overflow. This way, it might trigger
  12935. // a nextTick recursion warning, but that's not so bad.
  12936. function emitReadable(stream) {
  12937. var state = stream._readableState;
  12938. state.needReadable = false;
  12939. if (!state.emittedReadable) {
  12940. debug('emitReadable', state.flowing);
  12941. state.emittedReadable = true;
  12942. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  12943. }
  12944. }
  12945. function emitReadable_(stream) {
  12946. debug('emit readable');
  12947. stream.emit('readable');
  12948. flow(stream);
  12949. }
  12950. // at this point, the user has presumably seen the 'readable' event,
  12951. // and called read() to consume some data. that may have triggered
  12952. // in turn another _read(n) call, in which case reading = true if
  12953. // it's in progress.
  12954. // However, if we're not ended, or reading, and the length < hwm,
  12955. // then go ahead and try to read some more preemptively.
  12956. function maybeReadMore(stream, state) {
  12957. if (!state.readingMore) {
  12958. state.readingMore = true;
  12959. pna.nextTick(maybeReadMore_, stream, state);
  12960. }
  12961. }
  12962. function maybeReadMore_(stream, state) {
  12963. var len = state.length;
  12964. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  12965. debug('maybeReadMore read 0');
  12966. stream.read(0);
  12967. if (len === state.length)
  12968. // didn't get any data, stop spinning.
  12969. break;else len = state.length;
  12970. }
  12971. state.readingMore = false;
  12972. }
  12973. // abstract method. to be overridden in specific implementation classes.
  12974. // call cb(er, data) where data is <= n in length.
  12975. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  12976. // arbitrary, and perhaps not very meaningful.
  12977. Readable.prototype._read = function (n) {
  12978. this.emit('error', new Error('_read() is not implemented'));
  12979. };
  12980. Readable.prototype.pipe = function (dest, pipeOpts) {
  12981. var src = this;
  12982. var state = this._readableState;
  12983. switch (state.pipesCount) {
  12984. case 0:
  12985. state.pipes = dest;
  12986. break;
  12987. case 1:
  12988. state.pipes = [state.pipes, dest];
  12989. break;
  12990. default:
  12991. state.pipes.push(dest);
  12992. break;
  12993. }
  12994. state.pipesCount += 1;
  12995. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  12996. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  12997. var endFn = doEnd ? onend : unpipe;
  12998. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  12999. dest.on('unpipe', onunpipe);
  13000. function onunpipe(readable, unpipeInfo) {
  13001. debug('onunpipe');
  13002. if (readable === src) {
  13003. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  13004. unpipeInfo.hasUnpiped = true;
  13005. cleanup();
  13006. }
  13007. }
  13008. }
  13009. function onend() {
  13010. debug('onend');
  13011. dest.end();
  13012. }
  13013. // when the dest drains, it reduces the awaitDrain counter
  13014. // on the source. This would be more elegant with a .once()
  13015. // handler in flow(), but adding and removing repeatedly is
  13016. // too slow.
  13017. var ondrain = pipeOnDrain(src);
  13018. dest.on('drain', ondrain);
  13019. var cleanedUp = false;
  13020. function cleanup() {
  13021. debug('cleanup');
  13022. // cleanup event handlers once the pipe is broken
  13023. dest.removeListener('close', onclose);
  13024. dest.removeListener('finish', onfinish);
  13025. dest.removeListener('drain', ondrain);
  13026. dest.removeListener('error', onerror);
  13027. dest.removeListener('unpipe', onunpipe);
  13028. src.removeListener('end', onend);
  13029. src.removeListener('end', unpipe);
  13030. src.removeListener('data', ondata);
  13031. cleanedUp = true;
  13032. // if the reader is waiting for a drain event from this
  13033. // specific writer, then it would cause it to never start
  13034. // flowing again.
  13035. // So, if this is awaiting a drain, then we just call it now.
  13036. // If we don't know, then assume that we are waiting for one.
  13037. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  13038. }
  13039. // If the user pushes more data while we're writing to dest then we'll end up
  13040. // in ondata again. However, we only want to increase awaitDrain once because
  13041. // dest will only emit one 'drain' event for the multiple writes.
  13042. // => Introduce a guard on increasing awaitDrain.
  13043. var increasedAwaitDrain = false;
  13044. src.on('data', ondata);
  13045. function ondata(chunk) {
  13046. debug('ondata');
  13047. increasedAwaitDrain = false;
  13048. var ret = dest.write(chunk);
  13049. if (false === ret && !increasedAwaitDrain) {
  13050. // If the user unpiped during `dest.write()`, it is possible
  13051. // to get stuck in a permanently paused state if that write
  13052. // also returned false.
  13053. // => Check whether `dest` is still a piping destination.
  13054. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  13055. debug('false write response, pause', src._readableState.awaitDrain);
  13056. src._readableState.awaitDrain++;
  13057. increasedAwaitDrain = true;
  13058. }
  13059. src.pause();
  13060. }
  13061. }
  13062. // if the dest has an error, then stop piping into it.
  13063. // however, don't suppress the throwing behavior for this.
  13064. function onerror(er) {
  13065. debug('onerror', er);
  13066. unpipe();
  13067. dest.removeListener('error', onerror);
  13068. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  13069. }
  13070. // Make sure our error handler is attached before userland ones.
  13071. prependListener(dest, 'error', onerror);
  13072. // Both close and finish should trigger unpipe, but only once.
  13073. function onclose() {
  13074. dest.removeListener('finish', onfinish);
  13075. unpipe();
  13076. }
  13077. dest.once('close', onclose);
  13078. function onfinish() {
  13079. debug('onfinish');
  13080. dest.removeListener('close', onclose);
  13081. unpipe();
  13082. }
  13083. dest.once('finish', onfinish);
  13084. function unpipe() {
  13085. debug('unpipe');
  13086. src.unpipe(dest);
  13087. }
  13088. // tell the dest that it's being piped to
  13089. dest.emit('pipe', src);
  13090. // start the flow if it hasn't been started already.
  13091. if (!state.flowing) {
  13092. debug('pipe resume');
  13093. src.resume();
  13094. }
  13095. return dest;
  13096. };
  13097. function pipeOnDrain(src) {
  13098. return function () {
  13099. var state = src._readableState;
  13100. debug('pipeOnDrain', state.awaitDrain);
  13101. if (state.awaitDrain) state.awaitDrain--;
  13102. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  13103. state.flowing = true;
  13104. flow(src);
  13105. }
  13106. };
  13107. }
  13108. Readable.prototype.unpipe = function (dest) {
  13109. var state = this._readableState;
  13110. var unpipeInfo = { hasUnpiped: false };
  13111. // if we're not piping anywhere, then do nothing.
  13112. if (state.pipesCount === 0) return this;
  13113. // just one destination. most common case.
  13114. if (state.pipesCount === 1) {
  13115. // passed in one, but it's not the right one.
  13116. if (dest && dest !== state.pipes) return this;
  13117. if (!dest) dest = state.pipes;
  13118. // got a match.
  13119. state.pipes = null;
  13120. state.pipesCount = 0;
  13121. state.flowing = false;
  13122. if (dest) dest.emit('unpipe', this, unpipeInfo);
  13123. return this;
  13124. }
  13125. // slow case. multiple pipe destinations.
  13126. if (!dest) {
  13127. // remove all.
  13128. var dests = state.pipes;
  13129. var len = state.pipesCount;
  13130. state.pipes = null;
  13131. state.pipesCount = 0;
  13132. state.flowing = false;
  13133. for (var i = 0; i < len; i++) {
  13134. dests[i].emit('unpipe', this, unpipeInfo);
  13135. }return this;
  13136. }
  13137. // try to find the right one.
  13138. var index = indexOf(state.pipes, dest);
  13139. if (index === -1) return this;
  13140. state.pipes.splice(index, 1);
  13141. state.pipesCount -= 1;
  13142. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  13143. dest.emit('unpipe', this, unpipeInfo);
  13144. return this;
  13145. };
  13146. // set up data events if they are asked for
  13147. // Ensure readable listeners eventually get something
  13148. Readable.prototype.on = function (ev, fn) {
  13149. var res = Stream.prototype.on.call(this, ev, fn);
  13150. if (ev === 'data') {
  13151. // Start flowing on next tick if stream isn't explicitly paused
  13152. if (this._readableState.flowing !== false) this.resume();
  13153. } else if (ev === 'readable') {
  13154. var state = this._readableState;
  13155. if (!state.endEmitted && !state.readableListening) {
  13156. state.readableListening = state.needReadable = true;
  13157. state.emittedReadable = false;
  13158. if (!state.reading) {
  13159. pna.nextTick(nReadingNextTick, this);
  13160. } else if (state.length) {
  13161. emitReadable(this);
  13162. }
  13163. }
  13164. }
  13165. return res;
  13166. };
  13167. Readable.prototype.addListener = Readable.prototype.on;
  13168. function nReadingNextTick(self) {
  13169. debug('readable nexttick read 0');
  13170. self.read(0);
  13171. }
  13172. // pause() and resume() are remnants of the legacy readable stream API
  13173. // If the user uses them, then switch into old mode.
  13174. Readable.prototype.resume = function () {
  13175. var state = this._readableState;
  13176. if (!state.flowing) {
  13177. debug('resume');
  13178. state.flowing = true;
  13179. resume(this, state);
  13180. }
  13181. return this;
  13182. };
  13183. function resume(stream, state) {
  13184. if (!state.resumeScheduled) {
  13185. state.resumeScheduled = true;
  13186. pna.nextTick(resume_, stream, state);
  13187. }
  13188. }
  13189. function resume_(stream, state) {
  13190. if (!state.reading) {
  13191. debug('resume read 0');
  13192. stream.read(0);
  13193. }
  13194. state.resumeScheduled = false;
  13195. state.awaitDrain = 0;
  13196. stream.emit('resume');
  13197. flow(stream);
  13198. if (state.flowing && !state.reading) stream.read(0);
  13199. }
  13200. Readable.prototype.pause = function () {
  13201. debug('call pause flowing=%j', this._readableState.flowing);
  13202. if (false !== this._readableState.flowing) {
  13203. debug('pause');
  13204. this._readableState.flowing = false;
  13205. this.emit('pause');
  13206. }
  13207. return this;
  13208. };
  13209. function flow(stream) {
  13210. var state = stream._readableState;
  13211. debug('flow', state.flowing);
  13212. while (state.flowing && stream.read() !== null) {}
  13213. }
  13214. // wrap an old-style stream as the async data source.
  13215. // This is *not* part of the readable stream interface.
  13216. // It is an ugly unfortunate mess of history.
  13217. Readable.prototype.wrap = function (stream) {
  13218. var _this = this;
  13219. var state = this._readableState;
  13220. var paused = false;
  13221. stream.on('end', function () {
  13222. debug('wrapped end');
  13223. if (state.decoder && !state.ended) {
  13224. var chunk = state.decoder.end();
  13225. if (chunk && chunk.length) _this.push(chunk);
  13226. }
  13227. _this.push(null);
  13228. });
  13229. stream.on('data', function (chunk) {
  13230. debug('wrapped data');
  13231. if (state.decoder) chunk = state.decoder.write(chunk);
  13232. // don't skip over falsy values in objectMode
  13233. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  13234. var ret = _this.push(chunk);
  13235. if (!ret) {
  13236. paused = true;
  13237. stream.pause();
  13238. }
  13239. });
  13240. // proxy all the other methods.
  13241. // important when wrapping filters and duplexes.
  13242. for (var i in stream) {
  13243. if (this[i] === undefined && typeof stream[i] === 'function') {
  13244. this[i] = function (method) {
  13245. return function () {
  13246. return stream[method].apply(stream, arguments);
  13247. };
  13248. }(i);
  13249. }
  13250. }
  13251. // proxy certain important events.
  13252. for (var n = 0; n < kProxyEvents.length; n++) {
  13253. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  13254. }
  13255. // when we try to consume some more bytes, simply unpause the
  13256. // underlying stream.
  13257. this._read = function (n) {
  13258. debug('wrapped _read', n);
  13259. if (paused) {
  13260. paused = false;
  13261. stream.resume();
  13262. }
  13263. };
  13264. return this;
  13265. };
  13266. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  13267. // making it explicit this property is not enumerable
  13268. // because otherwise some prototype manipulation in
  13269. // userland will fail
  13270. enumerable: false,
  13271. get: function () {
  13272. return this._readableState.highWaterMark;
  13273. }
  13274. });
  13275. // exposed for testing purposes only.
  13276. Readable._fromList = fromList;
  13277. // Pluck off n bytes from an array of buffers.
  13278. // Length is the combined lengths of all the buffers in the list.
  13279. // This function is designed to be inlinable, so please take care when making
  13280. // changes to the function body.
  13281. function fromList(n, state) {
  13282. // nothing buffered
  13283. if (state.length === 0) return null;
  13284. var ret;
  13285. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  13286. // read it all, truncate the list
  13287. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  13288. state.buffer.clear();
  13289. } else {
  13290. // read part of list
  13291. ret = fromListPartial(n, state.buffer, state.decoder);
  13292. }
  13293. return ret;
  13294. }
  13295. // Extracts only enough buffered data to satisfy the amount requested.
  13296. // This function is designed to be inlinable, so please take care when making
  13297. // changes to the function body.
  13298. function fromListPartial(n, list, hasStrings) {
  13299. var ret;
  13300. if (n < list.head.data.length) {
  13301. // slice is the same for buffers and strings
  13302. ret = list.head.data.slice(0, n);
  13303. list.head.data = list.head.data.slice(n);
  13304. } else if (n === list.head.data.length) {
  13305. // first chunk is a perfect match
  13306. ret = list.shift();
  13307. } else {
  13308. // result spans more than one buffer
  13309. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  13310. }
  13311. return ret;
  13312. }
  13313. // Copies a specified amount of characters from the list of buffered data
  13314. // chunks.
  13315. // This function is designed to be inlinable, so please take care when making
  13316. // changes to the function body.
  13317. function copyFromBufferString(n, list) {
  13318. var p = list.head;
  13319. var c = 1;
  13320. var ret = p.data;
  13321. n -= ret.length;
  13322. while (p = p.next) {
  13323. var str = p.data;
  13324. var nb = n > str.length ? str.length : n;
  13325. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  13326. n -= nb;
  13327. if (n === 0) {
  13328. if (nb === str.length) {
  13329. ++c;
  13330. if (p.next) list.head = p.next;else list.head = list.tail = null;
  13331. } else {
  13332. list.head = p;
  13333. p.data = str.slice(nb);
  13334. }
  13335. break;
  13336. }
  13337. ++c;
  13338. }
  13339. list.length -= c;
  13340. return ret;
  13341. }
  13342. // Copies a specified amount of bytes from the list of buffered data chunks.
  13343. // This function is designed to be inlinable, so please take care when making
  13344. // changes to the function body.
  13345. function copyFromBuffer(n, list) {
  13346. var ret = Buffer.allocUnsafe(n);
  13347. var p = list.head;
  13348. var c = 1;
  13349. p.data.copy(ret);
  13350. n -= p.data.length;
  13351. while (p = p.next) {
  13352. var buf = p.data;
  13353. var nb = n > buf.length ? buf.length : n;
  13354. buf.copy(ret, ret.length - n, 0, nb);
  13355. n -= nb;
  13356. if (n === 0) {
  13357. if (nb === buf.length) {
  13358. ++c;
  13359. if (p.next) list.head = p.next;else list.head = list.tail = null;
  13360. } else {
  13361. list.head = p;
  13362. p.data = buf.slice(nb);
  13363. }
  13364. break;
  13365. }
  13366. ++c;
  13367. }
  13368. list.length -= c;
  13369. return ret;
  13370. }
  13371. function endReadable(stream) {
  13372. var state = stream._readableState;
  13373. // If we get here before consuming all the bytes, then that is a
  13374. // bug in node. Should never happen.
  13375. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  13376. if (!state.endEmitted) {
  13377. state.ended = true;
  13378. pna.nextTick(endReadableNT, state, stream);
  13379. }
  13380. }
  13381. function endReadableNT(state, stream) {
  13382. // Check that we didn't get one last unshift.
  13383. if (!state.endEmitted && state.length === 0) {
  13384. state.endEmitted = true;
  13385. stream.readable = false;
  13386. stream.emit('end');
  13387. }
  13388. }
  13389. function indexOf(xs, x) {
  13390. for (var i = 0, l = xs.length; i < l; i++) {
  13391. if (xs[i] === x) return i;
  13392. }
  13393. return -1;
  13394. }
  13395. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13396. },{"./_stream_duplex":67,"./internal/streams/BufferList":72,"./internal/streams/destroy":73,"./internal/streams/stream":74,"_process":65,"core-util-is":4,"events":6,"inherits":9,"isarray":11,"process-nextick-args":64,"safe-buffer":79,"string_decoder/":82,"util":2}],70:[function(require,module,exports){
  13397. // Copyright Joyent, Inc. and other Node contributors.
  13398. //
  13399. // Permission is hereby granted, free of charge, to any person obtaining a
  13400. // copy of this software and associated documentation files (the
  13401. // "Software"), to deal in the Software without restriction, including
  13402. // without limitation the rights to use, copy, modify, merge, publish,
  13403. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13404. // persons to whom the Software is furnished to do so, subject to the
  13405. // following conditions:
  13406. //
  13407. // The above copyright notice and this permission notice shall be included
  13408. // in all copies or substantial portions of the Software.
  13409. //
  13410. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13411. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13412. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13413. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13414. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13415. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13416. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13417. // a transform stream is a readable/writable stream where you do
  13418. // something with the data. Sometimes it's called a "filter",
  13419. // but that's not a great name for it, since that implies a thing where
  13420. // some bits pass through, and others are simply ignored. (That would
  13421. // be a valid example of a transform, of course.)
  13422. //
  13423. // While the output is causally related to the input, it's not a
  13424. // necessarily symmetric or synchronous transformation. For example,
  13425. // a zlib stream might take multiple plain-text writes(), and then
  13426. // emit a single compressed chunk some time in the future.
  13427. //
  13428. // Here's how this works:
  13429. //
  13430. // The Transform stream has all the aspects of the readable and writable
  13431. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  13432. // internally, and returns false if there's a lot of pending writes
  13433. // buffered up. When you call read(), that calls _read(n) until
  13434. // there's enough pending readable data buffered up.
  13435. //
  13436. // In a transform stream, the written data is placed in a buffer. When
  13437. // _read(n) is called, it transforms the queued up data, calling the
  13438. // buffered _write cb's as it consumes chunks. If consuming a single
  13439. // written chunk would result in multiple output chunks, then the first
  13440. // outputted bit calls the readcb, and subsequent chunks just go into
  13441. // the read buffer, and will cause it to emit 'readable' if necessary.
  13442. //
  13443. // This way, back-pressure is actually determined by the reading side,
  13444. // since _read has to be called to start processing a new chunk. However,
  13445. // a pathological inflate type of transform can cause excessive buffering
  13446. // here. For example, imagine a stream where every byte of input is
  13447. // interpreted as an integer from 0-255, and then results in that many
  13448. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  13449. // 1kb of data being output. In this case, you could write a very small
  13450. // amount of input, and end up with a very large amount of output. In
  13451. // such a pathological inflating mechanism, there'd be no way to tell
  13452. // the system to stop doing the transform. A single 4MB write could
  13453. // cause the system to run out of memory.
  13454. //
  13455. // However, even in such a pathological case, only a single written chunk
  13456. // would be consumed, and then the rest would wait (un-transformed) until
  13457. // the results of the previous transformed chunk were consumed.
  13458. 'use strict';
  13459. module.exports = Transform;
  13460. var Duplex = require('./_stream_duplex');
  13461. /*<replacement>*/
  13462. var util = Object.create(require('core-util-is'));
  13463. util.inherits = require('inherits');
  13464. /*</replacement>*/
  13465. util.inherits(Transform, Duplex);
  13466. function afterTransform(er, data) {
  13467. var ts = this._transformState;
  13468. ts.transforming = false;
  13469. var cb = ts.writecb;
  13470. if (!cb) {
  13471. return this.emit('error', new Error('write callback called multiple times'));
  13472. }
  13473. ts.writechunk = null;
  13474. ts.writecb = null;
  13475. if (data != null) // single equals check for both `null` and `undefined`
  13476. this.push(data);
  13477. cb(er);
  13478. var rs = this._readableState;
  13479. rs.reading = false;
  13480. if (rs.needReadable || rs.length < rs.highWaterMark) {
  13481. this._read(rs.highWaterMark);
  13482. }
  13483. }
  13484. function Transform(options) {
  13485. if (!(this instanceof Transform)) return new Transform(options);
  13486. Duplex.call(this, options);
  13487. this._transformState = {
  13488. afterTransform: afterTransform.bind(this),
  13489. needTransform: false,
  13490. transforming: false,
  13491. writecb: null,
  13492. writechunk: null,
  13493. writeencoding: null
  13494. };
  13495. // start out asking for a readable event once data is transformed.
  13496. this._readableState.needReadable = true;
  13497. // we have implemented the _read method, and done the other things
  13498. // that Readable wants before the first _read call, so unset the
  13499. // sync guard flag.
  13500. this._readableState.sync = false;
  13501. if (options) {
  13502. if (typeof options.transform === 'function') this._transform = options.transform;
  13503. if (typeof options.flush === 'function') this._flush = options.flush;
  13504. }
  13505. // When the writable side finishes, then flush out anything remaining.
  13506. this.on('prefinish', prefinish);
  13507. }
  13508. function prefinish() {
  13509. var _this = this;
  13510. if (typeof this._flush === 'function') {
  13511. this._flush(function (er, data) {
  13512. done(_this, er, data);
  13513. });
  13514. } else {
  13515. done(this, null, null);
  13516. }
  13517. }
  13518. Transform.prototype.push = function (chunk, encoding) {
  13519. this._transformState.needTransform = false;
  13520. return Duplex.prototype.push.call(this, chunk, encoding);
  13521. };
  13522. // This is the part where you do stuff!
  13523. // override this function in implementation classes.
  13524. // 'chunk' is an input chunk.
  13525. //
  13526. // Call `push(newChunk)` to pass along transformed output
  13527. // to the readable side. You may call 'push' zero or more times.
  13528. //
  13529. // Call `cb(err)` when you are done with this chunk. If you pass
  13530. // an error, then that'll put the hurt on the whole operation. If you
  13531. // never call cb(), then you'll never get another chunk.
  13532. Transform.prototype._transform = function (chunk, encoding, cb) {
  13533. throw new Error('_transform() is not implemented');
  13534. };
  13535. Transform.prototype._write = function (chunk, encoding, cb) {
  13536. var ts = this._transformState;
  13537. ts.writecb = cb;
  13538. ts.writechunk = chunk;
  13539. ts.writeencoding = encoding;
  13540. if (!ts.transforming) {
  13541. var rs = this._readableState;
  13542. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  13543. }
  13544. };
  13545. // Doesn't matter what the args are here.
  13546. // _transform does all the work.
  13547. // That we got here means that the readable side wants more data.
  13548. Transform.prototype._read = function (n) {
  13549. var ts = this._transformState;
  13550. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  13551. ts.transforming = true;
  13552. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  13553. } else {
  13554. // mark that we need a transform, so that any data that comes in
  13555. // will get processed, now that we've asked for it.
  13556. ts.needTransform = true;
  13557. }
  13558. };
  13559. Transform.prototype._destroy = function (err, cb) {
  13560. var _this2 = this;
  13561. Duplex.prototype._destroy.call(this, err, function (err2) {
  13562. cb(err2);
  13563. _this2.emit('close');
  13564. });
  13565. };
  13566. function done(stream, er, data) {
  13567. if (er) return stream.emit('error', er);
  13568. if (data != null) // single equals check for both `null` and `undefined`
  13569. stream.push(data);
  13570. // if there's nothing in the write buffer, then that means
  13571. // that nothing more will ever be provided
  13572. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  13573. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  13574. return stream.push(null);
  13575. }
  13576. },{"./_stream_duplex":67,"core-util-is":4,"inherits":9}],71:[function(require,module,exports){
  13577. (function (process,global,setImmediate){
  13578. // Copyright Joyent, Inc. and other Node contributors.
  13579. //
  13580. // Permission is hereby granted, free of charge, to any person obtaining a
  13581. // copy of this software and associated documentation files (the
  13582. // "Software"), to deal in the Software without restriction, including
  13583. // without limitation the rights to use, copy, modify, merge, publish,
  13584. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13585. // persons to whom the Software is furnished to do so, subject to the
  13586. // following conditions:
  13587. //
  13588. // The above copyright notice and this permission notice shall be included
  13589. // in all copies or substantial portions of the Software.
  13590. //
  13591. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13592. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13593. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13594. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13595. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13596. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13597. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13598. // A bit simpler than readable streams.
  13599. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  13600. // the drain event emission and buffering.
  13601. 'use strict';
  13602. /*<replacement>*/
  13603. var pna = require('process-nextick-args');
  13604. /*</replacement>*/
  13605. module.exports = Writable;
  13606. /* <replacement> */
  13607. function WriteReq(chunk, encoding, cb) {
  13608. this.chunk = chunk;
  13609. this.encoding = encoding;
  13610. this.callback = cb;
  13611. this.next = null;
  13612. }
  13613. // It seems a linked list but it is not
  13614. // there will be only 2 of these for each stream
  13615. function CorkedRequest(state) {
  13616. var _this = this;
  13617. this.next = null;
  13618. this.entry = null;
  13619. this.finish = function () {
  13620. onCorkedFinish(_this, state);
  13621. };
  13622. }
  13623. /* </replacement> */
  13624. /*<replacement>*/
  13625. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  13626. /*</replacement>*/
  13627. /*<replacement>*/
  13628. var Duplex;
  13629. /*</replacement>*/
  13630. Writable.WritableState = WritableState;
  13631. /*<replacement>*/
  13632. var util = Object.create(require('core-util-is'));
  13633. util.inherits = require('inherits');
  13634. /*</replacement>*/
  13635. /*<replacement>*/
  13636. var internalUtil = {
  13637. deprecate: require('util-deprecate')
  13638. };
  13639. /*</replacement>*/
  13640. /*<replacement>*/
  13641. var Stream = require('./internal/streams/stream');
  13642. /*</replacement>*/
  13643. /*<replacement>*/
  13644. var Buffer = require('safe-buffer').Buffer;
  13645. var OurUint8Array = global.Uint8Array || function () {};
  13646. function _uint8ArrayToBuffer(chunk) {
  13647. return Buffer.from(chunk);
  13648. }
  13649. function _isUint8Array(obj) {
  13650. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  13651. }
  13652. /*</replacement>*/
  13653. var destroyImpl = require('./internal/streams/destroy');
  13654. util.inherits(Writable, Stream);
  13655. function nop() {}
  13656. function WritableState(options, stream) {
  13657. Duplex = Duplex || require('./_stream_duplex');
  13658. options = options || {};
  13659. // Duplex streams are both readable and writable, but share
  13660. // the same options object.
  13661. // However, some cases require setting options to different
  13662. // values for the readable and the writable sides of the duplex stream.
  13663. // These options can be provided separately as readableXXX and writableXXX.
  13664. var isDuplex = stream instanceof Duplex;
  13665. // object stream flag to indicate whether or not this stream
  13666. // contains buffers or objects.
  13667. this.objectMode = !!options.objectMode;
  13668. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  13669. // the point at which write() starts returning false
  13670. // Note: 0 is a valid value, means that we always return false if
  13671. // the entire buffer is not flushed immediately on write()
  13672. var hwm = options.highWaterMark;
  13673. var writableHwm = options.writableHighWaterMark;
  13674. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  13675. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  13676. // cast to ints.
  13677. this.highWaterMark = Math.floor(this.highWaterMark);
  13678. // if _final has been called
  13679. this.finalCalled = false;
  13680. // drain event flag.
  13681. this.needDrain = false;
  13682. // at the start of calling end()
  13683. this.ending = false;
  13684. // when end() has been called, and returned
  13685. this.ended = false;
  13686. // when 'finish' is emitted
  13687. this.finished = false;
  13688. // has it been destroyed
  13689. this.destroyed = false;
  13690. // should we decode strings into buffers before passing to _write?
  13691. // this is here so that some node-core streams can optimize string
  13692. // handling at a lower level.
  13693. var noDecode = options.decodeStrings === false;
  13694. this.decodeStrings = !noDecode;
  13695. // Crypto is kind of old and crusty. Historically, its default string
  13696. // encoding is 'binary' so we have to make this configurable.
  13697. // Everything else in the universe uses 'utf8', though.
  13698. this.defaultEncoding = options.defaultEncoding || 'utf8';
  13699. // not an actual buffer we keep track of, but a measurement
  13700. // of how much we're waiting to get pushed to some underlying
  13701. // socket or file.
  13702. this.length = 0;
  13703. // a flag to see when we're in the middle of a write.
  13704. this.writing = false;
  13705. // when true all writes will be buffered until .uncork() call
  13706. this.corked = 0;
  13707. // a flag to be able to tell if the onwrite cb is called immediately,
  13708. // or on a later tick. We set this to true at first, because any
  13709. // actions that shouldn't happen until "later" should generally also
  13710. // not happen before the first write call.
  13711. this.sync = true;
  13712. // a flag to know if we're processing previously buffered items, which
  13713. // may call the _write() callback in the same tick, so that we don't
  13714. // end up in an overlapped onwrite situation.
  13715. this.bufferProcessing = false;
  13716. // the callback that's passed to _write(chunk,cb)
  13717. this.onwrite = function (er) {
  13718. onwrite(stream, er);
  13719. };
  13720. // the callback that the user supplies to write(chunk,encoding,cb)
  13721. this.writecb = null;
  13722. // the amount that is being written when _write is called.
  13723. this.writelen = 0;
  13724. this.bufferedRequest = null;
  13725. this.lastBufferedRequest = null;
  13726. // number of pending user-supplied write callbacks
  13727. // this must be 0 before 'finish' can be emitted
  13728. this.pendingcb = 0;
  13729. // emit prefinish if the only thing we're waiting for is _write cbs
  13730. // This is relevant for synchronous Transform streams
  13731. this.prefinished = false;
  13732. // True if the error was already emitted and should not be thrown again
  13733. this.errorEmitted = false;
  13734. // count buffered requests
  13735. this.bufferedRequestCount = 0;
  13736. // allocate the first CorkedRequest, there is always
  13737. // one allocated and free to use, and we maintain at most two
  13738. this.corkedRequestsFree = new CorkedRequest(this);
  13739. }
  13740. WritableState.prototype.getBuffer = function getBuffer() {
  13741. var current = this.bufferedRequest;
  13742. var out = [];
  13743. while (current) {
  13744. out.push(current);
  13745. current = current.next;
  13746. }
  13747. return out;
  13748. };
  13749. (function () {
  13750. try {
  13751. Object.defineProperty(WritableState.prototype, 'buffer', {
  13752. get: internalUtil.deprecate(function () {
  13753. return this.getBuffer();
  13754. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  13755. });
  13756. } catch (_) {}
  13757. })();
  13758. // Test _writableState for inheritance to account for Duplex streams,
  13759. // whose prototype chain only points to Readable.
  13760. var realHasInstance;
  13761. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  13762. realHasInstance = Function.prototype[Symbol.hasInstance];
  13763. Object.defineProperty(Writable, Symbol.hasInstance, {
  13764. value: function (object) {
  13765. if (realHasInstance.call(this, object)) return true;
  13766. if (this !== Writable) return false;
  13767. return object && object._writableState instanceof WritableState;
  13768. }
  13769. });
  13770. } else {
  13771. realHasInstance = function (object) {
  13772. return object instanceof this;
  13773. };
  13774. }
  13775. function Writable(options) {
  13776. Duplex = Duplex || require('./_stream_duplex');
  13777. // Writable ctor is applied to Duplexes, too.
  13778. // `realHasInstance` is necessary because using plain `instanceof`
  13779. // would return false, as no `_writableState` property is attached.
  13780. // Trying to use the custom `instanceof` for Writable here will also break the
  13781. // Node.js LazyTransform implementation, which has a non-trivial getter for
  13782. // `_writableState` that would lead to infinite recursion.
  13783. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  13784. return new Writable(options);
  13785. }
  13786. this._writableState = new WritableState(options, this);
  13787. // legacy.
  13788. this.writable = true;
  13789. if (options) {
  13790. if (typeof options.write === 'function') this._write = options.write;
  13791. if (typeof options.writev === 'function') this._writev = options.writev;
  13792. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  13793. if (typeof options.final === 'function') this._final = options.final;
  13794. }
  13795. Stream.call(this);
  13796. }
  13797. // Otherwise people can pipe Writable streams, which is just wrong.
  13798. Writable.prototype.pipe = function () {
  13799. this.emit('error', new Error('Cannot pipe, not readable'));
  13800. };
  13801. function writeAfterEnd(stream, cb) {
  13802. var er = new Error('write after end');
  13803. // TODO: defer error events consistently everywhere, not just the cb
  13804. stream.emit('error', er);
  13805. pna.nextTick(cb, er);
  13806. }
  13807. // Checks that a user-supplied chunk is valid, especially for the particular
  13808. // mode the stream is in. Currently this means that `null` is never accepted
  13809. // and undefined/non-string values are only allowed in object mode.
  13810. function validChunk(stream, state, chunk, cb) {
  13811. var valid = true;
  13812. var er = false;
  13813. if (chunk === null) {
  13814. er = new TypeError('May not write null values to stream');
  13815. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  13816. er = new TypeError('Invalid non-string/buffer chunk');
  13817. }
  13818. if (er) {
  13819. stream.emit('error', er);
  13820. pna.nextTick(cb, er);
  13821. valid = false;
  13822. }
  13823. return valid;
  13824. }
  13825. Writable.prototype.write = function (chunk, encoding, cb) {
  13826. var state = this._writableState;
  13827. var ret = false;
  13828. var isBuf = !state.objectMode && _isUint8Array(chunk);
  13829. if (isBuf && !Buffer.isBuffer(chunk)) {
  13830. chunk = _uint8ArrayToBuffer(chunk);
  13831. }
  13832. if (typeof encoding === 'function') {
  13833. cb = encoding;
  13834. encoding = null;
  13835. }
  13836. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  13837. if (typeof cb !== 'function') cb = nop;
  13838. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  13839. state.pendingcb++;
  13840. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  13841. }
  13842. return ret;
  13843. };
  13844. Writable.prototype.cork = function () {
  13845. var state = this._writableState;
  13846. state.corked++;
  13847. };
  13848. Writable.prototype.uncork = function () {
  13849. var state = this._writableState;
  13850. if (state.corked) {
  13851. state.corked--;
  13852. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  13853. }
  13854. };
  13855. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  13856. // node::ParseEncoding() requires lower case.
  13857. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  13858. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  13859. this._writableState.defaultEncoding = encoding;
  13860. return this;
  13861. };
  13862. function decodeChunk(state, chunk, encoding) {
  13863. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  13864. chunk = Buffer.from(chunk, encoding);
  13865. }
  13866. return chunk;
  13867. }
  13868. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  13869. // making it explicit this property is not enumerable
  13870. // because otherwise some prototype manipulation in
  13871. // userland will fail
  13872. enumerable: false,
  13873. get: function () {
  13874. return this._writableState.highWaterMark;
  13875. }
  13876. });
  13877. // if we're already writing something, then just put this
  13878. // in the queue, and wait our turn. Otherwise, call _write
  13879. // If we return false, then we need a drain event, so set that flag.
  13880. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  13881. if (!isBuf) {
  13882. var newChunk = decodeChunk(state, chunk, encoding);
  13883. if (chunk !== newChunk) {
  13884. isBuf = true;
  13885. encoding = 'buffer';
  13886. chunk = newChunk;
  13887. }
  13888. }
  13889. var len = state.objectMode ? 1 : chunk.length;
  13890. state.length += len;
  13891. var ret = state.length < state.highWaterMark;
  13892. // we must ensure that previous needDrain will not be reset to false.
  13893. if (!ret) state.needDrain = true;
  13894. if (state.writing || state.corked) {
  13895. var last = state.lastBufferedRequest;
  13896. state.lastBufferedRequest = {
  13897. chunk: chunk,
  13898. encoding: encoding,
  13899. isBuf: isBuf,
  13900. callback: cb,
  13901. next: null
  13902. };
  13903. if (last) {
  13904. last.next = state.lastBufferedRequest;
  13905. } else {
  13906. state.bufferedRequest = state.lastBufferedRequest;
  13907. }
  13908. state.bufferedRequestCount += 1;
  13909. } else {
  13910. doWrite(stream, state, false, len, chunk, encoding, cb);
  13911. }
  13912. return ret;
  13913. }
  13914. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  13915. state.writelen = len;
  13916. state.writecb = cb;
  13917. state.writing = true;
  13918. state.sync = true;
  13919. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  13920. state.sync = false;
  13921. }
  13922. function onwriteError(stream, state, sync, er, cb) {
  13923. --state.pendingcb;
  13924. if (sync) {
  13925. // defer the callback if we are being called synchronously
  13926. // to avoid piling up things on the stack
  13927. pna.nextTick(cb, er);
  13928. // this can emit finish, and it will always happen
  13929. // after error
  13930. pna.nextTick(finishMaybe, stream, state);
  13931. stream._writableState.errorEmitted = true;
  13932. stream.emit('error', er);
  13933. } else {
  13934. // the caller expect this to happen before if
  13935. // it is async
  13936. cb(er);
  13937. stream._writableState.errorEmitted = true;
  13938. stream.emit('error', er);
  13939. // this can emit finish, but finish must
  13940. // always follow error
  13941. finishMaybe(stream, state);
  13942. }
  13943. }
  13944. function onwriteStateUpdate(state) {
  13945. state.writing = false;
  13946. state.writecb = null;
  13947. state.length -= state.writelen;
  13948. state.writelen = 0;
  13949. }
  13950. function onwrite(stream, er) {
  13951. var state = stream._writableState;
  13952. var sync = state.sync;
  13953. var cb = state.writecb;
  13954. onwriteStateUpdate(state);
  13955. if (er) onwriteError(stream, state, sync, er, cb);else {
  13956. // Check if we're actually ready to finish, but don't emit yet
  13957. var finished = needFinish(state);
  13958. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  13959. clearBuffer(stream, state);
  13960. }
  13961. if (sync) {
  13962. /*<replacement>*/
  13963. asyncWrite(afterWrite, stream, state, finished, cb);
  13964. /*</replacement>*/
  13965. } else {
  13966. afterWrite(stream, state, finished, cb);
  13967. }
  13968. }
  13969. }
  13970. function afterWrite(stream, state, finished, cb) {
  13971. if (!finished) onwriteDrain(stream, state);
  13972. state.pendingcb--;
  13973. cb();
  13974. finishMaybe(stream, state);
  13975. }
  13976. // Must force callback to be called on nextTick, so that we don't
  13977. // emit 'drain' before the write() consumer gets the 'false' return
  13978. // value, and has a chance to attach a 'drain' listener.
  13979. function onwriteDrain(stream, state) {
  13980. if (state.length === 0 && state.needDrain) {
  13981. state.needDrain = false;
  13982. stream.emit('drain');
  13983. }
  13984. }
  13985. // if there's something in the buffer waiting, then process it
  13986. function clearBuffer(stream, state) {
  13987. state.bufferProcessing = true;
  13988. var entry = state.bufferedRequest;
  13989. if (stream._writev && entry && entry.next) {
  13990. // Fast case, write everything using _writev()
  13991. var l = state.bufferedRequestCount;
  13992. var buffer = new Array(l);
  13993. var holder = state.corkedRequestsFree;
  13994. holder.entry = entry;
  13995. var count = 0;
  13996. var allBuffers = true;
  13997. while (entry) {
  13998. buffer[count] = entry;
  13999. if (!entry.isBuf) allBuffers = false;
  14000. entry = entry.next;
  14001. count += 1;
  14002. }
  14003. buffer.allBuffers = allBuffers;
  14004. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  14005. // doWrite is almost always async, defer these to save a bit of time
  14006. // as the hot path ends with doWrite
  14007. state.pendingcb++;
  14008. state.lastBufferedRequest = null;
  14009. if (holder.next) {
  14010. state.corkedRequestsFree = holder.next;
  14011. holder.next = null;
  14012. } else {
  14013. state.corkedRequestsFree = new CorkedRequest(state);
  14014. }
  14015. state.bufferedRequestCount = 0;
  14016. } else {
  14017. // Slow case, write chunks one-by-one
  14018. while (entry) {
  14019. var chunk = entry.chunk;
  14020. var encoding = entry.encoding;
  14021. var cb = entry.callback;
  14022. var len = state.objectMode ? 1 : chunk.length;
  14023. doWrite(stream, state, false, len, chunk, encoding, cb);
  14024. entry = entry.next;
  14025. state.bufferedRequestCount--;
  14026. // if we didn't call the onwrite immediately, then
  14027. // it means that we need to wait until it does.
  14028. // also, that means that the chunk and cb are currently
  14029. // being processed, so move the buffer counter past them.
  14030. if (state.writing) {
  14031. break;
  14032. }
  14033. }
  14034. if (entry === null) state.lastBufferedRequest = null;
  14035. }
  14036. state.bufferedRequest = entry;
  14037. state.bufferProcessing = false;
  14038. }
  14039. Writable.prototype._write = function (chunk, encoding, cb) {
  14040. cb(new Error('_write() is not implemented'));
  14041. };
  14042. Writable.prototype._writev = null;
  14043. Writable.prototype.end = function (chunk, encoding, cb) {
  14044. var state = this._writableState;
  14045. if (typeof chunk === 'function') {
  14046. cb = chunk;
  14047. chunk = null;
  14048. encoding = null;
  14049. } else if (typeof encoding === 'function') {
  14050. cb = encoding;
  14051. encoding = null;
  14052. }
  14053. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  14054. // .end() fully uncorks
  14055. if (state.corked) {
  14056. state.corked = 1;
  14057. this.uncork();
  14058. }
  14059. // ignore unnecessary end() calls.
  14060. if (!state.ending && !state.finished) endWritable(this, state, cb);
  14061. };
  14062. function needFinish(state) {
  14063. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  14064. }
  14065. function callFinal(stream, state) {
  14066. stream._final(function (err) {
  14067. state.pendingcb--;
  14068. if (err) {
  14069. stream.emit('error', err);
  14070. }
  14071. state.prefinished = true;
  14072. stream.emit('prefinish');
  14073. finishMaybe(stream, state);
  14074. });
  14075. }
  14076. function prefinish(stream, state) {
  14077. if (!state.prefinished && !state.finalCalled) {
  14078. if (typeof stream._final === 'function') {
  14079. state.pendingcb++;
  14080. state.finalCalled = true;
  14081. pna.nextTick(callFinal, stream, state);
  14082. } else {
  14083. state.prefinished = true;
  14084. stream.emit('prefinish');
  14085. }
  14086. }
  14087. }
  14088. function finishMaybe(stream, state) {
  14089. var need = needFinish(state);
  14090. if (need) {
  14091. prefinish(stream, state);
  14092. if (state.pendingcb === 0) {
  14093. state.finished = true;
  14094. stream.emit('finish');
  14095. }
  14096. }
  14097. return need;
  14098. }
  14099. function endWritable(stream, state, cb) {
  14100. state.ending = true;
  14101. finishMaybe(stream, state);
  14102. if (cb) {
  14103. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  14104. }
  14105. state.ended = true;
  14106. stream.writable = false;
  14107. }
  14108. function onCorkedFinish(corkReq, state, err) {
  14109. var entry = corkReq.entry;
  14110. corkReq.entry = null;
  14111. while (entry) {
  14112. var cb = entry.callback;
  14113. state.pendingcb--;
  14114. cb(err);
  14115. entry = entry.next;
  14116. }
  14117. if (state.corkedRequestsFree) {
  14118. state.corkedRequestsFree.next = corkReq;
  14119. } else {
  14120. state.corkedRequestsFree = corkReq;
  14121. }
  14122. }
  14123. Object.defineProperty(Writable.prototype, 'destroyed', {
  14124. get: function () {
  14125. if (this._writableState === undefined) {
  14126. return false;
  14127. }
  14128. return this._writableState.destroyed;
  14129. },
  14130. set: function (value) {
  14131. // we ignore the value if the stream
  14132. // has not been initialized yet
  14133. if (!this._writableState) {
  14134. return;
  14135. }
  14136. // backward compatibility, the user is explicitly
  14137. // managing destroyed
  14138. this._writableState.destroyed = value;
  14139. }
  14140. });
  14141. Writable.prototype.destroy = destroyImpl.destroy;
  14142. Writable.prototype._undestroy = destroyImpl.undestroy;
  14143. Writable.prototype._destroy = function (err, cb) {
  14144. this.end();
  14145. cb(err);
  14146. };
  14147. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  14148. },{"./_stream_duplex":67,"./internal/streams/destroy":73,"./internal/streams/stream":74,"_process":65,"core-util-is":4,"inherits":9,"process-nextick-args":64,"safe-buffer":79,"timers":83,"util-deprecate":84}],72:[function(require,module,exports){
  14149. 'use strict';
  14150. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14151. var Buffer = require('safe-buffer').Buffer;
  14152. var util = require('util');
  14153. function copyBuffer(src, target, offset) {
  14154. src.copy(target, offset);
  14155. }
  14156. module.exports = function () {
  14157. function BufferList() {
  14158. _classCallCheck(this, BufferList);
  14159. this.head = null;
  14160. this.tail = null;
  14161. this.length = 0;
  14162. }
  14163. BufferList.prototype.push = function push(v) {
  14164. var entry = { data: v, next: null };
  14165. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  14166. this.tail = entry;
  14167. ++this.length;
  14168. };
  14169. BufferList.prototype.unshift = function unshift(v) {
  14170. var entry = { data: v, next: this.head };
  14171. if (this.length === 0) this.tail = entry;
  14172. this.head = entry;
  14173. ++this.length;
  14174. };
  14175. BufferList.prototype.shift = function shift() {
  14176. if (this.length === 0) return;
  14177. var ret = this.head.data;
  14178. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  14179. --this.length;
  14180. return ret;
  14181. };
  14182. BufferList.prototype.clear = function clear() {
  14183. this.head = this.tail = null;
  14184. this.length = 0;
  14185. };
  14186. BufferList.prototype.join = function join(s) {
  14187. if (this.length === 0) return '';
  14188. var p = this.head;
  14189. var ret = '' + p.data;
  14190. while (p = p.next) {
  14191. ret += s + p.data;
  14192. }return ret;
  14193. };
  14194. BufferList.prototype.concat = function concat(n) {
  14195. if (this.length === 0) return Buffer.alloc(0);
  14196. if (this.length === 1) return this.head.data;
  14197. var ret = Buffer.allocUnsafe(n >>> 0);
  14198. var p = this.head;
  14199. var i = 0;
  14200. while (p) {
  14201. copyBuffer(p.data, ret, i);
  14202. i += p.data.length;
  14203. p = p.next;
  14204. }
  14205. return ret;
  14206. };
  14207. return BufferList;
  14208. }();
  14209. if (util && util.inspect && util.inspect.custom) {
  14210. module.exports.prototype[util.inspect.custom] = function () {
  14211. var obj = util.inspect({ length: this.length });
  14212. return this.constructor.name + ' ' + obj;
  14213. };
  14214. }
  14215. },{"safe-buffer":79,"util":2}],73:[function(require,module,exports){
  14216. 'use strict';
  14217. /*<replacement>*/
  14218. var pna = require('process-nextick-args');
  14219. /*</replacement>*/
  14220. // undocumented cb() API, needed for core, not for public API
  14221. function destroy(err, cb) {
  14222. var _this = this;
  14223. var readableDestroyed = this._readableState && this._readableState.destroyed;
  14224. var writableDestroyed = this._writableState && this._writableState.destroyed;
  14225. if (readableDestroyed || writableDestroyed) {
  14226. if (cb) {
  14227. cb(err);
  14228. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  14229. pna.nextTick(emitErrorNT, this, err);
  14230. }
  14231. return this;
  14232. }
  14233. // we set destroyed to true before firing error callbacks in order
  14234. // to make it re-entrance safe in case destroy() is called within callbacks
  14235. if (this._readableState) {
  14236. this._readableState.destroyed = true;
  14237. }
  14238. // if this is a duplex stream mark the writable part as destroyed as well
  14239. if (this._writableState) {
  14240. this._writableState.destroyed = true;
  14241. }
  14242. this._destroy(err || null, function (err) {
  14243. if (!cb && err) {
  14244. pna.nextTick(emitErrorNT, _this, err);
  14245. if (_this._writableState) {
  14246. _this._writableState.errorEmitted = true;
  14247. }
  14248. } else if (cb) {
  14249. cb(err);
  14250. }
  14251. });
  14252. return this;
  14253. }
  14254. function undestroy() {
  14255. if (this._readableState) {
  14256. this._readableState.destroyed = false;
  14257. this._readableState.reading = false;
  14258. this._readableState.ended = false;
  14259. this._readableState.endEmitted = false;
  14260. }
  14261. if (this._writableState) {
  14262. this._writableState.destroyed = false;
  14263. this._writableState.ended = false;
  14264. this._writableState.ending = false;
  14265. this._writableState.finished = false;
  14266. this._writableState.errorEmitted = false;
  14267. }
  14268. }
  14269. function emitErrorNT(self, err) {
  14270. self.emit('error', err);
  14271. }
  14272. module.exports = {
  14273. destroy: destroy,
  14274. undestroy: undestroy
  14275. };
  14276. },{"process-nextick-args":64}],74:[function(require,module,exports){
  14277. module.exports = require('events').EventEmitter;
  14278. },{"events":6}],75:[function(require,module,exports){
  14279. module.exports = require('./readable').PassThrough
  14280. },{"./readable":76}],76:[function(require,module,exports){
  14281. exports = module.exports = require('./lib/_stream_readable.js');
  14282. exports.Stream = exports;
  14283. exports.Readable = exports;
  14284. exports.Writable = require('./lib/_stream_writable.js');
  14285. exports.Duplex = require('./lib/_stream_duplex.js');
  14286. exports.Transform = require('./lib/_stream_transform.js');
  14287. exports.PassThrough = require('./lib/_stream_passthrough.js');
  14288. },{"./lib/_stream_duplex.js":67,"./lib/_stream_passthrough.js":68,"./lib/_stream_readable.js":69,"./lib/_stream_transform.js":70,"./lib/_stream_writable.js":71}],77:[function(require,module,exports){
  14289. module.exports = require('./readable').Transform
  14290. },{"./readable":76}],78:[function(require,module,exports){
  14291. module.exports = require('./lib/_stream_writable.js');
  14292. },{"./lib/_stream_writable.js":71}],79:[function(require,module,exports){
  14293. /* eslint-disable node/no-deprecated-api */
  14294. var buffer = require('buffer')
  14295. var Buffer = buffer.Buffer
  14296. // alternative to using Object.keys for old browsers
  14297. function copyProps (src, dst) {
  14298. for (var key in src) {
  14299. dst[key] = src[key]
  14300. }
  14301. }
  14302. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  14303. module.exports = buffer
  14304. } else {
  14305. // Copy properties from require('buffer')
  14306. copyProps(buffer, exports)
  14307. exports.Buffer = SafeBuffer
  14308. }
  14309. function SafeBuffer (arg, encodingOrOffset, length) {
  14310. return Buffer(arg, encodingOrOffset, length)
  14311. }
  14312. // Copy static methods from Buffer
  14313. copyProps(Buffer, SafeBuffer)
  14314. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  14315. if (typeof arg === 'number') {
  14316. throw new TypeError('Argument must not be a number')
  14317. }
  14318. return Buffer(arg, encodingOrOffset, length)
  14319. }
  14320. SafeBuffer.alloc = function (size, fill, encoding) {
  14321. if (typeof size !== 'number') {
  14322. throw new TypeError('Argument must be a number')
  14323. }
  14324. var buf = Buffer(size)
  14325. if (fill !== undefined) {
  14326. if (typeof encoding === 'string') {
  14327. buf.fill(fill, encoding)
  14328. } else {
  14329. buf.fill(fill)
  14330. }
  14331. } else {
  14332. buf.fill(0)
  14333. }
  14334. return buf
  14335. }
  14336. SafeBuffer.allocUnsafe = function (size) {
  14337. if (typeof size !== 'number') {
  14338. throw new TypeError('Argument must be a number')
  14339. }
  14340. return Buffer(size)
  14341. }
  14342. SafeBuffer.allocUnsafeSlow = function (size) {
  14343. if (typeof size !== 'number') {
  14344. throw new TypeError('Argument must be a number')
  14345. }
  14346. return buffer.SlowBuffer(size)
  14347. }
  14348. },{"buffer":3}],80:[function(require,module,exports){
  14349. (function (setImmediate){
  14350. 'use strict';
  14351. module.exports = typeof setImmediate === 'function' ? setImmediate :
  14352. function setImmediate() {
  14353. var args = [].slice.apply(arguments);
  14354. args.splice(1, 0, 0);
  14355. setTimeout.apply(null, args);
  14356. };
  14357. }).call(this,require("timers").setImmediate)
  14358. },{"timers":83}],81:[function(require,module,exports){
  14359. // Copyright Joyent, Inc. and other Node contributors.
  14360. //
  14361. // Permission is hereby granted, free of charge, to any person obtaining a
  14362. // copy of this software and associated documentation files (the
  14363. // "Software"), to deal in the Software without restriction, including
  14364. // without limitation the rights to use, copy, modify, merge, publish,
  14365. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14366. // persons to whom the Software is furnished to do so, subject to the
  14367. // following conditions:
  14368. //
  14369. // The above copyright notice and this permission notice shall be included
  14370. // in all copies or substantial portions of the Software.
  14371. //
  14372. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14373. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14374. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14375. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14376. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14377. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14378. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14379. module.exports = Stream;
  14380. var EE = require('events').EventEmitter;
  14381. var inherits = require('inherits');
  14382. inherits(Stream, EE);
  14383. Stream.Readable = require('readable-stream/readable.js');
  14384. Stream.Writable = require('readable-stream/writable.js');
  14385. Stream.Duplex = require('readable-stream/duplex.js');
  14386. Stream.Transform = require('readable-stream/transform.js');
  14387. Stream.PassThrough = require('readable-stream/passthrough.js');
  14388. // Backwards-compat with node 0.4.x
  14389. Stream.Stream = Stream;
  14390. // old-style streams. Note that the pipe method (the only relevant
  14391. // part of this class) is overridden in the Readable class.
  14392. function Stream() {
  14393. EE.call(this);
  14394. }
  14395. Stream.prototype.pipe = function(dest, options) {
  14396. var source = this;
  14397. function ondata(chunk) {
  14398. if (dest.writable) {
  14399. if (false === dest.write(chunk) && source.pause) {
  14400. source.pause();
  14401. }
  14402. }
  14403. }
  14404. source.on('data', ondata);
  14405. function ondrain() {
  14406. if (source.readable && source.resume) {
  14407. source.resume();
  14408. }
  14409. }
  14410. dest.on('drain', ondrain);
  14411. // If the 'end' option is not supplied, dest.end() will be called when
  14412. // source gets the 'end' or 'close' events. Only dest.end() once.
  14413. if (!dest._isStdio && (!options || options.end !== false)) {
  14414. source.on('end', onend);
  14415. source.on('close', onclose);
  14416. }
  14417. var didOnEnd = false;
  14418. function onend() {
  14419. if (didOnEnd) return;
  14420. didOnEnd = true;
  14421. dest.end();
  14422. }
  14423. function onclose() {
  14424. if (didOnEnd) return;
  14425. didOnEnd = true;
  14426. if (typeof dest.destroy === 'function') dest.destroy();
  14427. }
  14428. // don't leave dangling pipes when there are errors.
  14429. function onerror(er) {
  14430. cleanup();
  14431. if (EE.listenerCount(this, 'error') === 0) {
  14432. throw er; // Unhandled stream error in pipe.
  14433. }
  14434. }
  14435. source.on('error', onerror);
  14436. dest.on('error', onerror);
  14437. // remove all the event listeners that were added.
  14438. function cleanup() {
  14439. source.removeListener('data', ondata);
  14440. dest.removeListener('drain', ondrain);
  14441. source.removeListener('end', onend);
  14442. source.removeListener('close', onclose);
  14443. source.removeListener('error', onerror);
  14444. dest.removeListener('error', onerror);
  14445. source.removeListener('end', cleanup);
  14446. source.removeListener('close', cleanup);
  14447. dest.removeListener('close', cleanup);
  14448. }
  14449. source.on('end', cleanup);
  14450. source.on('close', cleanup);
  14451. dest.on('close', cleanup);
  14452. dest.emit('pipe', source);
  14453. // Allow for unix-like usage: A.pipe(B).pipe(C)
  14454. return dest;
  14455. };
  14456. },{"events":6,"inherits":9,"readable-stream/duplex.js":66,"readable-stream/passthrough.js":75,"readable-stream/readable.js":76,"readable-stream/transform.js":77,"readable-stream/writable.js":78}],82:[function(require,module,exports){
  14457. // Copyright Joyent, Inc. and other Node contributors.
  14458. //
  14459. // Permission is hereby granted, free of charge, to any person obtaining a
  14460. // copy of this software and associated documentation files (the
  14461. // "Software"), to deal in the Software without restriction, including
  14462. // without limitation the rights to use, copy, modify, merge, publish,
  14463. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14464. // persons to whom the Software is furnished to do so, subject to the
  14465. // following conditions:
  14466. //
  14467. // The above copyright notice and this permission notice shall be included
  14468. // in all copies or substantial portions of the Software.
  14469. //
  14470. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14471. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14472. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14473. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14474. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14475. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14476. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14477. 'use strict';
  14478. /*<replacement>*/
  14479. var Buffer = require('safe-buffer').Buffer;
  14480. /*</replacement>*/
  14481. var isEncoding = Buffer.isEncoding || function (encoding) {
  14482. encoding = '' + encoding;
  14483. switch (encoding && encoding.toLowerCase()) {
  14484. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  14485. return true;
  14486. default:
  14487. return false;
  14488. }
  14489. };
  14490. function _normalizeEncoding(enc) {
  14491. if (!enc) return 'utf8';
  14492. var retried;
  14493. while (true) {
  14494. switch (enc) {
  14495. case 'utf8':
  14496. case 'utf-8':
  14497. return 'utf8';
  14498. case 'ucs2':
  14499. case 'ucs-2':
  14500. case 'utf16le':
  14501. case 'utf-16le':
  14502. return 'utf16le';
  14503. case 'latin1':
  14504. case 'binary':
  14505. return 'latin1';
  14506. case 'base64':
  14507. case 'ascii':
  14508. case 'hex':
  14509. return enc;
  14510. default:
  14511. if (retried) return; // undefined
  14512. enc = ('' + enc).toLowerCase();
  14513. retried = true;
  14514. }
  14515. }
  14516. };
  14517. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  14518. // modules monkey-patch it to support additional encodings
  14519. function normalizeEncoding(enc) {
  14520. var nenc = _normalizeEncoding(enc);
  14521. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  14522. return nenc || enc;
  14523. }
  14524. // StringDecoder provides an interface for efficiently splitting a series of
  14525. // buffers into a series of JS strings without breaking apart multi-byte
  14526. // characters.
  14527. exports.StringDecoder = StringDecoder;
  14528. function StringDecoder(encoding) {
  14529. this.encoding = normalizeEncoding(encoding);
  14530. var nb;
  14531. switch (this.encoding) {
  14532. case 'utf16le':
  14533. this.text = utf16Text;
  14534. this.end = utf16End;
  14535. nb = 4;
  14536. break;
  14537. case 'utf8':
  14538. this.fillLast = utf8FillLast;
  14539. nb = 4;
  14540. break;
  14541. case 'base64':
  14542. this.text = base64Text;
  14543. this.end = base64End;
  14544. nb = 3;
  14545. break;
  14546. default:
  14547. this.write = simpleWrite;
  14548. this.end = simpleEnd;
  14549. return;
  14550. }
  14551. this.lastNeed = 0;
  14552. this.lastTotal = 0;
  14553. this.lastChar = Buffer.allocUnsafe(nb);
  14554. }
  14555. StringDecoder.prototype.write = function (buf) {
  14556. if (buf.length === 0) return '';
  14557. var r;
  14558. var i;
  14559. if (this.lastNeed) {
  14560. r = this.fillLast(buf);
  14561. if (r === undefined) return '';
  14562. i = this.lastNeed;
  14563. this.lastNeed = 0;
  14564. } else {
  14565. i = 0;
  14566. }
  14567. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  14568. return r || '';
  14569. };
  14570. StringDecoder.prototype.end = utf8End;
  14571. // Returns only complete characters in a Buffer
  14572. StringDecoder.prototype.text = utf8Text;
  14573. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  14574. StringDecoder.prototype.fillLast = function (buf) {
  14575. if (this.lastNeed <= buf.length) {
  14576. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  14577. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  14578. }
  14579. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  14580. this.lastNeed -= buf.length;
  14581. };
  14582. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  14583. // continuation byte. If an invalid byte is detected, -2 is returned.
  14584. function utf8CheckByte(byte) {
  14585. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  14586. return byte >> 6 === 0x02 ? -1 : -2;
  14587. }
  14588. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  14589. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  14590. // needed to complete the UTF-8 character (if applicable) are returned.
  14591. function utf8CheckIncomplete(self, buf, i) {
  14592. var j = buf.length - 1;
  14593. if (j < i) return 0;
  14594. var nb = utf8CheckByte(buf[j]);
  14595. if (nb >= 0) {
  14596. if (nb > 0) self.lastNeed = nb - 1;
  14597. return nb;
  14598. }
  14599. if (--j < i || nb === -2) return 0;
  14600. nb = utf8CheckByte(buf[j]);
  14601. if (nb >= 0) {
  14602. if (nb > 0) self.lastNeed = nb - 2;
  14603. return nb;
  14604. }
  14605. if (--j < i || nb === -2) return 0;
  14606. nb = utf8CheckByte(buf[j]);
  14607. if (nb >= 0) {
  14608. if (nb > 0) {
  14609. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  14610. }
  14611. return nb;
  14612. }
  14613. return 0;
  14614. }
  14615. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  14616. // needed or are available. If we see a non-continuation byte where we expect
  14617. // one, we "replace" the validated continuation bytes we've seen so far with
  14618. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  14619. // behavior. The continuation byte check is included three times in the case
  14620. // where all of the continuation bytes for a character exist in the same buffer.
  14621. // It is also done this way as a slight performance increase instead of using a
  14622. // loop.
  14623. function utf8CheckExtraBytes(self, buf, p) {
  14624. if ((buf[0] & 0xC0) !== 0x80) {
  14625. self.lastNeed = 0;
  14626. return '\ufffd';
  14627. }
  14628. if (self.lastNeed > 1 && buf.length > 1) {
  14629. if ((buf[1] & 0xC0) !== 0x80) {
  14630. self.lastNeed = 1;
  14631. return '\ufffd';
  14632. }
  14633. if (self.lastNeed > 2 && buf.length > 2) {
  14634. if ((buf[2] & 0xC0) !== 0x80) {
  14635. self.lastNeed = 2;
  14636. return '\ufffd';
  14637. }
  14638. }
  14639. }
  14640. }
  14641. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  14642. function utf8FillLast(buf) {
  14643. var p = this.lastTotal - this.lastNeed;
  14644. var r = utf8CheckExtraBytes(this, buf, p);
  14645. if (r !== undefined) return r;
  14646. if (this.lastNeed <= buf.length) {
  14647. buf.copy(this.lastChar, p, 0, this.lastNeed);
  14648. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  14649. }
  14650. buf.copy(this.lastChar, p, 0, buf.length);
  14651. this.lastNeed -= buf.length;
  14652. }
  14653. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  14654. // partial character, the character's bytes are buffered until the required
  14655. // number of bytes are available.
  14656. function utf8Text(buf, i) {
  14657. var total = utf8CheckIncomplete(this, buf, i);
  14658. if (!this.lastNeed) return buf.toString('utf8', i);
  14659. this.lastTotal = total;
  14660. var end = buf.length - (total - this.lastNeed);
  14661. buf.copy(this.lastChar, 0, end);
  14662. return buf.toString('utf8', i, end);
  14663. }
  14664. // For UTF-8, a replacement character is added when ending on a partial
  14665. // character.
  14666. function utf8End(buf) {
  14667. var r = buf && buf.length ? this.write(buf) : '';
  14668. if (this.lastNeed) return r + '\ufffd';
  14669. return r;
  14670. }
  14671. // UTF-16LE typically needs two bytes per character, but even if we have an even
  14672. // number of bytes available, we need to check if we end on a leading/high
  14673. // surrogate. In that case, we need to wait for the next two bytes in order to
  14674. // decode the last character properly.
  14675. function utf16Text(buf, i) {
  14676. if ((buf.length - i) % 2 === 0) {
  14677. var r = buf.toString('utf16le', i);
  14678. if (r) {
  14679. var c = r.charCodeAt(r.length - 1);
  14680. if (c >= 0xD800 && c <= 0xDBFF) {
  14681. this.lastNeed = 2;
  14682. this.lastTotal = 4;
  14683. this.lastChar[0] = buf[buf.length - 2];
  14684. this.lastChar[1] = buf[buf.length - 1];
  14685. return r.slice(0, -1);
  14686. }
  14687. }
  14688. return r;
  14689. }
  14690. this.lastNeed = 1;
  14691. this.lastTotal = 2;
  14692. this.lastChar[0] = buf[buf.length - 1];
  14693. return buf.toString('utf16le', i, buf.length - 1);
  14694. }
  14695. // For UTF-16LE we do not explicitly append special replacement characters if we
  14696. // end on a partial character, we simply let v8 handle that.
  14697. function utf16End(buf) {
  14698. var r = buf && buf.length ? this.write(buf) : '';
  14699. if (this.lastNeed) {
  14700. var end = this.lastTotal - this.lastNeed;
  14701. return r + this.lastChar.toString('utf16le', 0, end);
  14702. }
  14703. return r;
  14704. }
  14705. function base64Text(buf, i) {
  14706. var n = (buf.length - i) % 3;
  14707. if (n === 0) return buf.toString('base64', i);
  14708. this.lastNeed = 3 - n;
  14709. this.lastTotal = 3;
  14710. if (n === 1) {
  14711. this.lastChar[0] = buf[buf.length - 1];
  14712. } else {
  14713. this.lastChar[0] = buf[buf.length - 2];
  14714. this.lastChar[1] = buf[buf.length - 1];
  14715. }
  14716. return buf.toString('base64', i, buf.length - n);
  14717. }
  14718. function base64End(buf) {
  14719. var r = buf && buf.length ? this.write(buf) : '';
  14720. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  14721. return r;
  14722. }
  14723. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  14724. function simpleWrite(buf) {
  14725. return buf.toString(this.encoding);
  14726. }
  14727. function simpleEnd(buf) {
  14728. return buf && buf.length ? this.write(buf) : '';
  14729. }
  14730. },{"safe-buffer":79}],83:[function(require,module,exports){
  14731. (function (setImmediate,clearImmediate){
  14732. var nextTick = require('process/browser.js').nextTick;
  14733. var apply = Function.prototype.apply;
  14734. var slice = Array.prototype.slice;
  14735. var immediateIds = {};
  14736. var nextImmediateId = 0;
  14737. // DOM APIs, for completeness
  14738. exports.setTimeout = function() {
  14739. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  14740. };
  14741. exports.setInterval = function() {
  14742. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  14743. };
  14744. exports.clearTimeout =
  14745. exports.clearInterval = function(timeout) { timeout.close(); };
  14746. function Timeout(id, clearFn) {
  14747. this._id = id;
  14748. this._clearFn = clearFn;
  14749. }
  14750. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  14751. Timeout.prototype.close = function() {
  14752. this._clearFn.call(window, this._id);
  14753. };
  14754. // Does not start the time, just sets up the members needed.
  14755. exports.enroll = function(item, msecs) {
  14756. clearTimeout(item._idleTimeoutId);
  14757. item._idleTimeout = msecs;
  14758. };
  14759. exports.unenroll = function(item) {
  14760. clearTimeout(item._idleTimeoutId);
  14761. item._idleTimeout = -1;
  14762. };
  14763. exports._unrefActive = exports.active = function(item) {
  14764. clearTimeout(item._idleTimeoutId);
  14765. var msecs = item._idleTimeout;
  14766. if (msecs >= 0) {
  14767. item._idleTimeoutId = setTimeout(function onTimeout() {
  14768. if (item._onTimeout)
  14769. item._onTimeout();
  14770. }, msecs);
  14771. }
  14772. };
  14773. // That's not how node.js implements it but the exposed api is the same.
  14774. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  14775. var id = nextImmediateId++;
  14776. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  14777. immediateIds[id] = true;
  14778. nextTick(function onNextTick() {
  14779. if (immediateIds[id]) {
  14780. // fn.call() is faster so we optimize for the common use-case
  14781. // @see http://jsperf.com/call-apply-segu
  14782. if (args) {
  14783. fn.apply(null, args);
  14784. } else {
  14785. fn.call(null);
  14786. }
  14787. // Prevent ids from leaking
  14788. exports.clearImmediate(id);
  14789. }
  14790. });
  14791. return id;
  14792. };
  14793. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  14794. delete immediateIds[id];
  14795. };
  14796. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  14797. },{"process/browser.js":65,"timers":83}],84:[function(require,module,exports){
  14798. (function (global){
  14799. /**
  14800. * Module exports.
  14801. */
  14802. module.exports = deprecate;
  14803. /**
  14804. * Mark that a method should not be used.
  14805. * Returns a modified function which warns once by default.
  14806. *
  14807. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  14808. *
  14809. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  14810. * will throw an Error when invoked.
  14811. *
  14812. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  14813. * will invoke `console.trace()` instead of `console.error()`.
  14814. *
  14815. * @param {Function} fn - the function to deprecate
  14816. * @param {String} msg - the string to print to the console when `fn` is invoked
  14817. * @returns {Function} a new "deprecated" version of `fn`
  14818. * @api public
  14819. */
  14820. function deprecate (fn, msg) {
  14821. if (config('noDeprecation')) {
  14822. return fn;
  14823. }
  14824. var warned = false;
  14825. function deprecated() {
  14826. if (!warned) {
  14827. if (config('throwDeprecation')) {
  14828. throw new Error(msg);
  14829. } else if (config('traceDeprecation')) {
  14830. console.trace(msg);
  14831. } else {
  14832. console.warn(msg);
  14833. }
  14834. warned = true;
  14835. }
  14836. return fn.apply(this, arguments);
  14837. }
  14838. return deprecated;
  14839. }
  14840. /**
  14841. * Checks `localStorage` for boolean values for the given `name`.
  14842. *
  14843. * @param {String} name
  14844. * @returns {Boolean}
  14845. * @api private
  14846. */
  14847. function config (name) {
  14848. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  14849. try {
  14850. if (!global.localStorage) return false;
  14851. } catch (_) {
  14852. return false;
  14853. }
  14854. var val = global.localStorage[name];
  14855. if (null == val) return false;
  14856. return String(val).toLowerCase() === 'true';
  14857. }
  14858. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14859. },{}],85:[function(require,module,exports){
  14860. "use strict";
  14861. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  14862. return mod && mod.__esModule ? mod : {
  14863. "default": mod
  14864. };
  14865. };
  14866. Object.defineProperty(exports, "__esModule", {
  14867. value: true
  14868. });
  14869. exports.HandleZip = void 0;
  14870. var jszip_1 = __importDefault(require("jszip"));
  14871. var method_1 = require("./common/method");
  14872. var HandleZip =
  14873. /** @class */
  14874. function () {
  14875. function HandleZip(file) {
  14876. // Support nodejs fs to read files
  14877. // if(file instanceof File){
  14878. this.uploadFile = file; // }
  14879. }
  14880. HandleZip.prototype.unzipFile = function (successFunc, errorFunc) {
  14881. // var new_zip:JSZip = new JSZip();
  14882. jszip_1["default"].loadAsync(this.uploadFile) // 1) read the Blob
  14883. .then(function (zip) {
  14884. console.log(zip);
  14885. var fileList = {},
  14886. lastIndex = Object.keys(zip.files).length,
  14887. index = 0;
  14888. zip.forEach(function (relativePath, zipEntry) {
  14889. var fileName = zipEntry.name;
  14890. var fileNameArr = fileName.split(".");
  14891. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  14892. var fileType = "string";
  14893. if (suffix in {
  14894. "png": 1,
  14895. "jpeg": 1,
  14896. "jpg": 1,
  14897. "gif": 1,
  14898. "bmp": 1,
  14899. "tif": 1,
  14900. "webp": 1
  14901. }) {
  14902. fileType = "base64";
  14903. } else if (suffix == "emf") {
  14904. fileType = "arraybuffer";
  14905. }
  14906. zipEntry.async(fileType).then(function (data) {
  14907. if (fileType == "base64") {
  14908. data = "data:image/" + suffix + ";base64," + data;
  14909. }
  14910. fileList[zipEntry.name] = data; // console.log(lastIndex, index);
  14911. if (lastIndex == index + 1) {
  14912. successFunc(fileList);
  14913. }
  14914. index++;
  14915. });
  14916. });
  14917. }, function (e) {
  14918. errorFunc(e);
  14919. });
  14920. };
  14921. HandleZip.prototype.unzipFileByUrl = function (url, successFunc, errorFunc) {
  14922. var new_zip = new jszip_1["default"]();
  14923. method_1.getBinaryContent(url, function (err, data) {
  14924. if (err) {
  14925. throw err; // or handle err
  14926. }
  14927. jszip_1["default"].loadAsync(data).then(function (zip) {
  14928. var fileList = {},
  14929. lastIndex = Object.keys(zip.files).length,
  14930. index = 0;
  14931. zip.forEach(function (relativePath, zipEntry) {
  14932. var fileName = zipEntry.name;
  14933. var fileNameArr = fileName.split(".");
  14934. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  14935. var fileType = "string";
  14936. if (suffix in {
  14937. "png": 1,
  14938. "jpeg": 1,
  14939. "jpg": 1,
  14940. "gif": 1,
  14941. "bmp": 1,
  14942. "tif": 1,
  14943. "webp": 1
  14944. }) {
  14945. fileType = "base64";
  14946. } else if (suffix == "emf") {
  14947. fileType = "arraybuffer";
  14948. }
  14949. zipEntry.async(fileType).then(function (data) {
  14950. if (fileType == "base64") {
  14951. data = "data:image/" + suffix + ";base64," + data;
  14952. }
  14953. fileList[zipEntry.name] = data; // console.log(lastIndex, index);
  14954. if (lastIndex == index + 1) {
  14955. successFunc(fileList);
  14956. }
  14957. index++;
  14958. });
  14959. });
  14960. }, function (e) {
  14961. errorFunc(e);
  14962. });
  14963. });
  14964. };
  14965. HandleZip.prototype.newZipFile = function () {
  14966. var zip = new jszip_1["default"]();
  14967. this.workBook = zip;
  14968. }; //title:"nested/hello.txt", content:"Hello Worldasdfasfasdfasfasfasfasfasdfas"
  14969. HandleZip.prototype.addToZipFile = function (title, content) {
  14970. if (this.workBook == null) {
  14971. var zip = new jszip_1["default"]();
  14972. this.workBook = zip;
  14973. }
  14974. this.workBook.file(title, content);
  14975. };
  14976. return HandleZip;
  14977. }();
  14978. exports.HandleZip = HandleZip;
  14979. },{"./common/method":94,"jszip":21}],86:[function(require,module,exports){
  14980. "use strict";
  14981. Object.defineProperty(exports, "__esModule", {
  14982. value: true
  14983. });
  14984. exports.LuckyImageBase = exports.LuckysheetCalcChain = exports.LuckySheetConfigMerge = exports.LuckySheetborderInfoCellValueStyle = exports.LuckySheetborderInfoCellValue = exports.LuckySheetborderInfoCellForImp = exports.LuckyConfig = exports.LuckyInlineString = exports.LuckySheetCellFormat = exports.LuckySheetCelldataValue = exports.LuckySheetCelldataBase = exports.LuckyFileInfo = exports.LuckySheetBase = exports.LuckyFileBase = void 0;
  14985. var LuckyFileBase =
  14986. /** @class */
  14987. function () {
  14988. function LuckyFileBase() {}
  14989. return LuckyFileBase;
  14990. }();
  14991. exports.LuckyFileBase = LuckyFileBase;
  14992. var LuckySheetBase =
  14993. /** @class */
  14994. function () {
  14995. function LuckySheetBase() {}
  14996. return LuckySheetBase;
  14997. }();
  14998. exports.LuckySheetBase = LuckySheetBase;
  14999. var LuckyFileInfo =
  15000. /** @class */
  15001. function () {
  15002. function LuckyFileInfo() {}
  15003. return LuckyFileInfo;
  15004. }();
  15005. exports.LuckyFileInfo = LuckyFileInfo;
  15006. var LuckySheetCelldataBase =
  15007. /** @class */
  15008. function () {
  15009. function LuckySheetCelldataBase() {}
  15010. return LuckySheetCelldataBase;
  15011. }();
  15012. exports.LuckySheetCelldataBase = LuckySheetCelldataBase;
  15013. var LuckySheetCelldataValue =
  15014. /** @class */
  15015. function () {
  15016. function LuckySheetCelldataValue() {}
  15017. return LuckySheetCelldataValue;
  15018. }();
  15019. exports.LuckySheetCelldataValue = LuckySheetCelldataValue;
  15020. var LuckySheetCellFormat =
  15021. /** @class */
  15022. function () {
  15023. function LuckySheetCellFormat() {}
  15024. return LuckySheetCellFormat;
  15025. }();
  15026. exports.LuckySheetCellFormat = LuckySheetCellFormat;
  15027. var LuckyInlineString =
  15028. /** @class */
  15029. function () {
  15030. function LuckyInlineString() {}
  15031. return LuckyInlineString;
  15032. }();
  15033. exports.LuckyInlineString = LuckyInlineString;
  15034. var LuckyConfig =
  15035. /** @class */
  15036. function () {
  15037. function LuckyConfig() {}
  15038. return LuckyConfig;
  15039. }();
  15040. exports.LuckyConfig = LuckyConfig;
  15041. var LuckySheetborderInfoCellForImp =
  15042. /** @class */
  15043. function () {
  15044. function LuckySheetborderInfoCellForImp() {}
  15045. return LuckySheetborderInfoCellForImp;
  15046. }();
  15047. exports.LuckySheetborderInfoCellForImp = LuckySheetborderInfoCellForImp;
  15048. var LuckySheetborderInfoCellValue =
  15049. /** @class */
  15050. function () {
  15051. function LuckySheetborderInfoCellValue() {}
  15052. return LuckySheetborderInfoCellValue;
  15053. }();
  15054. exports.LuckySheetborderInfoCellValue = LuckySheetborderInfoCellValue;
  15055. var LuckySheetborderInfoCellValueStyle =
  15056. /** @class */
  15057. function () {
  15058. function LuckySheetborderInfoCellValueStyle() {}
  15059. return LuckySheetborderInfoCellValueStyle;
  15060. }();
  15061. exports.LuckySheetborderInfoCellValueStyle = LuckySheetborderInfoCellValueStyle;
  15062. var LuckySheetConfigMerge =
  15063. /** @class */
  15064. function () {
  15065. function LuckySheetConfigMerge() {}
  15066. return LuckySheetConfigMerge;
  15067. }();
  15068. exports.LuckySheetConfigMerge = LuckySheetConfigMerge;
  15069. var LuckysheetCalcChain =
  15070. /** @class */
  15071. function () {
  15072. function LuckysheetCalcChain() {}
  15073. return LuckysheetCalcChain;
  15074. }();
  15075. exports.LuckysheetCalcChain = LuckysheetCalcChain;
  15076. var LuckyImageBase =
  15077. /** @class */
  15078. function () {
  15079. function LuckyImageBase() {}
  15080. return LuckyImageBase;
  15081. }();
  15082. exports.LuckyImageBase = LuckyImageBase;
  15083. },{}],87:[function(require,module,exports){
  15084. "use strict";
  15085. var __extends = void 0 && (void 0).__extends || function () {
  15086. var _extendStatics = function extendStatics(d, b) {
  15087. _extendStatics = Object.setPrototypeOf || {
  15088. __proto__: []
  15089. } instanceof Array && function (d, b) {
  15090. d.__proto__ = b;
  15091. } || function (d, b) {
  15092. for (var p in b) {
  15093. if (b.hasOwnProperty(p)) d[p] = b[p];
  15094. }
  15095. };
  15096. return _extendStatics(d, b);
  15097. };
  15098. return function (d, b) {
  15099. _extendStatics(d, b);
  15100. function __() {
  15101. this.constructor = d;
  15102. }
  15103. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15104. };
  15105. }();
  15106. Object.defineProperty(exports, "__esModule", {
  15107. value: true
  15108. });
  15109. exports.LuckySheetCelldata = void 0;
  15110. var ReadXml_1 = require("./ReadXml");
  15111. var method_1 = require("../common/method");
  15112. var constant_1 = require("../common/constant");
  15113. var LuckyBase_1 = require("./LuckyBase");
  15114. var LuckySheetCelldata =
  15115. /** @class */
  15116. function (_super) {
  15117. __extends(LuckySheetCelldata, _super);
  15118. function LuckySheetCelldata(cell, styles, sharedStrings, mergeCells, sheetFile, ReadXml) {
  15119. var _this = //Private
  15120. _super.call(this) || this;
  15121. _this.cell = cell;
  15122. _this.sheetFile = sheetFile;
  15123. _this.styles = styles;
  15124. _this.sharedStrings = sharedStrings;
  15125. _this.readXml = ReadXml;
  15126. _this.mergeCells = mergeCells;
  15127. var attrList = cell.attributeList;
  15128. var r = attrList.r,
  15129. s = attrList.s,
  15130. t = attrList.t;
  15131. var range = method_1.getcellrange(r);
  15132. _this.r = range.row[0];
  15133. _this.c = range.column[0];
  15134. _this.v = _this.generateValue(s, t);
  15135. return _this;
  15136. }
  15137. /**
  15138. * @param s Style index ,start 1
  15139. * @param t Cell type, Optional value is ST_CellType, it's found at constat.ts
  15140. */
  15141. LuckySheetCelldata.prototype.generateValue = function (s, t) {
  15142. var _this = this;
  15143. var v = this.cell.getInnerElements("v");
  15144. var f = this.cell.getInnerElements("f");
  15145. if (v == null) {
  15146. v = this.cell.getInnerElements("t");
  15147. }
  15148. var cellXfs = this.styles["cellXfs"];
  15149. var cellStyleXfs = this.styles["cellStyleXfs"];
  15150. var cellStyles = this.styles["cellStyles"];
  15151. var fonts = this.styles["fonts"];
  15152. var fills = this.styles["fills"];
  15153. var borders = this.styles["borders"];
  15154. var numfmts = this.styles["numfmts"];
  15155. var clrScheme = this.styles["clrScheme"];
  15156. var sharedStrings = this.sharedStrings;
  15157. var cellValue = new LuckyBase_1.LuckySheetCelldataValue();
  15158. if (f != null) {
  15159. var formula = f[0],
  15160. attrList = formula.attributeList;
  15161. var t_1 = attrList.t,
  15162. ref = attrList.ref,
  15163. si = attrList.si;
  15164. var formulaValue = f[0].value;
  15165. if (t_1 == "shared") {
  15166. this._fomulaRef = ref;
  15167. this._formulaType = t_1;
  15168. this._formulaSi = si;
  15169. } // console.log(ref, t, si);
  15170. if (ref != null || formulaValue != null && formulaValue.length > 0) {
  15171. formulaValue = method_1.escapeCharacter(formulaValue);
  15172. cellValue.f = "=" + formulaValue;
  15173. }
  15174. }
  15175. var familyFont = null;
  15176. var quotePrefix;
  15177. if (s != null) {
  15178. var sNum = parseInt(s);
  15179. var cellXf = cellXfs[sNum];
  15180. var xfId = cellXf.attributeList.xfId;
  15181. var numFmtId = void 0,
  15182. fontId = void 0,
  15183. fillId = void 0,
  15184. borderId = void 0;
  15185. var horizontal = void 0,
  15186. vertical = void 0,
  15187. wrapText = void 0,
  15188. textRotation = void 0,
  15189. shrinkToFit = void 0,
  15190. indent = void 0,
  15191. applyProtection = void 0;
  15192. if (xfId != null) {
  15193. var cellStyleXf = cellStyleXfs[parseInt(xfId)];
  15194. var attrList = cellStyleXf.attributeList;
  15195. var applyNumberFormat_1 = attrList.applyNumberFormat;
  15196. var applyFont_1 = attrList.applyFont;
  15197. var applyFill_1 = attrList.applyFill;
  15198. var applyBorder_1 = attrList.applyBorder;
  15199. var applyAlignment_1 = attrList.applyAlignment; // let applyProtection = attrList.applyProtection;
  15200. applyProtection = attrList.applyProtection;
  15201. quotePrefix = attrList.quotePrefix;
  15202. if (applyNumberFormat_1 != "0" && attrList.numFmtId != null) {
  15203. // if(attrList.numFmtId!="0"){
  15204. numFmtId = attrList.numFmtId; // }
  15205. }
  15206. if (applyFont_1 != "0" && attrList.fontId != null) {
  15207. fontId = attrList.fontId;
  15208. }
  15209. if (applyFill_1 != "0" && attrList.fillId != null) {
  15210. fillId = attrList.fillId;
  15211. }
  15212. if (applyBorder_1 != "0" && attrList.borderId != null) {
  15213. borderId = attrList.borderId;
  15214. }
  15215. if (applyAlignment_1 != null && applyAlignment_1 != "0") {
  15216. var alignment = cellStyleXf.getInnerElements("alignment");
  15217. if (alignment != null) {
  15218. var attrList_1 = alignment[0].attributeList;
  15219. if (attrList_1.horizontal != null) {
  15220. horizontal = attrList_1.horizontal;
  15221. }
  15222. if (attrList_1.vertical != null) {
  15223. vertical = attrList_1.vertical;
  15224. }
  15225. if (attrList_1.wrapText != null) {
  15226. wrapText = attrList_1.wrapText;
  15227. }
  15228. if (attrList_1.textRotation != null) {
  15229. textRotation = attrList_1.textRotation;
  15230. }
  15231. if (attrList_1.shrinkToFit != null) {
  15232. shrinkToFit = attrList_1.shrinkToFit;
  15233. }
  15234. if (attrList_1.indent != null) {
  15235. indent = attrList_1.indent;
  15236. }
  15237. }
  15238. }
  15239. }
  15240. var applyNumberFormat = cellXf.attributeList.applyNumberFormat;
  15241. var applyFont = cellXf.attributeList.applyFont;
  15242. var applyFill = cellXf.attributeList.applyFill;
  15243. var applyBorder = cellXf.attributeList.applyBorder;
  15244. var applyAlignment = cellXf.attributeList.applyAlignment;
  15245. if (cellXf.attributeList.applyProtection != null) {
  15246. applyProtection = cellXf.attributeList.applyProtection;
  15247. }
  15248. if (cellXf.attributeList.quotePrefix != null) {
  15249. quotePrefix = cellXf.attributeList.quotePrefix;
  15250. }
  15251. if (applyNumberFormat != "0" && cellXf.attributeList.numFmtId != null) {
  15252. numFmtId = cellXf.attributeList.numFmtId;
  15253. }
  15254. if (applyFont != "0") {
  15255. fontId = cellXf.attributeList.fontId;
  15256. }
  15257. if (applyFill != "0") {
  15258. fillId = cellXf.attributeList.fillId;
  15259. }
  15260. if (applyBorder != "0") {
  15261. borderId = cellXf.attributeList.borderId;
  15262. }
  15263. if (applyAlignment != "0") {
  15264. var alignment = cellXf.getInnerElements("alignment");
  15265. if (alignment != null && alignment.length > 0) {
  15266. var attrList = alignment[0].attributeList;
  15267. if (attrList.horizontal != null) {
  15268. horizontal = attrList.horizontal;
  15269. }
  15270. if (attrList.vertical != null) {
  15271. vertical = attrList.vertical;
  15272. }
  15273. if (attrList.wrapText != null) {
  15274. wrapText = attrList.wrapText;
  15275. }
  15276. if (attrList.textRotation != null) {
  15277. textRotation = attrList.textRotation;
  15278. }
  15279. if (attrList.shrinkToFit != null) {
  15280. shrinkToFit = attrList.shrinkToFit;
  15281. }
  15282. if (attrList.indent != null) {
  15283. indent = attrList.indent;
  15284. }
  15285. }
  15286. }
  15287. if (numFmtId != undefined) {
  15288. var numf = numfmts[parseInt(numFmtId)];
  15289. var cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15290. cellFormat.fa = method_1.escapeCharacter(numf); // console.log(numf, numFmtId, this.v);
  15291. cellFormat.t = t || 'd';
  15292. cellValue.ct = cellFormat;
  15293. }
  15294. if (fillId != undefined) {
  15295. var fillIdNum = parseInt(fillId);
  15296. var fill = fills[fillIdNum]; // console.log(cellValue.v);
  15297. var bg = this.getBackgroundByFill(fill, clrScheme);
  15298. if (bg != null) {
  15299. cellValue.bg = bg;
  15300. }
  15301. }
  15302. if (fontId != undefined) {
  15303. var fontIdNum = parseInt(fontId);
  15304. var font = fonts[fontIdNum];
  15305. if (font != null) {
  15306. var sz = font.getInnerElements("sz"); //font size
  15307. var colors = font.getInnerElements("color"); //font color
  15308. var family = font.getInnerElements("name"); //font family
  15309. var familyOverrides = font.getInnerElements("family"); //font family will be overrided by name
  15310. var charset = font.getInnerElements("charset"); //font charset
  15311. var bolds = font.getInnerElements("b"); //font bold
  15312. var italics = font.getInnerElements("i"); //font italic
  15313. var strikes = font.getInnerElements("strike"); //font italic
  15314. var underlines = font.getInnerElements("u"); //font italic
  15315. if (sz != null && sz.length > 0) {
  15316. var fs = sz[0].attributeList.val;
  15317. if (fs != null) {
  15318. cellValue.fs = parseInt(fs);
  15319. }
  15320. }
  15321. if (colors != null && colors.length > 0) {
  15322. var color = colors[0];
  15323. var fc = ReadXml_1.getColor(color, this.styles, "t");
  15324. if (fc != null) {
  15325. cellValue.fc = fc;
  15326. }
  15327. }
  15328. if (familyOverrides != null && familyOverrides.length > 0) {
  15329. var val = familyOverrides[0].attributeList.val;
  15330. if (val != null) {
  15331. familyFont = constant_1.fontFamilys[val];
  15332. }
  15333. }
  15334. if (family != null && family.length > 0) {
  15335. var val = family[0].attributeList.val;
  15336. if (val != null) {
  15337. cellValue.ff = val;
  15338. }
  15339. }
  15340. if (bolds != null && bolds.length > 0) {
  15341. var bold = bolds[0].attributeList.val;
  15342. if (bold == "0") {
  15343. cellValue.bl = 0;
  15344. } else {
  15345. cellValue.bl = 1;
  15346. }
  15347. }
  15348. if (italics != null && italics.length > 0) {
  15349. var italic = italics[0].attributeList.val;
  15350. if (italic == "0") {
  15351. cellValue.it = 0;
  15352. } else {
  15353. cellValue.it = 1;
  15354. }
  15355. }
  15356. if (strikes != null && strikes.length > 0) {
  15357. var strike = strikes[0].attributeList.val;
  15358. if (strike == "0") {
  15359. cellValue.cl = 0;
  15360. } else {
  15361. cellValue.cl = 1;
  15362. }
  15363. }
  15364. if (underlines != null && underlines.length > 0) {
  15365. var underline = underlines[0].attributeList.val;
  15366. if (underline == "single") {
  15367. cellValue.un = 1;
  15368. } else if (underline == "double") {
  15369. cellValue.un = 2;
  15370. } else if (underline == "singleAccounting") {
  15371. cellValue.un = 3;
  15372. } else if (underline == "doubleAccounting") {
  15373. cellValue.un = 4;
  15374. } else {
  15375. cellValue.un = 0;
  15376. }
  15377. }
  15378. }
  15379. } // vt: number | undefined//Vertical alignment, 0 middle, 1 up, 2 down, alignment
  15380. // ht: number | undefined//Horizontal alignment,0 center, 1 left, 2 right, alignment
  15381. // tr: number | undefined //Text rotation,0: 0、1: 45 、2: -45、3 Vertical text、4: 90 、5: -90, alignment
  15382. // tb: number | undefined //Text wrap,0 truncation, 1 overflow, 2 word wrap, alignment
  15383. if (horizontal != undefined) {
  15384. //Horizontal alignment
  15385. if (horizontal == "center") {
  15386. cellValue.ht = 0;
  15387. } else if (horizontal == "centerContinuous") {
  15388. cellValue.ht = 0; //luckysheet unsupport
  15389. } else if (horizontal == "left") {
  15390. cellValue.ht = 1;
  15391. } else if (horizontal == "right") {
  15392. cellValue.ht = 2;
  15393. } else if (horizontal == "distributed") {
  15394. cellValue.ht = 0; //luckysheet unsupport
  15395. } else if (horizontal == "fill") {
  15396. cellValue.ht = 1; //luckysheet unsupport
  15397. } else if (horizontal == "general") {
  15398. cellValue.ht = 1; //luckysheet unsupport
  15399. } else if (horizontal == "justify") {
  15400. cellValue.ht = 0; //luckysheet unsupport
  15401. } else {
  15402. cellValue.ht = 1;
  15403. }
  15404. }
  15405. if (vertical != undefined) {
  15406. //Vertical alignment
  15407. if (vertical == "bottom") {
  15408. cellValue.vt = 2;
  15409. } else if (vertical == "center") {
  15410. cellValue.vt = 0;
  15411. } else if (vertical == "distributed") {
  15412. cellValue.vt = 0; //luckysheet unsupport
  15413. } else if (vertical == "justify") {
  15414. cellValue.vt = 0; //luckysheet unsupport
  15415. } else if (vertical == "top") {
  15416. cellValue.vt = 1;
  15417. } else {
  15418. cellValue.vt = 1;
  15419. }
  15420. } else {
  15421. //sometimes bottom style is lost after setting it in excel
  15422. //when vertical is undefined set it to 2.
  15423. cellValue.vt = 2;
  15424. }
  15425. if (wrapText != undefined) {
  15426. if (wrapText == "1") {
  15427. cellValue.tb = 2;
  15428. } else {
  15429. cellValue.tb = 1;
  15430. }
  15431. } else {
  15432. cellValue.tb = 1;
  15433. }
  15434. if (textRotation != undefined) {
  15435. // tr: number | undefined //Text rotation,0: 0、1: 45 、2: -45、3 Vertical text、4: 90 、5: -90, alignment
  15436. if (textRotation == "255") {
  15437. cellValue.tr = 3;
  15438. } // else if(textRotation=="45"){
  15439. // cellValue.tr = 1;
  15440. // }
  15441. // else if(textRotation=="90"){
  15442. // cellValue.tr = 4;
  15443. // }
  15444. // else if(textRotation=="135"){
  15445. // cellValue.tr = 2;
  15446. // }
  15447. // else if(textRotation=="180"){
  15448. // cellValue.tr = 5;
  15449. // }
  15450. else {
  15451. cellValue.tr = 0;
  15452. cellValue.rt = parseInt(textRotation);
  15453. }
  15454. }
  15455. if (shrinkToFit != undefined) {//luckysheet unsupport
  15456. }
  15457. if (indent != undefined) {//luckysheet unsupport
  15458. }
  15459. if (borderId != undefined) {
  15460. var borderIdNum = parseInt(borderId);
  15461. var border = borders[borderIdNum]; // this._borderId = borderIdNum;
  15462. var borderObject = new LuckyBase_1.LuckySheetborderInfoCellForImp();
  15463. borderObject.rangeType = "cell"; // borderObject.cells = [];
  15464. var borderCellValue = new LuckyBase_1.LuckySheetborderInfoCellValue();
  15465. borderCellValue.row_index = this.r;
  15466. borderCellValue.col_index = this.c;
  15467. var lefts = border.getInnerElements("left");
  15468. var rights = border.getInnerElements("right");
  15469. var tops = border.getInnerElements("top");
  15470. var bottoms = border.getInnerElements("bottom");
  15471. var diagonals = border.getInnerElements("diagonal");
  15472. var starts = border.getInnerElements("start");
  15473. var ends = border.getInnerElements("end");
  15474. var left = this.getBorderInfo(lefts);
  15475. var right = this.getBorderInfo(rights);
  15476. var top_1 = this.getBorderInfo(tops);
  15477. var bottom = this.getBorderInfo(bottoms);
  15478. var diagonal = this.getBorderInfo(diagonals);
  15479. var start = this.getBorderInfo(starts);
  15480. var end = this.getBorderInfo(ends);
  15481. var isAdd = false;
  15482. if (start != null && start.color != null) {
  15483. borderCellValue.l = start;
  15484. isAdd = true;
  15485. }
  15486. if (end != null && end.color != null) {
  15487. borderCellValue.r = end;
  15488. isAdd = true;
  15489. }
  15490. if (left != null && left.color != null) {
  15491. borderCellValue.l = left;
  15492. isAdd = true;
  15493. }
  15494. if (right != null && right.color != null) {
  15495. borderCellValue.r = right;
  15496. isAdd = true;
  15497. }
  15498. if (top_1 != null && top_1.color != null) {
  15499. borderCellValue.t = top_1;
  15500. isAdd = true;
  15501. }
  15502. if (bottom != null && bottom.color != null) {
  15503. borderCellValue.b = bottom;
  15504. isAdd = true;
  15505. }
  15506. if (isAdd) {
  15507. borderObject.value = borderCellValue; // this.config._borderInfo[borderId] = borderObject;
  15508. this._borderObject = borderObject;
  15509. }
  15510. }
  15511. } else {
  15512. cellValue.tb = 1;
  15513. }
  15514. if (v != null) {
  15515. var value = v[0].value;
  15516. if (/&#\d+;/.test(value)) {
  15517. value = this.htmlDecode(value);
  15518. }
  15519. if (t == constant_1.ST_CellType["SharedString"]) {
  15520. var siIndex = parseInt(v[0].value);
  15521. var sharedSI = sharedStrings[siIndex];
  15522. var rFlag = sharedSI.getInnerElements("r");
  15523. if (rFlag == null) {
  15524. var tFlag = sharedSI.getInnerElements("t");
  15525. if (tFlag != null) {
  15526. var text_1 = "";
  15527. tFlag.forEach(function (t) {
  15528. text_1 += t.value;
  15529. });
  15530. text_1 = method_1.escapeCharacter(text_1); //isContainMultiType(text) &&
  15531. if (familyFont == "Roman" && text_1.length > 0) {
  15532. var textArray = text_1.split("");
  15533. var preWordType = null,
  15534. wordText = "",
  15535. preWholef = null;
  15536. var wholef = "Times New Roman";
  15537. if (cellValue.ff != null) {
  15538. wholef = cellValue.ff;
  15539. }
  15540. var cellFormat = cellValue.ct;
  15541. if (cellFormat == null) {
  15542. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15543. }
  15544. if (cellFormat.s == null) {
  15545. cellFormat.s = [];
  15546. }
  15547. for (var i = 0; i < textArray.length; i++) {
  15548. var w = textArray[i];
  15549. var type = null,
  15550. ff = wholef;
  15551. if (method_1.isChinese(w)) {
  15552. type = "c";
  15553. ff = "宋体";
  15554. } else if (method_1.isJapanese(w)) {
  15555. type = "j";
  15556. ff = "Yu Gothic";
  15557. } else if (method_1.isKoera(w)) {
  15558. type = "k";
  15559. ff = "Malgun Gothic";
  15560. } else {
  15561. type = "e";
  15562. }
  15563. if (type != preWordType && preWordType != null || i == textArray.length - 1) {
  15564. var InlineString = new LuckyBase_1.LuckyInlineString();
  15565. InlineString.ff = preWholef;
  15566. if (cellValue.fc != null) {
  15567. InlineString.fc = cellValue.fc;
  15568. }
  15569. if (cellValue.fs != null) {
  15570. InlineString.fs = cellValue.fs;
  15571. }
  15572. if (cellValue.cl != null) {
  15573. InlineString.cl = cellValue.cl;
  15574. }
  15575. if (cellValue.un != null) {
  15576. InlineString.un = cellValue.un;
  15577. }
  15578. if (cellValue.bl != null) {
  15579. InlineString.bl = cellValue.bl;
  15580. }
  15581. if (cellValue.it != null) {
  15582. InlineString.it = cellValue.it;
  15583. }
  15584. if (i == textArray.length - 1) {
  15585. if (type == preWordType) {
  15586. InlineString.ff = ff;
  15587. InlineString.v = wordText + w;
  15588. } else {
  15589. InlineString.ff = preWholef;
  15590. InlineString.v = wordText;
  15591. cellFormat.s.push(InlineString);
  15592. var InlineStringLast = new LuckyBase_1.LuckyInlineString();
  15593. InlineStringLast.ff = ff;
  15594. InlineStringLast.v = w;
  15595. if (cellValue.fc != null) {
  15596. InlineStringLast.fc = cellValue.fc;
  15597. }
  15598. if (cellValue.fs != null) {
  15599. InlineStringLast.fs = cellValue.fs;
  15600. }
  15601. if (cellValue.cl != null) {
  15602. InlineStringLast.cl = cellValue.cl;
  15603. }
  15604. if (cellValue.un != null) {
  15605. InlineStringLast.un = cellValue.un;
  15606. }
  15607. if (cellValue.bl != null) {
  15608. InlineStringLast.bl = cellValue.bl;
  15609. }
  15610. if (cellValue.it != null) {
  15611. InlineStringLast.it = cellValue.it;
  15612. }
  15613. cellFormat.s.push(InlineStringLast);
  15614. break;
  15615. }
  15616. } else {
  15617. InlineString.v = wordText;
  15618. }
  15619. cellFormat.s.push(InlineString);
  15620. wordText = w;
  15621. } else {
  15622. wordText += w;
  15623. }
  15624. preWordType = type;
  15625. preWholef = ff;
  15626. }
  15627. cellFormat.t = "inlineStr"; // cellFormat.s = [InlineString];
  15628. cellValue.ct = cellFormat; // console.log(cellValue);
  15629. } else {
  15630. text_1 = this.replaceSpecialWrap(text_1);
  15631. if (text_1.indexOf("\r\n") > -1 || text_1.indexOf("\n") > -1) {
  15632. var InlineString = new LuckyBase_1.LuckyInlineString();
  15633. InlineString.v = text_1;
  15634. var cellFormat = cellValue.ct;
  15635. if (cellFormat == null) {
  15636. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15637. }
  15638. if (cellValue.ff != null) {
  15639. InlineString.ff = cellValue.ff;
  15640. }
  15641. if (cellValue.fc != null) {
  15642. InlineString.fc = cellValue.fc;
  15643. }
  15644. if (cellValue.fs != null) {
  15645. InlineString.fs = cellValue.fs;
  15646. }
  15647. if (cellValue.cl != null) {
  15648. InlineString.cl = cellValue.cl;
  15649. }
  15650. if (cellValue.un != null) {
  15651. InlineString.un = cellValue.un;
  15652. }
  15653. if (cellValue.bl != null) {
  15654. InlineString.bl = cellValue.bl;
  15655. }
  15656. if (cellValue.it != null) {
  15657. InlineString.it = cellValue.it;
  15658. }
  15659. cellFormat.t = "inlineStr";
  15660. cellFormat.s = [InlineString];
  15661. cellValue.ct = cellFormat;
  15662. } else {
  15663. cellValue.v = text_1;
  15664. quotePrefix = "1";
  15665. }
  15666. }
  15667. }
  15668. } else {
  15669. var styles_1 = [];
  15670. rFlag.forEach(function (r) {
  15671. var tFlag = r.getInnerElements("t");
  15672. var rPr = r.getInnerElements("rPr");
  15673. var InlineString = new LuckyBase_1.LuckyInlineString();
  15674. if (tFlag != null && tFlag.length > 0) {
  15675. var text = tFlag[0].value;
  15676. text = _this.replaceSpecialWrap(text);
  15677. text = method_1.escapeCharacter(text);
  15678. InlineString.v = text;
  15679. }
  15680. if (rPr != null && rPr.length > 0) {
  15681. var frpr = rPr[0];
  15682. var sz = ReadXml_1.getlineStringAttr(frpr, "sz"),
  15683. rFont = ReadXml_1.getlineStringAttr(frpr, "rFont"),
  15684. family = ReadXml_1.getlineStringAttr(frpr, "family"),
  15685. charset = ReadXml_1.getlineStringAttr(frpr, "charset"),
  15686. scheme = ReadXml_1.getlineStringAttr(frpr, "scheme"),
  15687. b = ReadXml_1.getlineStringAttr(frpr, "b"),
  15688. i = ReadXml_1.getlineStringAttr(frpr, "i"),
  15689. u = ReadXml_1.getlineStringAttr(frpr, "u"),
  15690. strike = ReadXml_1.getlineStringAttr(frpr, "strike"),
  15691. vertAlign = ReadXml_1.getlineStringAttr(frpr, "vertAlign"),
  15692. color = void 0;
  15693. var cEle = frpr.getInnerElements("color");
  15694. if (cEle != null && cEle.length > 0) {
  15695. color = ReadXml_1.getColor(cEle[0], _this.styles, "t");
  15696. }
  15697. var ff = void 0; // if(family!=null){
  15698. // ff = fontFamilys[family];
  15699. // }
  15700. if (rFont != null) {
  15701. ff = rFont;
  15702. }
  15703. if (ff != null) {
  15704. InlineString.ff = ff;
  15705. } else if (cellValue.ff != null) {
  15706. InlineString.ff = cellValue.ff;
  15707. }
  15708. if (color != null) {
  15709. InlineString.fc = color;
  15710. } else if (cellValue.fc != null) {
  15711. InlineString.fc = cellValue.fc;
  15712. }
  15713. if (sz != null) {
  15714. InlineString.fs = parseInt(sz);
  15715. } else if (cellValue.fs != null) {
  15716. InlineString.fs = cellValue.fs;
  15717. }
  15718. if (strike != null) {
  15719. InlineString.cl = parseInt(strike);
  15720. } else if (cellValue.cl != null) {
  15721. InlineString.cl = cellValue.cl;
  15722. }
  15723. if (u != null) {
  15724. InlineString.un = parseInt(u);
  15725. } else if (cellValue.un != null) {
  15726. InlineString.un = cellValue.un;
  15727. }
  15728. if (b != null) {
  15729. InlineString.bl = parseInt(b);
  15730. } else if (cellValue.bl != null) {
  15731. InlineString.bl = cellValue.bl;
  15732. }
  15733. if (i != null) {
  15734. InlineString.it = parseInt(i);
  15735. } else if (cellValue.it != null) {
  15736. InlineString.it = cellValue.it;
  15737. }
  15738. if (vertAlign != null) {
  15739. InlineString.va = parseInt(vertAlign);
  15740. } // ff:string | undefined //font family
  15741. // fc:string | undefined//font color
  15742. // fs:number | undefined//font size
  15743. // cl:number | undefined//strike
  15744. // un:number | undefined//underline
  15745. // bl:number | undefined//blod
  15746. // it:number | undefined//italic
  15747. // v:string | undefined
  15748. } else {
  15749. if (InlineString.ff == null && cellValue.ff != null) {
  15750. InlineString.ff = cellValue.ff;
  15751. }
  15752. if (InlineString.fc == null && cellValue.fc != null) {
  15753. InlineString.fc = cellValue.fc;
  15754. }
  15755. if (InlineString.fs == null && cellValue.fs != null) {
  15756. InlineString.fs = cellValue.fs;
  15757. }
  15758. if (InlineString.cl == null && cellValue.cl != null) {
  15759. InlineString.cl = cellValue.cl;
  15760. }
  15761. if (InlineString.un == null && cellValue.un != null) {
  15762. InlineString.un = cellValue.un;
  15763. }
  15764. if (InlineString.bl == null && cellValue.bl != null) {
  15765. InlineString.bl = cellValue.bl;
  15766. }
  15767. if (InlineString.it == null && cellValue.it != null) {
  15768. InlineString.it = cellValue.it;
  15769. }
  15770. }
  15771. styles_1.push(InlineString);
  15772. });
  15773. var cellFormat = cellValue.ct;
  15774. if (cellFormat == null) {
  15775. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15776. }
  15777. cellFormat.t = "inlineStr";
  15778. cellFormat.s = styles_1;
  15779. cellValue.ct = cellFormat;
  15780. }
  15781. } // to be confirmed
  15782. else if (t == constant_1.ST_CellType["InlineString"] && v != null) {
  15783. cellValue.v = "'" + value;
  15784. } else {
  15785. value = method_1.escapeCharacter(value);
  15786. cellValue.v = value;
  15787. }
  15788. }
  15789. if (quotePrefix != null) {
  15790. cellValue.qp = parseInt(quotePrefix);
  15791. }
  15792. return cellValue;
  15793. };
  15794. LuckySheetCelldata.prototype.replaceSpecialWrap = function (text) {
  15795. text = text.replace(/_x000D_/g, "").replace(/&#13;&#10;/g, "\r\n").replace(/&#13;/g, "\r").replace(/&#10;/g, "\n");
  15796. return text;
  15797. };
  15798. LuckySheetCelldata.prototype.getBackgroundByFill = function (fill, clrScheme) {
  15799. var patternFills = fill.getInnerElements("patternFill");
  15800. if (patternFills != null) {
  15801. var patternFill = patternFills[0];
  15802. var fgColors = patternFill.getInnerElements("fgColor");
  15803. var bgColors = patternFill.getInnerElements("bgColor");
  15804. var fg = void 0,
  15805. bg = void 0;
  15806. if (fgColors != null) {
  15807. var fgColor = fgColors[0];
  15808. fg = ReadXml_1.getColor(fgColor, this.styles);
  15809. }
  15810. if (bgColors != null) {
  15811. var bgColor = bgColors[0];
  15812. bg = ReadXml_1.getColor(bgColor, this.styles);
  15813. } // console.log(fgColors,bgColors,clrScheme);
  15814. if (fg != null) {
  15815. return fg;
  15816. } else if (bg != null) {
  15817. return bg;
  15818. }
  15819. } else {
  15820. var gradientfills = fill.getInnerElements("gradientFill");
  15821. if (gradientfills != null) {
  15822. //graient color fill handler
  15823. return null;
  15824. }
  15825. }
  15826. };
  15827. LuckySheetCelldata.prototype.getBorderInfo = function (borders) {
  15828. if (borders == null) {
  15829. return null;
  15830. }
  15831. var border = borders[0],
  15832. attrList = border.attributeList;
  15833. var clrScheme = this.styles["clrScheme"];
  15834. var style = attrList.style;
  15835. if (style == null || style == "none") {
  15836. return null;
  15837. }
  15838. var colors = border.getInnerElements("color");
  15839. var colorRet = "#000000";
  15840. if (colors != null) {
  15841. var color = colors[0];
  15842. colorRet = ReadXml_1.getColor(color, this.styles, "b");
  15843. if (colorRet == null) {
  15844. colorRet = "#000000";
  15845. }
  15846. }
  15847. var ret = new LuckyBase_1.LuckySheetborderInfoCellValueStyle();
  15848. ret.style = constant_1.borderTypes[style];
  15849. ret.color = colorRet;
  15850. return ret;
  15851. };
  15852. LuckySheetCelldata.prototype.htmlDecode = function (str) {
  15853. return str.replace(/&#(x)?([^&]{1,5});/g, function ($, $1, $2) {
  15854. return String.fromCharCode(parseInt($2, $1 ? 16 : 10));
  15855. });
  15856. };
  15857. ;
  15858. return LuckySheetCelldata;
  15859. }(LuckyBase_1.LuckySheetCelldataBase);
  15860. exports.LuckySheetCelldata = LuckySheetCelldata;
  15861. },{"../common/constant":92,"../common/method":94,"./LuckyBase":86,"./ReadXml":91}],88:[function(require,module,exports){
  15862. "use strict";
  15863. var __extends = void 0 && (void 0).__extends || function () {
  15864. var _extendStatics = function extendStatics(d, b) {
  15865. _extendStatics = Object.setPrototypeOf || {
  15866. __proto__: []
  15867. } instanceof Array && function (d, b) {
  15868. d.__proto__ = b;
  15869. } || function (d, b) {
  15870. for (var p in b) {
  15871. if (b.hasOwnProperty(p)) d[p] = b[p];
  15872. }
  15873. };
  15874. return _extendStatics(d, b);
  15875. };
  15876. return function (d, b) {
  15877. _extendStatics(d, b);
  15878. function __() {
  15879. this.constructor = d;
  15880. }
  15881. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15882. };
  15883. }();
  15884. Object.defineProperty(exports, "__esModule", {
  15885. value: true
  15886. });
  15887. exports.LuckyFile = void 0;
  15888. var LuckySheet_1 = require("./LuckySheet");
  15889. var constant_1 = require("../common/constant");
  15890. var ReadXml_1 = require("./ReadXml");
  15891. var method_1 = require("../common/method");
  15892. var LuckyBase_1 = require("./LuckyBase");
  15893. var LuckyImage_1 = require("./LuckyImage");
  15894. var LuckyFile =
  15895. /** @class */
  15896. function (_super) {
  15897. __extends(LuckyFile, _super);
  15898. function LuckyFile(files, fileName) {
  15899. var _this = _super.call(this) || this;
  15900. _this.columnWidthSet = [];
  15901. _this.rowHeightSet = [];
  15902. _this.files = files;
  15903. _this.fileName = fileName;
  15904. _this.readXml = new ReadXml_1.ReadXml(files);
  15905. console.log('readXml:', _this.readXml);
  15906. _this.getSheetNameList();
  15907. _this.sharedStrings = _this.readXml.getElementsByTagName("sst/si", constant_1.sharedStringsFile);
  15908. _this.calcChain = _this.readXml.getElementsByTagName("calcChain/c", constant_1.calcChainFile);
  15909. _this.styles = {};
  15910. _this.styles["cellXfs"] = _this.readXml.getElementsByTagName("cellXfs/xf", constant_1.stylesFile);
  15911. _this.styles["cellStyleXfs"] = _this.readXml.getElementsByTagName("cellStyleXfs/xf", constant_1.stylesFile);
  15912. _this.styles["cellStyles"] = _this.readXml.getElementsByTagName("cellStyles/cellStyle", constant_1.stylesFile);
  15913. _this.styles["fonts"] = _this.readXml.getElementsByTagName("fonts/font", constant_1.stylesFile);
  15914. _this.styles["fills"] = _this.readXml.getElementsByTagName("fills/fill", constant_1.stylesFile);
  15915. _this.styles["borders"] = _this.readXml.getElementsByTagName("borders/border", constant_1.stylesFile);
  15916. _this.styles["clrScheme"] = _this.readXml.getElementsByTagName("a:clrScheme/a:dk1|a:lt1|a:dk2|a:lt2|a:accent1|a:accent2|a:accent3|a:accent4|a:accent5|a:accent6|a:hlink|a:folHlink", constant_1.theme1File);
  15917. _this.styles["indexedColors"] = _this.readXml.getElementsByTagName("colors/indexedColors/rgbColor", constant_1.stylesFile);
  15918. _this.styles["mruColors"] = _this.readXml.getElementsByTagName("colors/mruColors/color", constant_1.stylesFile);
  15919. _this.imageList = new LuckyImage_1.ImageList(files);
  15920. var numfmts = _this.readXml.getElementsByTagName("numFmt/numFmt", constant_1.stylesFile);
  15921. var numFmtDefaultC = JSON.parse(JSON.stringify(constant_1.numFmtDefault));
  15922. for (var i = 0; i < numfmts.length; i++) {
  15923. var attrList = numfmts[i].attributeList;
  15924. var numfmtid = method_1.getXmlAttibute(attrList, "numFmtId", "49");
  15925. var formatcode = method_1.getXmlAttibute(attrList, "formatCode", "@"); // console.log(numfmtid, formatcode);
  15926. if (!(numfmtid in constant_1.numFmtDefault)) {
  15927. numFmtDefaultC[numfmtid] = constant_1.numFmtDefaultMap[formatcode] || formatcode;
  15928. }
  15929. }
  15930. console.log("calcChain", _this.calcChain); // console.log(JSON.stringify(numFmtDefaultC), numfmts);
  15931. _this.styles["numfmts"] = numFmtDefaultC;
  15932. return _this;
  15933. }
  15934. /**
  15935. * @return All sheet name of workbook
  15936. */
  15937. LuckyFile.prototype.getSheetNameList = function () {
  15938. var workbookRelList = this.readXml.getElementsByTagName("Relationships/Relationship", constant_1.workbookRels);
  15939. if (workbookRelList == null) {
  15940. return;
  15941. }
  15942. var regex = new RegExp("worksheets/[^/]*?.xml");
  15943. var sheetNames = {};
  15944. for (var i = 0; i < workbookRelList.length; i++) {
  15945. var rel = workbookRelList[i],
  15946. attrList = rel.attributeList;
  15947. var id = attrList["Id"],
  15948. target = attrList["Target"];
  15949. if (regex.test(target)) {
  15950. if (target.indexOf('/xl') === 0) {
  15951. sheetNames[id] = target.substr(1);
  15952. } else {
  15953. sheetNames[id] = "xl/" + target;
  15954. }
  15955. }
  15956. }
  15957. this.sheetNameList = sheetNames;
  15958. };
  15959. /**
  15960. * @param sheetName WorkSheet'name
  15961. * @return sheet file name and path in zip
  15962. */
  15963. LuckyFile.prototype.getSheetFileBysheetId = function (sheetId) {
  15964. // for(let i=0;i<this.sheetNameList.length;i++){
  15965. // let sheetFileName = this.sheetNameList[i];
  15966. // if(sheetFileName.indexOf("sheet"+sheetId)>-1){
  15967. // return sheetFileName;
  15968. // }
  15969. // }
  15970. return this.sheetNameList[sheetId];
  15971. };
  15972. /**
  15973. * @return workBook information
  15974. */
  15975. LuckyFile.prototype.getWorkBookInfo = function () {
  15976. var Company = this.readXml.getElementsByTagName("Company", constant_1.appFile);
  15977. var AppVersion = this.readXml.getElementsByTagName("AppVersion", constant_1.appFile);
  15978. var creator = this.readXml.getElementsByTagName("dc:creator", constant_1.coreFile);
  15979. var lastModifiedBy = this.readXml.getElementsByTagName("cp:lastModifiedBy", constant_1.coreFile);
  15980. var created = this.readXml.getElementsByTagName("dcterms:created", constant_1.coreFile);
  15981. var modified = this.readXml.getElementsByTagName("dcterms:modified", constant_1.coreFile);
  15982. this.info = new LuckyBase_1.LuckyFileInfo();
  15983. this.info.name = this.fileName;
  15984. this.info.creator = creator.length > 0 ? creator[0].value : "";
  15985. this.info.lastmodifiedby = lastModifiedBy.length > 0 ? lastModifiedBy[0].value : "";
  15986. this.info.createdTime = created.length > 0 ? created[0].value : "";
  15987. this.info.modifiedTime = modified.length > 0 ? modified[0].value : "";
  15988. this.info.company = Company.length > 0 ? Company[0].value : "";
  15989. this.info.appversion = AppVersion.length > 0 ? AppVersion[0].value : "";
  15990. };
  15991. /**
  15992. * @return All sheet , include whole information
  15993. */
  15994. LuckyFile.prototype.getSheetsFull = function (isInitialCell) {
  15995. if (isInitialCell === void 0) {
  15996. isInitialCell = true;
  15997. }
  15998. console.log(this.calcChain);
  15999. var sheets = this.readXml.getElementsByTagName("sheets/sheet", constant_1.workBookFile);
  16000. var sheetList = {};
  16001. for (var key in sheets) {
  16002. var sheet = sheets[key];
  16003. sheetList[sheet.attributeList.name] = sheet.attributeList["sheetId"];
  16004. }
  16005. this.sheets = [];
  16006. var order = 0;
  16007. for (var key in sheets) {
  16008. var sheet = sheets[key];
  16009. var sheetName = sheet.attributeList.name;
  16010. var sheetId = sheet.attributeList["sheetId"];
  16011. var rid = sheet.attributeList["r:id"];
  16012. var sheetFile = this.getSheetFileBysheetId(rid);
  16013. var hide = sheet.attributeList.state === "hidden" ? 1 : 0;
  16014. var drawing = this.readXml.getElementsByTagName("worksheet/drawing", sheetFile),
  16015. drawingFile = void 0,
  16016. drawingRelsFile = void 0;
  16017. if (drawing != null && drawing.length > 0) {
  16018. var attrList = drawing[0].attributeList;
  16019. var rid_1 = method_1.getXmlAttibute(attrList, "r:id", null);
  16020. if (rid_1 != null) {
  16021. drawingFile = this.getDrawingFile(rid_1, sheetFile);
  16022. drawingRelsFile = this.getDrawingRelsFile(drawingFile);
  16023. }
  16024. }
  16025. if (sheetFile != null) {
  16026. console.log(this.calcChain);
  16027. var sheet_1 = new LuckySheet_1.LuckySheet(sheetName, sheetId, order, isInitialCell, {
  16028. sheetFile: sheetFile,
  16029. readXml: this.readXml,
  16030. sheetList: sheetList,
  16031. styles: this.styles,
  16032. sharedStrings: this.sharedStrings,
  16033. calcChain: this.calcChain,
  16034. imageList: this.imageList,
  16035. drawingFile: drawingFile,
  16036. drawingRelsFile: drawingRelsFile,
  16037. hide: hide
  16038. });
  16039. this.columnWidthSet = [];
  16040. this.rowHeightSet = [];
  16041. this.imagePositionCaculation(sheet_1);
  16042. this.sheets.push(sheet_1);
  16043. order++;
  16044. }
  16045. }
  16046. console.log(this.sheets);
  16047. };
  16048. LuckyFile.prototype.extendArray = function (index, sets, def, hidden, lens) {
  16049. if (index < sets.length) {
  16050. return;
  16051. }
  16052. var startIndex = sets.length,
  16053. endIndex = index;
  16054. var allGap = 0;
  16055. if (startIndex > 0) {
  16056. allGap = sets[startIndex - 1];
  16057. } // else{
  16058. // sets.push(0);
  16059. // }
  16060. for (var i = startIndex; i <= endIndex; i++) {
  16061. var gap = def,
  16062. istring = i.toString();
  16063. if (istring in hidden) {
  16064. gap = 0;
  16065. } else if (istring in lens) {
  16066. gap = lens[istring];
  16067. }
  16068. allGap += Math.round(gap + 1);
  16069. sets.push(allGap);
  16070. }
  16071. };
  16072. LuckyFile.prototype.imagePositionCaculation = function (sheet) {
  16073. var images = sheet.images,
  16074. defaultColWidth = sheet.defaultColWidth,
  16075. defaultRowHeight = sheet.defaultRowHeight;
  16076. var colhidden = {};
  16077. if (sheet.config.colhidden) {
  16078. colhidden = sheet.config.colhidden;
  16079. }
  16080. var columnlen = {};
  16081. if (sheet.config.columnlen) {
  16082. columnlen = sheet.config.columnlen;
  16083. }
  16084. var rowhidden = {};
  16085. if (sheet.config.rowhidden) {
  16086. rowhidden = sheet.config.rowhidden;
  16087. }
  16088. var rowlen = {};
  16089. if (sheet.config.rowlen) {
  16090. rowlen = sheet.config.rowlen;
  16091. }
  16092. for (var key in images) {
  16093. var imageObject = images[key]; //Image, luckyImage
  16094. var fromCol = imageObject.fromCol;
  16095. var fromColOff = imageObject.fromColOff;
  16096. var fromRow = imageObject.fromRow;
  16097. var fromRowOff = imageObject.fromRowOff;
  16098. var toCol = imageObject.toCol;
  16099. var toColOff = imageObject.toColOff;
  16100. var toRow = imageObject.toRow;
  16101. var toRowOff = imageObject.toRowOff;
  16102. var x_n = 0,
  16103. y_n = 0;
  16104. var cx_n = 0,
  16105. cy_n = 0;
  16106. if (fromCol >= this.columnWidthSet.length) {
  16107. this.extendArray(fromCol, this.columnWidthSet, defaultColWidth, colhidden, columnlen);
  16108. }
  16109. if (fromCol == 0) {
  16110. x_n = 0;
  16111. } else {
  16112. x_n = this.columnWidthSet[fromCol - 1];
  16113. }
  16114. x_n = x_n + fromColOff;
  16115. if (fromRow >= this.rowHeightSet.length) {
  16116. this.extendArray(fromRow, this.rowHeightSet, defaultRowHeight, rowhidden, rowlen);
  16117. }
  16118. if (fromRow == 0) {
  16119. y_n = 0;
  16120. } else {
  16121. y_n = this.rowHeightSet[fromRow - 1];
  16122. }
  16123. y_n = y_n + fromRowOff;
  16124. if (toCol >= this.columnWidthSet.length) {
  16125. this.extendArray(toCol, this.columnWidthSet, defaultColWidth, colhidden, columnlen);
  16126. }
  16127. if (toCol == 0) {
  16128. cx_n = 0;
  16129. } else {
  16130. cx_n = this.columnWidthSet[toCol - 1];
  16131. }
  16132. cx_n = cx_n + toColOff - x_n;
  16133. if (toRow >= this.rowHeightSet.length) {
  16134. this.extendArray(toRow, this.rowHeightSet, defaultRowHeight, rowhidden, rowlen);
  16135. }
  16136. if (toRow == 0) {
  16137. cy_n = 0;
  16138. } else {
  16139. cy_n = this.rowHeightSet[toRow - 1];
  16140. }
  16141. cy_n = cy_n + toRowOff - y_n;
  16142. console.log(defaultColWidth, colhidden, columnlen);
  16143. console.log(fromCol, this.columnWidthSet[fromCol], fromColOff);
  16144. console.log(toCol, this.columnWidthSet[toCol], toColOff, JSON.stringify(this.columnWidthSet));
  16145. imageObject.originWidth = cx_n;
  16146. imageObject.originHeight = cy_n;
  16147. imageObject.crop.height = cy_n;
  16148. imageObject.crop.width = cx_n;
  16149. imageObject["default"].height = cy_n;
  16150. imageObject["default"].left = x_n;
  16151. imageObject["default"].top = y_n;
  16152. imageObject["default"].width = cx_n;
  16153. } //console.log(this.columnWidthSet, this.rowHeightSet);
  16154. };
  16155. /**
  16156. * @return drawing file string
  16157. */
  16158. LuckyFile.prototype.getDrawingFile = function (rid, sheetFile) {
  16159. var sheetRelsPath = "xl/worksheets/_rels/";
  16160. var sheetFileArr = sheetFile.split("/");
  16161. var sheetRelsName = sheetFileArr[sheetFileArr.length - 1];
  16162. var sheetRelsFile = sheetRelsPath + sheetRelsName + ".rels";
  16163. var drawing = this.readXml.getElementsByTagName("Relationships/Relationship", sheetRelsFile);
  16164. if (drawing.length > 0) {
  16165. for (var i = 0; i < drawing.length; i++) {
  16166. var relationship = drawing[i];
  16167. var attrList = relationship.attributeList;
  16168. var relationshipId = method_1.getXmlAttibute(attrList, "Id", null);
  16169. if (relationshipId == rid) {
  16170. var target = method_1.getXmlAttibute(attrList, "Target", null);
  16171. if (target != null) {
  16172. return target.replace(/\.\.\//g, "");
  16173. }
  16174. }
  16175. }
  16176. }
  16177. return null;
  16178. };
  16179. LuckyFile.prototype.getDrawingRelsFile = function (drawingFile) {
  16180. var drawingRelsPath = "xl/drawings/_rels/";
  16181. var drawingFileArr = drawingFile.split("/");
  16182. var drawingRelsName = drawingFileArr[drawingFileArr.length - 1];
  16183. var drawingRelsFile = drawingRelsPath + drawingRelsName + ".rels";
  16184. return drawingRelsFile;
  16185. };
  16186. /**
  16187. * @return All sheet base information widthout cell and config
  16188. */
  16189. LuckyFile.prototype.getSheetsWithoutCell = function () {
  16190. this.getSheetsFull(false);
  16191. };
  16192. /**
  16193. * @return LuckySheet file json
  16194. */
  16195. LuckyFile.prototype.Parse = function () {
  16196. // let xml = this.readXml;
  16197. // for(let key in this.sheetNameList){
  16198. // let sheetName=this.sheetNameList[key];
  16199. // let sheetColumns = xml.getElementsByTagName("row/c/f", sheetName);
  16200. // console.log(sheetColumns);
  16201. // }
  16202. // return "";
  16203. this.getWorkBookInfo();
  16204. this.getSheetsFull(); // for(let i=0;i<this.sheets.length;i++){
  16205. // let sheet = this.sheets[i];
  16206. // let _borderInfo = sheet.config._borderInfo;
  16207. // if(_borderInfo==null){
  16208. // continue;
  16209. // }
  16210. // let _borderInfoKeys = Object.keys(_borderInfo);
  16211. // _borderInfoKeys.sort();
  16212. // for(let a=0;a<_borderInfoKeys.length;a++){
  16213. // let key = parseInt(_borderInfoKeys[a]);
  16214. // let b = _borderInfo[key];
  16215. // if(b.cells.length==0){
  16216. // continue;
  16217. // }
  16218. // if(sheet.config.borderInfo==null){
  16219. // sheet.config.borderInfo = [];
  16220. // }
  16221. // sheet.config.borderInfo.push(b);
  16222. // }
  16223. // }
  16224. return this.toJsonString(this);
  16225. };
  16226. LuckyFile.prototype.toJsonString = function (file) {
  16227. var LuckyOutPutFile = new LuckyBase_1.LuckyFileBase();
  16228. LuckyOutPutFile.info = file.info;
  16229. LuckyOutPutFile.sheets = [];
  16230. file.sheets.forEach(function (sheet) {
  16231. var sheetout = new LuckyBase_1.LuckySheetBase(); //let attrName = ["name","color","config","index","status","order","row","column","luckysheet_select_save","scrollLeft","scrollTop","zoomRatio","showGridLines","defaultColWidth","defaultRowHeight","celldata","chart","isPivotTable","pivotTable","luckysheet_conditionformat_save","freezen","calcChain"];
  16232. if (sheet.name != null) {
  16233. sheetout.name = sheet.name;
  16234. }
  16235. if (sheet.color != null) {
  16236. sheetout.color = sheet.color;
  16237. }
  16238. if (sheet.config != null) {
  16239. sheetout.config = sheet.config; // if(sheetout.config._borderInfo!=null){
  16240. // delete sheetout.config._borderInfo;
  16241. // }
  16242. }
  16243. if (sheet.index != null) {
  16244. sheetout.index = sheet.index;
  16245. }
  16246. if (sheet.status != null) {
  16247. sheetout.status = sheet.status;
  16248. }
  16249. if (sheet.order != null) {
  16250. sheetout.order = sheet.order;
  16251. }
  16252. if (sheet.row != null) {
  16253. sheetout.row = sheet.row;
  16254. }
  16255. if (sheet.column != null) {
  16256. sheetout.column = sheet.column;
  16257. }
  16258. if (sheet.luckysheet_select_save != null) {
  16259. sheetout.luckysheet_select_save = sheet.luckysheet_select_save;
  16260. }
  16261. if (sheet.scrollLeft != null) {
  16262. sheetout.scrollLeft = sheet.scrollLeft;
  16263. }
  16264. if (sheet.scrollTop != null) {
  16265. sheetout.scrollTop = sheet.scrollTop;
  16266. }
  16267. if (sheet.zoomRatio != null) {
  16268. sheetout.zoomRatio = sheet.zoomRatio;
  16269. }
  16270. if (sheet.showGridLines != null) {
  16271. sheetout.showGridLines = sheet.showGridLines;
  16272. }
  16273. if (sheet.defaultColWidth != null) {
  16274. sheetout.defaultColWidth = sheet.defaultColWidth;
  16275. }
  16276. if (sheet.defaultRowHeight != null) {
  16277. sheetout.defaultRowHeight = sheet.defaultRowHeight;
  16278. }
  16279. if (sheet.celldata != null) {
  16280. // sheetout.celldata = sheet.celldata;
  16281. sheetout.celldata = [];
  16282. sheet.celldata.forEach(function (cell) {
  16283. var cellout = new LuckyBase_1.LuckySheetCelldataBase();
  16284. cellout.r = cell.r;
  16285. cellout.c = cell.c;
  16286. cellout.v = cell.v;
  16287. sheetout.celldata.push(cellout);
  16288. });
  16289. }
  16290. if (sheet.chart != null) {
  16291. sheetout.chart = sheet.chart;
  16292. }
  16293. if (sheet.isPivotTable != null) {
  16294. sheetout.isPivotTable = sheet.isPivotTable;
  16295. }
  16296. if (sheet.pivotTable != null) {
  16297. sheetout.pivotTable = sheet.pivotTable;
  16298. }
  16299. if (sheet.luckysheet_conditionformat_save != null) {
  16300. sheetout.luckysheet_conditionformat_save = sheet.luckysheet_conditionformat_save;
  16301. }
  16302. if (sheet.freezen != null) {
  16303. sheetout.freezen = sheet.freezen;
  16304. }
  16305. if (sheet.calcChain != null) {
  16306. sheetout.calcChain = sheet.calcChain;
  16307. }
  16308. if (sheet.images != null) {
  16309. sheetout.images = sheet.images;
  16310. }
  16311. if (sheet.dataVerification != null) {
  16312. sheetout.dataVerification = sheet.dataVerification;
  16313. }
  16314. if (sheet.hyperlink != null) {
  16315. sheetout.hyperlink = sheet.hyperlink;
  16316. }
  16317. if (sheet.hide != null) {
  16318. sheetout.hide = sheet.hide;
  16319. }
  16320. LuckyOutPutFile.sheets.push(sheetout);
  16321. });
  16322. return JSON.stringify(LuckyOutPutFile);
  16323. };
  16324. return LuckyFile;
  16325. }(LuckyBase_1.LuckyFileBase);
  16326. exports.LuckyFile = LuckyFile;
  16327. },{"../common/constant":92,"../common/method":94,"./LuckyBase":86,"./LuckyImage":89,"./LuckySheet":90,"./ReadXml":91}],89:[function(require,module,exports){
  16328. "use strict";
  16329. var __extends = void 0 && (void 0).__extends || function () {
  16330. var _extendStatics = function extendStatics(d, b) {
  16331. _extendStatics = Object.setPrototypeOf || {
  16332. __proto__: []
  16333. } instanceof Array && function (d, b) {
  16334. d.__proto__ = b;
  16335. } || function (d, b) {
  16336. for (var p in b) {
  16337. if (b.hasOwnProperty(p)) d[p] = b[p];
  16338. }
  16339. };
  16340. return _extendStatics(d, b);
  16341. };
  16342. return function (d, b) {
  16343. _extendStatics(d, b);
  16344. function __() {
  16345. this.constructor = d;
  16346. }
  16347. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16348. };
  16349. }();
  16350. Object.defineProperty(exports, "__esModule", {
  16351. value: true
  16352. });
  16353. exports.ImageList = void 0;
  16354. var LuckyBase_1 = require("./LuckyBase");
  16355. var emf_1 = require("../common/emf");
  16356. var ImageList =
  16357. /** @class */
  16358. function () {
  16359. function ImageList(files) {
  16360. if (files == null) {
  16361. return;
  16362. }
  16363. this.images = {};
  16364. for (var fileKey in files) {
  16365. // let reg = new RegExp("xl/media/image1.png", "g");
  16366. if (fileKey.indexOf("xl/media/") > -1) {
  16367. var fileNameArr = fileKey.split(".");
  16368. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  16369. if (suffix in {
  16370. "png": 1,
  16371. "jpeg": 1,
  16372. "jpg": 1,
  16373. "gif": 1,
  16374. "bmp": 1,
  16375. "tif": 1,
  16376. "webp": 1,
  16377. "emf": 1
  16378. }) {
  16379. if (suffix == "emf") {
  16380. var pNum = 0; // number of the page, that you want to render
  16381. var scale = 1; // the scale of the document
  16382. var wrt = new emf_1.ToContext2D(pNum, scale);
  16383. var inp, out, stt;
  16384. emf_1.FromEMF.K = [];
  16385. inp = emf_1.FromEMF.C;
  16386. out = emf_1.FromEMF.K;
  16387. stt = 4;
  16388. for (var p in inp) {
  16389. out[inp[p]] = p.slice(stt);
  16390. }
  16391. emf_1.FromEMF.Parse(files[fileKey], wrt);
  16392. this.images[fileKey] = wrt.canvas.toDataURL("image/png");
  16393. } else {
  16394. this.images[fileKey] = files[fileKey];
  16395. }
  16396. }
  16397. }
  16398. }
  16399. }
  16400. ImageList.prototype.getImageByName = function (pathName) {
  16401. if (pathName in this.images) {
  16402. var base64 = this.images[pathName];
  16403. return new Image(pathName, base64);
  16404. }
  16405. return null;
  16406. };
  16407. return ImageList;
  16408. }();
  16409. exports.ImageList = ImageList;
  16410. var Image =
  16411. /** @class */
  16412. function (_super) {
  16413. __extends(Image, _super);
  16414. function Image(pathName, base64) {
  16415. var _this = _super.call(this) || this;
  16416. _this.src = base64;
  16417. return _this;
  16418. }
  16419. Image.prototype.setDefault = function () {};
  16420. return Image;
  16421. }(LuckyBase_1.LuckyImageBase);
  16422. },{"../common/emf":93,"./LuckyBase":86}],90:[function(require,module,exports){
  16423. "use strict";
  16424. var __extends = void 0 && (void 0).__extends || function () {
  16425. var _extendStatics = function extendStatics(d, b) {
  16426. _extendStatics = Object.setPrototypeOf || {
  16427. __proto__: []
  16428. } instanceof Array && function (d, b) {
  16429. d.__proto__ = b;
  16430. } || function (d, b) {
  16431. for (var p in b) {
  16432. if (b.hasOwnProperty(p)) d[p] = b[p];
  16433. }
  16434. };
  16435. return _extendStatics(d, b);
  16436. };
  16437. return function (d, b) {
  16438. _extendStatics(d, b);
  16439. function __() {
  16440. this.constructor = d;
  16441. }
  16442. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16443. };
  16444. }();
  16445. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  16446. return mod && mod.__esModule ? mod : {
  16447. "default": mod
  16448. };
  16449. };
  16450. Object.defineProperty(exports, "__esModule", {
  16451. value: true
  16452. });
  16453. exports.LuckySheet = void 0;
  16454. var LuckyCell_1 = require("./LuckyCell");
  16455. var method_1 = require("../common/method");
  16456. var constant_1 = require("../common/constant");
  16457. var ReadXml_1 = require("./ReadXml");
  16458. var LuckyBase_1 = require("./LuckyBase");
  16459. var dayjs_1 = __importDefault(require("dayjs"));
  16460. var LuckySheet =
  16461. /** @class */
  16462. function (_super) {
  16463. __extends(LuckySheet, _super);
  16464. function LuckySheet(sheetName, sheetId, sheetOrder, isInitialCell, allFileOption) {
  16465. if (isInitialCell === void 0) {
  16466. isInitialCell = false;
  16467. }
  16468. var _this = //Private
  16469. _super.call(this) || this;
  16470. _this.isInitialCell = isInitialCell;
  16471. _this.readXml = allFileOption.readXml;
  16472. _this.sheetFile = allFileOption.sheetFile;
  16473. _this.styles = allFileOption.styles;
  16474. _this.sharedStrings = allFileOption.sharedStrings;
  16475. _this.calcChainEles = allFileOption.calcChain;
  16476. _this.sheetList = allFileOption.sheetList;
  16477. _this.imageList = allFileOption.imageList;
  16478. _this.hide = allFileOption.hide; //Output
  16479. _this.name = sheetName;
  16480. _this.index = sheetId;
  16481. _this.order = sheetOrder.toString();
  16482. _this.config = new LuckyBase_1.LuckyConfig();
  16483. _this.celldata = [];
  16484. _this.mergeCells = _this.readXml.getElementsByTagName("mergeCells/mergeCell", _this.sheetFile);
  16485. var clrScheme = _this.styles["clrScheme"];
  16486. var sheetView = _this.readXml.getElementsByTagName("sheetViews/sheetView", _this.sheetFile);
  16487. var showGridLines = "1",
  16488. tabSelected = "0",
  16489. zoomScale = "100",
  16490. activeCell = "A1";
  16491. if (sheetView.length > 0) {
  16492. var attrList = sheetView[0].attributeList;
  16493. showGridLines = method_1.getXmlAttibute(attrList, "showGridLines", "1");
  16494. tabSelected = method_1.getXmlAttibute(attrList, "tabSelected", "0");
  16495. zoomScale = method_1.getXmlAttibute(attrList, "zoomScale", "100"); // let colorId = getXmlAttibute(attrList, "colorId", "0");
  16496. var selections = sheetView[0].getInnerElements("selection");
  16497. if (selections != null && selections.length > 0) {
  16498. activeCell = method_1.getXmlAttibute(selections[0].attributeList, "activeCell", "A1");
  16499. var range = method_1.getcellrange(activeCell, _this.sheetList, sheetId);
  16500. _this.luckysheet_select_save = [];
  16501. _this.luckysheet_select_save.push(range);
  16502. }
  16503. }
  16504. _this.showGridLines = showGridLines;
  16505. _this.status = tabSelected;
  16506. _this.zoomRatio = parseInt(zoomScale) / 100;
  16507. var tabColors = _this.readXml.getElementsByTagName("sheetPr/tabColor", _this.sheetFile);
  16508. if (tabColors != null && tabColors.length > 0) {
  16509. var tabColor = tabColors[0],
  16510. attrList = tabColor.attributeList; // if(attrList.rgb!=null){
  16511. var tc = ReadXml_1.getColor(tabColor, _this.styles, "b");
  16512. _this.color = tc; // }
  16513. }
  16514. var sheetFormatPr = _this.readXml.getElementsByTagName("sheetFormatPr", _this.sheetFile);
  16515. var defaultColWidth, defaultRowHeight;
  16516. if (sheetFormatPr.length > 0) {
  16517. var attrList = sheetFormatPr[0].attributeList;
  16518. defaultColWidth = method_1.getXmlAttibute(attrList, "defaultColWidth", "9.21");
  16519. defaultRowHeight = method_1.getXmlAttibute(attrList, "defaultRowHeight", "19");
  16520. }
  16521. _this.defaultColWidth = method_1.getColumnWidthPixel(parseFloat(defaultColWidth));
  16522. _this.defaultRowHeight = method_1.getRowHeightPixel(parseFloat(defaultRowHeight));
  16523. _this.generateConfigColumnLenAndHidden();
  16524. var cellOtherInfo = _this.generateConfigRowLenAndHiddenAddCell();
  16525. if (_this.calcChain == null) {
  16526. _this.calcChain = [];
  16527. }
  16528. var formulaListExist = {};
  16529. for (var c = 0; c < _this.calcChainEles.length; c++) {
  16530. var calcChainEle = _this.calcChainEles[c],
  16531. attrList = calcChainEle.attributeList;
  16532. if (attrList.i != sheetId) {
  16533. continue;
  16534. }
  16535. var r = attrList.r,
  16536. i = attrList.i,
  16537. l = attrList.l,
  16538. s = attrList.s,
  16539. a = attrList.a,
  16540. t = attrList.t;
  16541. var range = method_1.getcellrange(r);
  16542. var chain = new LuckyBase_1.LuckysheetCalcChain();
  16543. chain.r = range.row[0];
  16544. chain.c = range.column[0];
  16545. chain.index = _this.index;
  16546. _this.calcChain.push(chain);
  16547. formulaListExist["r" + r + "c" + c] = null;
  16548. }
  16549. if (_this.formulaRefList != null) {
  16550. for (var key in _this.formulaRefList) {
  16551. var funclist = _this.formulaRefList[key];
  16552. var mainFunc = funclist["mainRef"],
  16553. mainCellValue = mainFunc.cellValue;
  16554. var formulaTxt = mainFunc.fv;
  16555. var mainR = mainCellValue.r,
  16556. mainC = mainCellValue.c; // let refRange = getcellrange(ref);
  16557. for (var name_1 in funclist) {
  16558. if (name_1 == "mainRef") {
  16559. continue;
  16560. }
  16561. var funcValue = funclist[name_1],
  16562. cellValue = funcValue.cellValue;
  16563. if (cellValue == null) {
  16564. continue;
  16565. }
  16566. var r = cellValue.r,
  16567. c = cellValue.c;
  16568. var func = formulaTxt;
  16569. var offsetRow = r - mainR,
  16570. offsetCol = c - mainC;
  16571. if (offsetRow > 0) {
  16572. func = "=" + method_1.fromulaRef.functionCopy(func, "down", offsetRow);
  16573. } else if (offsetRow < 0) {
  16574. func = "=" + method_1.fromulaRef.functionCopy(func, "up", Math.abs(offsetRow));
  16575. }
  16576. if (offsetCol > 0) {
  16577. func = "=" + method_1.fromulaRef.functionCopy(func, "right", offsetCol);
  16578. } else if (offsetCol < 0) {
  16579. func = "=" + method_1.fromulaRef.functionCopy(func, "left", Math.abs(offsetCol));
  16580. } // console.log(offsetRow, offsetCol, func);
  16581. cellValue.v.f = func; //添加共享公式链
  16582. var chain = new LuckyBase_1.LuckysheetCalcChain();
  16583. chain.r = cellValue.r;
  16584. chain.c = cellValue.c;
  16585. chain.index = _this.index;
  16586. _this.calcChain.push(chain);
  16587. }
  16588. }
  16589. } //There may be formulas that do not appear in calcChain
  16590. for (var key in cellOtherInfo.formulaList) {
  16591. if (!(key in formulaListExist)) {
  16592. var formulaListItem = cellOtherInfo.formulaList[key];
  16593. var chain = new LuckyBase_1.LuckysheetCalcChain();
  16594. chain.r = formulaListItem.r;
  16595. chain.c = formulaListItem.c;
  16596. chain.index = _this.index;
  16597. _this.calcChain.push(chain);
  16598. }
  16599. } // dataVerification config
  16600. _this.dataVerification = _this.generateConfigDataValidations(); // hyperlink config
  16601. _this.hyperlink = _this.generateConfigHyperlinks(); // sheet hide
  16602. _this.hide = _this.hide;
  16603. if (_this.mergeCells != null) {
  16604. for (var i = 0; i < _this.mergeCells.length; i++) {
  16605. var merge = _this.mergeCells[i],
  16606. attrList = merge.attributeList;
  16607. var ref = attrList.ref;
  16608. if (ref == null) {
  16609. continue;
  16610. }
  16611. var range = method_1.getcellrange(ref, _this.sheetList, sheetId);
  16612. var mergeValue = new LuckyBase_1.LuckySheetConfigMerge();
  16613. mergeValue.r = range.row[0];
  16614. mergeValue.c = range.column[0];
  16615. mergeValue.rs = range.row[1] - range.row[0] + 1;
  16616. mergeValue.cs = range.column[1] - range.column[0] + 1;
  16617. if (_this.config.merge == null) {
  16618. _this.config.merge = {};
  16619. }
  16620. _this.config.merge[range.row[0] + "_" + range.column[0]] = mergeValue;
  16621. }
  16622. }
  16623. var drawingFile = allFileOption.drawingFile,
  16624. drawingRelsFile = allFileOption.drawingRelsFile;
  16625. if (drawingFile != null && drawingRelsFile != null) {
  16626. var twoCellAnchors = _this.readXml.getElementsByTagName("xdr:twoCellAnchor", drawingFile);
  16627. if (twoCellAnchors != null && twoCellAnchors.length > 0) {
  16628. for (var i = 0; i < twoCellAnchors.length; i++) {
  16629. var twoCellAnchor = twoCellAnchors[i];
  16630. var editAs = method_1.getXmlAttibute(twoCellAnchor.attributeList, "editAs", "twoCell");
  16631. var xdrFroms = twoCellAnchor.getInnerElements("xdr:from"),
  16632. xdrTos = twoCellAnchor.getInnerElements("xdr:to");
  16633. var xdr_blipfills = twoCellAnchor.getInnerElements("a:blip");
  16634. if (xdrFroms != null && xdr_blipfills != null && xdrFroms.length > 0 && xdr_blipfills.length > 0) {
  16635. var xdrFrom = xdrFroms[0],
  16636. xdrTo = xdrTos[0],
  16637. xdr_blipfill = xdr_blipfills[0];
  16638. var rembed = method_1.getXmlAttibute(xdr_blipfill.attributeList, "r:embed", null);
  16639. var imageObject = _this.getBase64ByRid(rembed, drawingRelsFile); // let aoff = xdr_xfrm.getInnerElements("a:off"), aext = xdr_xfrm.getInnerElements("a:ext");
  16640. // if(aoff!=null && aext!=null && aoff.length>0 && aext.length>0){
  16641. // let aoffAttribute = aoff[0].attributeList, aextAttribute = aext[0].attributeList;
  16642. // let x = getXmlAttibute(aoffAttribute, "x", null);
  16643. // let y = getXmlAttibute(aoffAttribute, "y", null);
  16644. // let cx = getXmlAttibute(aextAttribute, "cx", null);
  16645. // let cy = getXmlAttibute(aextAttribute, "cy", null);
  16646. // if(x!=null && y!=null && cx!=null && cy!=null && imageObject !=null){
  16647. // let x_n = getPxByEMUs(parseInt(x), "c"),y_n = getPxByEMUs(parseInt(y));
  16648. // let cx_n = getPxByEMUs(parseInt(cx), "c"),cy_n = getPxByEMUs(parseInt(cy));
  16649. var x_n = 0,
  16650. y_n = 0;
  16651. var cx_n = 0,
  16652. cy_n = 0;
  16653. imageObject.fromCol = _this.getXdrValue(xdrFrom.getInnerElements("xdr:col"));
  16654. imageObject.fromColOff = method_1.getPxByEMUs(_this.getXdrValue(xdrFrom.getInnerElements("xdr:colOff")));
  16655. imageObject.fromRow = _this.getXdrValue(xdrFrom.getInnerElements("xdr:row"));
  16656. imageObject.fromRowOff = method_1.getPxByEMUs(_this.getXdrValue(xdrFrom.getInnerElements("xdr:rowOff")));
  16657. imageObject.toCol = _this.getXdrValue(xdrTo.getInnerElements("xdr:col"));
  16658. imageObject.toColOff = method_1.getPxByEMUs(_this.getXdrValue(xdrTo.getInnerElements("xdr:colOff")));
  16659. imageObject.toRow = _this.getXdrValue(xdrTo.getInnerElements("xdr:row"));
  16660. imageObject.toRowOff = method_1.getPxByEMUs(_this.getXdrValue(xdrTo.getInnerElements("xdr:rowOff")));
  16661. imageObject.originWidth = cx_n;
  16662. imageObject.originHeight = cy_n;
  16663. if (editAs == "absolute") {
  16664. imageObject.type = "3";
  16665. } else if (editAs == "oneCell") {
  16666. imageObject.type = "2";
  16667. } else {
  16668. imageObject.type = "1";
  16669. }
  16670. imageObject.isFixedPos = false;
  16671. imageObject.fixedLeft = 0;
  16672. imageObject.fixedTop = 0;
  16673. var imageBorder = {
  16674. color: "#000",
  16675. radius: 0,
  16676. style: "solid",
  16677. width: 0
  16678. };
  16679. imageObject.border = imageBorder;
  16680. var imageCrop = {
  16681. height: cy_n,
  16682. offsetLeft: 0,
  16683. offsetTop: 0,
  16684. width: cx_n
  16685. };
  16686. imageObject.crop = imageCrop;
  16687. var imageDefault = {
  16688. height: cy_n,
  16689. left: x_n,
  16690. top: y_n,
  16691. width: cx_n
  16692. };
  16693. imageObject["default"] = imageDefault;
  16694. if (_this.images == null) {
  16695. _this.images = {};
  16696. }
  16697. _this.images[method_1.generateRandomIndex("image")] = imageObject; // }
  16698. // }
  16699. }
  16700. }
  16701. }
  16702. }
  16703. return _this;
  16704. }
  16705. LuckySheet.prototype.getXdrValue = function (ele) {
  16706. if (ele == null || ele.length == 0) {
  16707. return null;
  16708. }
  16709. return parseInt(ele[0].value);
  16710. };
  16711. LuckySheet.prototype.getBase64ByRid = function (rid, drawingRelsFile) {
  16712. var Relationships = this.readXml.getElementsByTagName("Relationships/Relationship", drawingRelsFile);
  16713. if (Relationships != null && Relationships.length > 0) {
  16714. for (var i = 0; i < Relationships.length; i++) {
  16715. var Relationship = Relationships[i];
  16716. var attrList = Relationship.attributeList;
  16717. var Id = method_1.getXmlAttibute(attrList, "Id", null);
  16718. var src = method_1.getXmlAttibute(attrList, "Target", null);
  16719. if (Id == rid) {
  16720. src = src.replace(/\.\.\//g, "");
  16721. src = "xl/" + src;
  16722. var imgage = this.imageList.getImageByName(src);
  16723. return imgage;
  16724. }
  16725. }
  16726. }
  16727. return null;
  16728. };
  16729. /**
  16730. * @desc This will convert cols/col to luckysheet config of column'width
  16731. */
  16732. LuckySheet.prototype.generateConfigColumnLenAndHidden = function () {
  16733. var cols = this.readXml.getElementsByTagName("cols/col", this.sheetFile);
  16734. for (var i = 0; i < cols.length; i++) {
  16735. var col = cols[i],
  16736. attrList = col.attributeList;
  16737. var min = method_1.getXmlAttibute(attrList, "min", null);
  16738. var max = method_1.getXmlAttibute(attrList, "max", null);
  16739. var width = method_1.getXmlAttibute(attrList, "width", null);
  16740. var hidden = method_1.getXmlAttibute(attrList, "hidden", null);
  16741. var customWidth = method_1.getXmlAttibute(attrList, "customWidth", null);
  16742. if (min == null || max == null) {
  16743. continue;
  16744. }
  16745. var minNum = parseInt(min) - 1,
  16746. maxNum = parseInt(max) - 1,
  16747. widthNum = parseFloat(width);
  16748. for (var m = minNum; m <= maxNum; m++) {
  16749. if (width != null) {
  16750. if (this.config.columnlen == null) {
  16751. this.config.columnlen = {};
  16752. }
  16753. this.config.columnlen[m] = method_1.getColumnWidthPixel(widthNum);
  16754. }
  16755. if (hidden == "1") {
  16756. if (this.config.colhidden == null) {
  16757. this.config.colhidden = {};
  16758. }
  16759. this.config.colhidden[m] = 0;
  16760. if (this.config.columnlen) {
  16761. delete this.config.columnlen[m];
  16762. }
  16763. }
  16764. if (customWidth != null) {
  16765. if (this.config.customWidth == null) {
  16766. this.config.customWidth = {};
  16767. }
  16768. this.config.customWidth[m] = 1;
  16769. }
  16770. }
  16771. }
  16772. };
  16773. /**
  16774. * @desc This will convert cols/col to luckysheet config of column'width
  16775. */
  16776. LuckySheet.prototype.generateConfigRowLenAndHiddenAddCell = function () {
  16777. var rows = this.readXml.getElementsByTagName("sheetData/row", this.sheetFile);
  16778. var cellOtherInfo = {};
  16779. var formulaList = {};
  16780. cellOtherInfo.formulaList = formulaList;
  16781. for (var i = 0; i < rows.length; i++) {
  16782. var row = rows[i],
  16783. attrList = row.attributeList;
  16784. var rowNo = method_1.getXmlAttibute(attrList, "r", null);
  16785. var height = method_1.getXmlAttibute(attrList, "ht", null);
  16786. var hidden = method_1.getXmlAttibute(attrList, "hidden", null);
  16787. var customHeight = method_1.getXmlAttibute(attrList, "customHeight", null);
  16788. if (rowNo == null) {
  16789. continue;
  16790. }
  16791. var rowNoNum = parseInt(rowNo) - 1;
  16792. if (height != null) {
  16793. var heightNum = parseFloat(height);
  16794. if (this.config.rowlen == null) {
  16795. this.config.rowlen = {};
  16796. }
  16797. this.config.rowlen[rowNoNum] = method_1.getRowHeightPixel(heightNum);
  16798. }
  16799. if (hidden == "1") {
  16800. if (this.config.rowhidden == null) {
  16801. this.config.rowhidden = {};
  16802. }
  16803. this.config.rowhidden[rowNoNum] = 0;
  16804. if (this.config.rowlen) {
  16805. delete this.config.rowlen[rowNoNum];
  16806. }
  16807. }
  16808. if (customHeight != null) {
  16809. if (this.config.customHeight == null) {
  16810. this.config.customHeight = {};
  16811. }
  16812. this.config.customHeight[rowNoNum] = 1;
  16813. }
  16814. if (this.isInitialCell) {
  16815. var cells = row.getInnerElements("c");
  16816. for (var key in cells) {
  16817. var cell = cells[key];
  16818. var cellValue = new LuckyCell_1.LuckySheetCelldata(cell, this.styles, this.sharedStrings, this.mergeCells, this.sheetFile, this.readXml);
  16819. if (cellValue._borderObject != null) {
  16820. if (this.config.borderInfo == null) {
  16821. this.config.borderInfo = [];
  16822. }
  16823. this.config.borderInfo.push(cellValue._borderObject);
  16824. delete cellValue._borderObject;
  16825. } // let borderId = cellValue._borderId;
  16826. // if(borderId!=null){
  16827. // let borders = this.styles["borders"] as Element[];
  16828. // if(this.config._borderInfo==null){
  16829. // this.config._borderInfo = {};
  16830. // }
  16831. // if( borderId in this.config._borderInfo){
  16832. // this.config._borderInfo[borderId].cells.push(cellValue.r + "_" + cellValue.c);
  16833. // }
  16834. // else{
  16835. // let border = borders[borderId];
  16836. // let borderObject = new LuckySheetborderInfoCellForImp();
  16837. // borderObject.rangeType = "cellGroup";
  16838. // borderObject.cells = [];
  16839. // let borderCellValue = new LuckySheetborderInfoCellValue();
  16840. // let lefts = border.getInnerElements("left");
  16841. // let rights = border.getInnerElements("right");
  16842. // let tops = border.getInnerElements("top");
  16843. // let bottoms = border.getInnerElements("bottom");
  16844. // let diagonals = border.getInnerElements("diagonal");
  16845. // let left = this.getBorderInfo(lefts);
  16846. // let right = this.getBorderInfo(rights);
  16847. // let top = this.getBorderInfo(tops);
  16848. // let bottom = this.getBorderInfo(bottoms);
  16849. // let diagonal = this.getBorderInfo(diagonals);
  16850. // let isAdd = false;
  16851. // if(left!=null && left.color!=null){
  16852. // borderCellValue.l = left;
  16853. // isAdd = true;
  16854. // }
  16855. // if(right!=null && right.color!=null){
  16856. // borderCellValue.r = right;
  16857. // isAdd = true;
  16858. // }
  16859. // if(top!=null && top.color!=null){
  16860. // borderCellValue.t = top;
  16861. // isAdd = true;
  16862. // }
  16863. // if(bottom!=null && bottom.color!=null){
  16864. // borderCellValue.b = bottom;
  16865. // isAdd = true;
  16866. // }
  16867. // if(isAdd){
  16868. // borderObject.value = borderCellValue;
  16869. // this.config._borderInfo[borderId] = borderObject;
  16870. // }
  16871. // }
  16872. // }
  16873. if (cellValue._formulaType == "shared") {
  16874. if (this.formulaRefList == null) {
  16875. this.formulaRefList = {};
  16876. }
  16877. if (this.formulaRefList[cellValue._formulaSi] == null) {
  16878. this.formulaRefList[cellValue._formulaSi] = {};
  16879. }
  16880. var fv = void 0;
  16881. if (cellValue.v != null) {
  16882. fv = cellValue.v.f;
  16883. }
  16884. var refValue = {
  16885. t: cellValue._formulaType,
  16886. ref: cellValue._fomulaRef,
  16887. si: cellValue._formulaSi,
  16888. fv: fv,
  16889. cellValue: cellValue
  16890. };
  16891. if (cellValue._fomulaRef != null) {
  16892. this.formulaRefList[cellValue._formulaSi]["mainRef"] = refValue;
  16893. } else {
  16894. this.formulaRefList[cellValue._formulaSi][cellValue.r + "_" + cellValue.c] = refValue;
  16895. } // console.log(refValue, this.formulaRefList);
  16896. } //There may be formulas that do not appear in calcChain
  16897. if (cellValue.v != null && cellValue.v.f != null) {
  16898. var formulaCell = {
  16899. r: cellValue.r,
  16900. c: cellValue.c
  16901. };
  16902. cellOtherInfo.formulaList["r" + cellValue.r + "c" + cellValue.c] = formulaCell;
  16903. }
  16904. this.celldata.push(cellValue);
  16905. }
  16906. }
  16907. }
  16908. return cellOtherInfo;
  16909. };
  16910. /**
  16911. * luckysheet config of dataValidations
  16912. *
  16913. * @returns {IluckysheetDataVerification} - dataValidations config
  16914. */
  16915. LuckySheet.prototype.generateConfigDataValidations = function () {
  16916. var rows = this.readXml.getElementsByTagName("dataValidations/dataValidation", this.sheetFile);
  16917. var extLst = this.readXml.getElementsByTagName("extLst/ext/x14:dataValidations/x14:dataValidation", this.sheetFile) || [];
  16918. rows = rows.concat(extLst);
  16919. var dataVerification = {};
  16920. for (var i = 0; i < rows.length; i++) {
  16921. var row = rows[i];
  16922. var attrList = row.attributeList;
  16923. var formulaValue = row.value;
  16924. var type = method_1.getXmlAttibute(attrList, "type", null);
  16925. if (!type) {
  16926. continue;
  16927. }
  16928. var operator = "",
  16929. sqref = "",
  16930. sqrefIndexArr = [],
  16931. valueArr = [];
  16932. var _prohibitInput = method_1.getXmlAttibute(attrList, "allowBlank", null) !== "1" ? false : true; // x14 processing
  16933. var formulaReg = new RegExp(/<x14:formula1>|<xm:sqref>/g);
  16934. if (formulaReg.test(formulaValue) && (extLst === null || extLst === void 0 ? void 0 : extLst.length) >= 0) {
  16935. operator = method_1.getXmlAttibute(attrList, "operator", null);
  16936. var peelOffData = method_1.getPeelOffX14(formulaValue);
  16937. sqref = peelOffData === null || peelOffData === void 0 ? void 0 : peelOffData.sqref;
  16938. sqrefIndexArr = method_1.getMultiSequenceToNum(sqref);
  16939. valueArr = method_1.getMultiFormulaValue(peelOffData === null || peelOffData === void 0 ? void 0 : peelOffData.formula);
  16940. } else {
  16941. operator = method_1.getXmlAttibute(attrList, "operator", null);
  16942. sqref = method_1.getXmlAttibute(attrList, "sqref", null);
  16943. sqrefIndexArr = method_1.getMultiSequenceToNum(sqref);
  16944. valueArr = method_1.getMultiFormulaValue(formulaValue);
  16945. }
  16946. var _type = constant_1.DATA_VERIFICATION_MAP[type];
  16947. var _type2 = null;
  16948. var _value1 = (valueArr === null || valueArr === void 0 ? void 0 : valueArr.length) >= 1 ? valueArr[0] : "";
  16949. var _value2 = (valueArr === null || valueArr === void 0 ? void 0 : valueArr.length) === 2 ? valueArr[1] : "";
  16950. var _hint = method_1.getXmlAttibute(attrList, "prompt", null);
  16951. var _hintShow = _hint ? true : false;
  16952. var matchType = constant_1.COMMON_TYPE2.includes(_type) ? "common" : _type;
  16953. _type2 = operator ? constant_1.DATA_VERIFICATION_TYPE2_MAP[matchType][operator] : "bw"; // mobile phone number processing
  16954. if (_type === "text_content" && ((_value1 === null || _value1 === void 0 ? void 0 : _value1.includes("LEN")) || (_value1 === null || _value1 === void 0 ? void 0 : _value1.includes("len"))) && (_value1 === null || _value1 === void 0 ? void 0 : _value1.includes("=11"))) {
  16955. _type = "validity";
  16956. _type2 = "phone";
  16957. } // date processing
  16958. if (_type === "date") {
  16959. var D1900 = new Date(1899, 11, 30, 0, 0, 0);
  16960. _value1 = dayjs_1["default"](D1900).clone().add(Number(_value1), "day").format("YYYY-MM-DD");
  16961. _value2 = dayjs_1["default"](D1900).clone().add(Number(_value2), "day").format("YYYY-MM-DD");
  16962. } // checkbox and dropdown processing
  16963. if (_type === "checkbox" || _type === "dropdown") {
  16964. _type2 = null;
  16965. } // dynamically add dataVerifications
  16966. for (var _i = 0, sqrefIndexArr_1 = sqrefIndexArr; _i < sqrefIndexArr_1.length; _i++) {
  16967. var ref = sqrefIndexArr_1[_i];
  16968. dataVerification[ref] = {
  16969. type: _type,
  16970. type2: _type2,
  16971. value1: _value1,
  16972. value2: _value2,
  16973. checked: false,
  16974. remote: false,
  16975. prohibitInput: _prohibitInput,
  16976. hintShow: _hintShow,
  16977. hintText: _hint
  16978. };
  16979. }
  16980. }
  16981. return dataVerification;
  16982. };
  16983. /**
  16984. * luckysheet config of hyperlink
  16985. *
  16986. * @returns {IluckysheetHyperlink} - hyperlink config
  16987. */
  16988. LuckySheet.prototype.generateConfigHyperlinks = function () {
  16989. var _a;
  16990. var rows = this.readXml.getElementsByTagName("hyperlinks/hyperlink", this.sheetFile);
  16991. var hyperlink = {};
  16992. var _loop_1 = function _loop_1(i) {
  16993. var row = rows[i];
  16994. var attrList = row.attributeList;
  16995. var ref = method_1.getXmlAttibute(attrList, "ref", null),
  16996. refArr = method_1.getMultiSequenceToNum(ref),
  16997. _display = method_1.getXmlAttibute(attrList, "display", null),
  16998. _address = method_1.getXmlAttibute(attrList, "location", null),
  16999. _tooltip = method_1.getXmlAttibute(attrList, "tooltip", null);
  17000. var _type = _address ? "internal" : "external"; // external hyperlink
  17001. if (!_address) {
  17002. var rid_1 = attrList["r:id"];
  17003. var sheetFile = this_1.sheetFile;
  17004. var relationshipList = this_1.readXml.getElementsByTagName("Relationships/Relationship", "xl/worksheets/_rels/" + sheetFile.replace(constant_1.worksheetFilePath, "") + ".rels");
  17005. var findRid = relationshipList === null || relationshipList === void 0 ? void 0 : relationshipList.find(function (e) {
  17006. return e.attributeList["Id"] === rid_1;
  17007. });
  17008. if (findRid) {
  17009. _address = findRid.attributeList["Target"];
  17010. _type = (_a = findRid.attributeList["TargetMode"]) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase();
  17011. }
  17012. } // match R1C1
  17013. var addressReg = new RegExp(/^.*!R([\d$])+C([\d$])*$/g);
  17014. if (addressReg.test(_address)) {
  17015. _address = method_1.getTransR1C1ToSequence(_address);
  17016. } // dynamically add hyperlinks
  17017. for (var _i = 0, refArr_1 = refArr; _i < refArr_1.length; _i++) {
  17018. var ref_1 = refArr_1[_i];
  17019. hyperlink[ref_1] = {
  17020. linkAddress: _address,
  17021. linkTooltip: _tooltip || "",
  17022. linkType: _type,
  17023. display: _display || ""
  17024. };
  17025. }
  17026. };
  17027. var this_1 = this;
  17028. for (var i = 0; i < rows.length; i++) {
  17029. _loop_1(i);
  17030. }
  17031. return hyperlink;
  17032. };
  17033. return LuckySheet;
  17034. }(LuckyBase_1.LuckySheetBase);
  17035. exports.LuckySheet = LuckySheet;
  17036. },{"../common/constant":92,"../common/method":94,"./LuckyBase":86,"./LuckyCell":87,"./ReadXml":91,"dayjs":5}],91:[function(require,module,exports){
  17037. "use strict";
  17038. var __extends = void 0 && (void 0).__extends || function () {
  17039. var _extendStatics = function extendStatics(d, b) {
  17040. _extendStatics = Object.setPrototypeOf || {
  17041. __proto__: []
  17042. } instanceof Array && function (d, b) {
  17043. d.__proto__ = b;
  17044. } || function (d, b) {
  17045. for (var p in b) {
  17046. if (b.hasOwnProperty(p)) d[p] = b[p];
  17047. }
  17048. };
  17049. return _extendStatics(d, b);
  17050. };
  17051. return function (d, b) {
  17052. _extendStatics(d, b);
  17053. function __() {
  17054. this.constructor = d;
  17055. }
  17056. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17057. };
  17058. }();
  17059. Object.defineProperty(exports, "__esModule", {
  17060. value: true
  17061. });
  17062. exports.getlineStringAttr = exports.getColor = exports.Element = exports.ReadXml = void 0;
  17063. var constant_1 = require("../common/constant");
  17064. var method_1 = require("../common/method");
  17065. var xmloperation =
  17066. /** @class */
  17067. function () {
  17068. function xmloperation() {}
  17069. /**
  17070. * @param tag Search xml tag name , div,title etc.
  17071. * @param file Xml string
  17072. * @return Xml element string
  17073. */
  17074. xmloperation.prototype.getElementsByOneTag = function (tag, file) {
  17075. //<a:[^/>: ]+?>.*?</a:[^/>: ]+?>
  17076. var readTagReg;
  17077. if (tag.indexOf("|") > -1) {
  17078. var tags = tag.split("|"),
  17079. tagsRegTxt = "";
  17080. for (var i = 0; i < tags.length; i++) {
  17081. var t = tags[i];
  17082. tagsRegTxt += "|<" + t + " [^>]+?[^/]>[\\s\\S]*?</" + t + ">|<" + t + " [^>]+?/>|<" + t + ">[\\s\\S]*?</" + t + ">|<" + t + "/>";
  17083. }
  17084. tagsRegTxt = tagsRegTxt.substr(1, tagsRegTxt.length);
  17085. readTagReg = new RegExp(tagsRegTxt, "g");
  17086. } else {
  17087. readTagReg = new RegExp("<" + tag + " [^>]+?[^/]>[\\s\\S]*?</" + tag + ">|<" + tag + " [^>]+?/>|<" + tag + ">[\\s\\S]*?</" + tag + ">|<" + tag + "/>", "g");
  17088. }
  17089. var ret = file.match(readTagReg);
  17090. if (ret == null) {
  17091. return [];
  17092. } else {
  17093. return ret;
  17094. }
  17095. };
  17096. return xmloperation;
  17097. }();
  17098. var ReadXml =
  17099. /** @class */
  17100. function (_super) {
  17101. __extends(ReadXml, _super);
  17102. function ReadXml(files) {
  17103. var _this = _super.call(this) || this;
  17104. _this.originFile = files;
  17105. return _this;
  17106. }
  17107. /**
  17108. * @param path Search xml tag group , div,title etc.
  17109. * @param fileName One of uploadfileList, uploadfileList is file group, {key:value}
  17110. * @return Xml element calss
  17111. */
  17112. ReadXml.prototype.getElementsByTagName = function (path, fileName) {
  17113. var file = this.getFileByName(fileName);
  17114. if (path === 'calcChain/c') console.log(file);
  17115. var pathArr = path.split("/"),
  17116. ret;
  17117. for (var key in pathArr) {
  17118. var path_1 = pathArr[key];
  17119. if (ret == undefined) {
  17120. ret = this.getElementsByOneTag(path_1, file);
  17121. } else {
  17122. if (ret instanceof Array) {
  17123. var items = [];
  17124. for (var key_1 in ret) {
  17125. var item = ret[key_1];
  17126. items = items.concat(this.getElementsByOneTag(path_1, item));
  17127. }
  17128. ret = items;
  17129. } else {
  17130. ret = this.getElementsByOneTag(path_1, ret);
  17131. }
  17132. }
  17133. }
  17134. var elements = [];
  17135. for (var i = 0; i < ret.length; i++) {
  17136. var ele = new Element(ret[i]);
  17137. elements.push(ele);
  17138. }
  17139. if (path === 'calcChain/c') console.log(elements);
  17140. return elements;
  17141. };
  17142. /**
  17143. * @param name One of uploadfileList's name, search for file by this parameter
  17144. * @retrun Select a file from uploadfileList
  17145. */
  17146. ReadXml.prototype.getFileByName = function (name) {
  17147. for (var fileKey in this.originFile) {
  17148. if (fileKey.indexOf(name) > -1) {
  17149. return this.originFile[fileKey];
  17150. }
  17151. }
  17152. return "";
  17153. };
  17154. return ReadXml;
  17155. }(xmloperation);
  17156. exports.ReadXml = ReadXml;
  17157. var Element =
  17158. /** @class */
  17159. function (_super) {
  17160. __extends(Element, _super);
  17161. function Element(str) {
  17162. var _this = _super.call(this) || this;
  17163. _this.elementString = str;
  17164. _this.setValue();
  17165. var readAttrReg = new RegExp('[a-zA-Z0-9_:]*?=".*?"', "g");
  17166. var attrList = _this.container.match(readAttrReg);
  17167. _this.attributeList = {};
  17168. if (attrList != null) {
  17169. for (var key in attrList) {
  17170. var attrFull = attrList[key]; // let al= attrFull.split("=");
  17171. if (attrFull.length == 0) {
  17172. continue;
  17173. }
  17174. var attrKey = attrFull.substr(0, attrFull.indexOf('='));
  17175. var attrValue = attrFull.substr(attrFull.indexOf('=') + 1);
  17176. if (attrKey == null || attrValue == null || attrKey.length == 0 || attrValue.length == 0) {
  17177. continue;
  17178. }
  17179. _this.attributeList[attrKey] = attrValue.substr(1, attrValue.length - 2);
  17180. }
  17181. }
  17182. return _this;
  17183. }
  17184. /**
  17185. * @param name Get attribute by key in element
  17186. * @return Single attribute
  17187. */
  17188. Element.prototype.get = function (name) {
  17189. return this.attributeList[name];
  17190. };
  17191. /**
  17192. * @param tag Get elements by tag in elementString
  17193. * @return Element group
  17194. */
  17195. Element.prototype.getInnerElements = function (tag) {
  17196. var ret = this.getElementsByOneTag(tag, this.elementString);
  17197. var elements = [];
  17198. for (var i = 0; i < ret.length; i++) {
  17199. var ele = new Element(ret[i]);
  17200. elements.push(ele);
  17201. }
  17202. if (elements.length == 0) {
  17203. return null;
  17204. }
  17205. return elements;
  17206. };
  17207. /**
  17208. * @desc get xml dom value and container, <container>value</container>
  17209. */
  17210. Element.prototype.setValue = function () {
  17211. var str = this.elementString;
  17212. if (str.substr(str.length - 2, 2) == "/>") {
  17213. this.value = "";
  17214. this.container = str;
  17215. } else {
  17216. var firstTag = this.getFirstTag();
  17217. var firstTagReg = new RegExp("(<" + firstTag + " [^>]+?[^/]>)([\\s\\S]*?)</" + firstTag + ">|(<" + firstTag + ">)([\\s\\S]*?)</" + firstTag + ">", "g");
  17218. var result = firstTagReg.exec(str);
  17219. if (result != null) {
  17220. if (result[1] != null) {
  17221. this.container = result[1];
  17222. this.value = result[2];
  17223. } else {
  17224. this.container = result[3];
  17225. this.value = result[4];
  17226. }
  17227. }
  17228. }
  17229. };
  17230. /**
  17231. * @desc get xml dom first tag, <a><b></b></a>, get a
  17232. */
  17233. Element.prototype.getFirstTag = function () {
  17234. var str = this.elementString;
  17235. var firstTag = str.substr(0, str.indexOf(' '));
  17236. if (firstTag == "" || firstTag.indexOf(">") > -1) {
  17237. firstTag = str.substr(0, str.indexOf('>'));
  17238. }
  17239. firstTag = firstTag.substr(1, firstTag.length);
  17240. return firstTag;
  17241. };
  17242. return Element;
  17243. }(xmloperation);
  17244. exports.Element = Element;
  17245. function combineIndexedColor(indexedColorsInner, indexedColors) {
  17246. var ret = {};
  17247. if (indexedColorsInner == null || indexedColorsInner.length == 0) {
  17248. return indexedColors;
  17249. }
  17250. for (var key in indexedColors) {
  17251. var value = indexedColors[key],
  17252. kn = parseInt(key);
  17253. var inner = indexedColorsInner[kn];
  17254. if (inner == null) {
  17255. ret[key] = value;
  17256. } else {
  17257. var rgb = inner.attributeList.rgb;
  17258. ret[key] = rgb;
  17259. }
  17260. }
  17261. return ret;
  17262. } //clrScheme:Element[]
  17263. function getColor(color, styles, type) {
  17264. if (type === void 0) {
  17265. type = "g";
  17266. }
  17267. var attrList = color.attributeList;
  17268. var clrScheme = styles["clrScheme"];
  17269. var indexedColorsInner = styles["indexedColors"];
  17270. var mruColorsInner = styles["mruColors"];
  17271. var indexedColorsList = combineIndexedColor(indexedColorsInner, constant_1.indexedColors);
  17272. var indexed = attrList.indexed,
  17273. rgb = attrList.rgb,
  17274. theme = attrList.theme,
  17275. tint = attrList.tint;
  17276. var bg;
  17277. if (indexed != null) {
  17278. var indexedNum = parseInt(indexed);
  17279. bg = indexedColorsList[indexedNum];
  17280. if (bg != null) {
  17281. bg = bg.substring(bg.length - 6, bg.length);
  17282. bg = "#" + bg;
  17283. }
  17284. } else if (rgb != null) {
  17285. rgb = rgb.substring(rgb.length - 6, rgb.length);
  17286. bg = "#" + rgb;
  17287. } else if (theme != null) {
  17288. var themeNum = parseInt(theme);
  17289. if (themeNum == 0) {
  17290. themeNum = 1;
  17291. } else if (themeNum == 1) {
  17292. themeNum = 0;
  17293. } else if (themeNum == 2) {
  17294. themeNum = 3;
  17295. } else if (themeNum == 3) {
  17296. themeNum = 2;
  17297. }
  17298. var clrSchemeElement = clrScheme[themeNum];
  17299. if (clrSchemeElement != null) {
  17300. var clrs = clrSchemeElement.getInnerElements("a:sysClr|a:srgbClr");
  17301. if (clrs != null) {
  17302. var clr = clrs[0];
  17303. var clrAttrList = clr.attributeList; // console.log(clr.container, );
  17304. if (clr.container.indexOf("sysClr") > -1) {
  17305. // if(type=="g" && clrAttrList.val=="windowText"){
  17306. // bg = null;
  17307. // }
  17308. // else if((type=="t" || type=="b") && clrAttrList.val=="window"){
  17309. // bg = null;
  17310. // }
  17311. // else
  17312. if (clrAttrList.lastClr != null) {
  17313. bg = "#" + clrAttrList.lastClr;
  17314. } else if (clrAttrList.val != null) {
  17315. bg = "#" + clrAttrList.val;
  17316. }
  17317. } else if (clr.container.indexOf("srgbClr") > -1) {
  17318. // console.log(clrAttrList.val);
  17319. bg = "#" + clrAttrList.val;
  17320. }
  17321. }
  17322. }
  17323. }
  17324. if (tint != null) {
  17325. var tintNum = parseFloat(tint);
  17326. if (bg != null) {
  17327. bg = method_1.LightenDarkenColor(bg, tintNum);
  17328. }
  17329. }
  17330. return bg;
  17331. }
  17332. exports.getColor = getColor;
  17333. /**
  17334. * @dom xml attribute object
  17335. * @attr attribute name
  17336. * @d if attribute is null, return default value
  17337. * @return attribute value
  17338. */
  17339. function getlineStringAttr(frpr, attr) {
  17340. var attrEle = frpr.getInnerElements(attr),
  17341. value;
  17342. if (attrEle != null && attrEle.length > 0) {
  17343. if (attr == "b" || attr == "i" || attr == "strike") {
  17344. value = "1";
  17345. } else if (attr == "u") {
  17346. var v = attrEle[0].attributeList.val;
  17347. if (v == "double") {
  17348. value = "2";
  17349. } else if (v == "singleAccounting") {
  17350. value = "3";
  17351. } else if (v == "doubleAccounting") {
  17352. value = "4";
  17353. } else {
  17354. value = "1";
  17355. }
  17356. } else if (attr == "vertAlign") {
  17357. var v = attrEle[0].attributeList.val;
  17358. if (v == "subscript") {
  17359. value = "1";
  17360. } else if (v == "superscript") {
  17361. value = "2";
  17362. }
  17363. } else {
  17364. value = attrEle[0].attributeList.val;
  17365. }
  17366. }
  17367. return value;
  17368. }
  17369. exports.getlineStringAttr = getlineStringAttr;
  17370. },{"../common/constant":92,"../common/method":94}],92:[function(require,module,exports){
  17371. "use strict";
  17372. Object.defineProperty(exports, "__esModule", {
  17373. value: true
  17374. });
  17375. exports.DATA_VERIFICATION_TYPE2_MAP = exports.COMMON_TYPE2 = exports.DATA_VERIFICATION_MAP = exports.fontFamilys = exports.numFmtDefaultMap = exports.borderTypes = exports.OEM_CHARSET = exports.indexedColors = exports.numFmtDefault = exports.BuiltInCellStyles = exports.ST_CellType = exports.workbookRels = exports.theme1File = exports.worksheetFilePath = exports.sharedStringsFile = exports.stylesFile = exports.calcChainFile = exports.workBookFile = exports.contentTypesFile = exports.appFile = exports.coreFile = exports.columeHeader_word_index = exports.columeHeader_word = void 0;
  17376. exports.columeHeader_word = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  17377. exports.columeHeader_word_index = {
  17378. 'A': 0,
  17379. 'B': 1,
  17380. 'C': 2,
  17381. 'D': 3,
  17382. 'E': 4,
  17383. 'F': 5,
  17384. 'G': 6,
  17385. 'H': 7,
  17386. 'I': 8,
  17387. 'J': 9,
  17388. 'K': 10,
  17389. 'L': 11,
  17390. 'M': 12,
  17391. 'N': 13,
  17392. 'O': 14,
  17393. 'P': 15,
  17394. 'Q': 16,
  17395. 'R': 17,
  17396. 'S': 18,
  17397. 'T': 19,
  17398. 'U': 20,
  17399. 'V': 21,
  17400. 'W': 22,
  17401. 'X': 23,
  17402. 'Y': 24,
  17403. 'Z': 25
  17404. };
  17405. exports.coreFile = "docProps/core.xml";
  17406. exports.appFile = "docProps/app.xml";
  17407. exports.contentTypesFile = "[Content_Types].xml";
  17408. exports.workBookFile = "xl/workbook.xml";
  17409. exports.calcChainFile = "xl/calcChain.xml";
  17410. exports.stylesFile = "xl/styles.xml";
  17411. exports.sharedStringsFile = "xl/sharedStrings.xml";
  17412. exports.worksheetFilePath = "xl/worksheets/";
  17413. exports.theme1File = "xl/theme/theme1.xml";
  17414. exports.workbookRels = "xl/_rels/workbook.xml.rels"; //Excel Built-In cell type
  17415. exports.ST_CellType = {
  17416. "Boolean": "b",
  17417. "Date": "d",
  17418. "Error": "e",
  17419. "InlineString": "inlineStr",
  17420. "Number": "n",
  17421. "SharedString": "s",
  17422. "String": "str"
  17423. }; //Excel Built-In cell style
  17424. exports.BuiltInCellStyles = {
  17425. "0": "Normal"
  17426. };
  17427. exports.numFmtDefault = {
  17428. "0": 'General',
  17429. "1": '0',
  17430. "2": '0.00',
  17431. "3": '#,##0',
  17432. "4": '#,##0.00',
  17433. "9": '0%',
  17434. "10": '0.00%',
  17435. "11": '0.00E+00',
  17436. "12": '# ?/?',
  17437. "13": '# ??/??',
  17438. "14": 'm/d/yy',
  17439. "15": 'd-mmm-yy',
  17440. "16": 'd-mmm',
  17441. "17": 'mmm-yy',
  17442. "18": 'h:mm AM/PM',
  17443. "19": 'h:mm:ss AM/PM',
  17444. "20": 'h:mm',
  17445. "21": 'h:mm:ss',
  17446. "22": 'm/d/yy h:mm',
  17447. "37": '#,##0 ;(#,##0)',
  17448. "38": '#,##0 ;[Red](#,##0)',
  17449. "39": '#,##0.00;(#,##0.00)',
  17450. "40": '#,##0.00;[Red](#,##0.00)',
  17451. "45": 'mm:ss',
  17452. "46": '[h]:mm:ss',
  17453. "47": 'mmss.0',
  17454. "48": '##0.0E+0',
  17455. "49": '@'
  17456. };
  17457. exports.indexedColors = {
  17458. "0": '00000000',
  17459. "1": '00FFFFFF',
  17460. "2": '00FF0000',
  17461. "3": '0000FF00',
  17462. "4": '000000FF',
  17463. "5": '00FFFF00',
  17464. "6": '00FF00FF',
  17465. "7": '0000FFFF',
  17466. "8": '00000000',
  17467. "9": '00FFFFFF',
  17468. "10": '00FF0000',
  17469. "11": '0000FF00',
  17470. "12": '000000FF',
  17471. "13": '00FFFF00',
  17472. "14": '00FF00FF',
  17473. "15": '0000FFFF',
  17474. "16": '00800000',
  17475. "17": '00008000',
  17476. "18": '00000080',
  17477. "19": '00808000',
  17478. "20": '00800080',
  17479. "21": '00008080',
  17480. "22": '00C0C0C0',
  17481. "23": '00808080',
  17482. "24": '009999FF',
  17483. "25": '00993366',
  17484. "26": '00FFFFCC',
  17485. "27": '00CCFFFF',
  17486. "28": '00660066',
  17487. "29": '00FF8080',
  17488. "30": '000066CC',
  17489. "31": '00CCCCFF',
  17490. "32": '00000080',
  17491. "33": '00FF00FF',
  17492. "34": '00FFFF00',
  17493. "35": '0000FFFF',
  17494. "36": '00800080',
  17495. "37": '00800000',
  17496. "38": '00008080',
  17497. "39": '000000FF',
  17498. "40": '0000CCFF',
  17499. "41": '00CCFFFF',
  17500. "42": '00CCFFCC',
  17501. "43": '00FFFF99',
  17502. "44": '0099CCFF',
  17503. "45": '00FF99CC',
  17504. "46": '00CC99FF',
  17505. "47": '00FFCC99',
  17506. "48": '003366FF',
  17507. "49": '0033CCCC',
  17508. "50": '0099CC00',
  17509. "51": '00FFCC00',
  17510. "52": '00FF9900',
  17511. "53": '00FF6600',
  17512. "54": '00666699',
  17513. "55": '00969696',
  17514. "56": '00003366',
  17515. "57": '00339966',
  17516. "58": '00003300',
  17517. "59": '00333300',
  17518. "60": '00993300',
  17519. "61": '00993366',
  17520. "62": '00333399',
  17521. "63": '00333333',
  17522. "64": null,
  17523. "65": null
  17524. };
  17525. exports.OEM_CHARSET = {
  17526. "0": "ANSI_CHARSET",
  17527. "1": "DEFAULT_CHARSET",
  17528. "2": "SYMBOL_CHARSET",
  17529. "77": "MAC_CHARSET",
  17530. "128": "SHIFTJIS_CHARSET",
  17531. "129": "HANGUL_CHARSET",
  17532. "130": "JOHAB_CHARSET",
  17533. "134": "GB2312_CHARSET",
  17534. "136": "CHINESEBIG5_CHARSET",
  17535. "161": "GREEK_CHARSET",
  17536. "162": "TURKISH_CHARSET",
  17537. "163": "VIETNAMESE_CHARSET",
  17538. "177": "HEBREW_CHARSET",
  17539. "178": "ARABIC_CHARSET",
  17540. "186": "BALTIC_CHARSET",
  17541. "204": "RUSSIAN_CHARSET",
  17542. "222": "THAI_CHARSET",
  17543. "238": "EASTEUROPE_CHARSET",
  17544. "255": "OEM_CHARSET"
  17545. };
  17546. exports.borderTypes = {
  17547. "none": 0,
  17548. "thin": 1,
  17549. "hair": 2,
  17550. "dotted": 3,
  17551. "dashed": 4,
  17552. "dashDot": 5,
  17553. "dashDotDot": 6,
  17554. "double": 7,
  17555. "medium": 8,
  17556. "mediumDashed": 9,
  17557. "mediumDashDot": 10,
  17558. "mediumDashDotDot": 11,
  17559. "slantDashDot": 12,
  17560. "thick": 13
  17561. };
  17562. exports.numFmtDefaultMap = {
  17563. "yyyy/m/d;@": "yyyy/MM/dd",
  17564. "yyyy&quot;年&quot;m&quot;月&quot;d&quot;日&quot;;@": "yyyy&quot;年&quot;MM&quot;月&quot;dd&quot;日&quot;",
  17565. "[$-409]yyyy/m/d\\ h:mm\\ AM/PM;@": "yyyy/MM/dd hh:mm AM/PM"
  17566. };
  17567. exports.fontFamilys = {
  17568. "0": "defualt",
  17569. "1": "Roman",
  17570. "2": "Swiss",
  17571. "3": "Modern",
  17572. "4": "Script",
  17573. "5": "Decorative"
  17574. };
  17575. exports.DATA_VERIFICATION_MAP = {
  17576. list: "dropdown",
  17577. whole: "number_integer",
  17578. decimal: "number_decimal",
  17579. custom: "text_content",
  17580. textLength: "text_length",
  17581. date: "date",
  17582. "unknown1": "number",
  17583. "unknown2": "checkbox",
  17584. "unknown3": "validity"
  17585. };
  17586. exports.COMMON_TYPE2 = ["number", "number_integer", "number_decimal", "text_length"];
  17587. exports.DATA_VERIFICATION_TYPE2_MAP = {
  17588. common: {
  17589. between: "bw",
  17590. notBetween: "nb",
  17591. equal: "eq",
  17592. notEqualTo: "ne",
  17593. moreThanThe: "gt",
  17594. lessThan: "lt",
  17595. greaterOrEqualTo: "gte",
  17596. lessThanOrEqualTo: "lte"
  17597. },
  17598. text_content: {
  17599. include: "include",
  17600. exclude: "exclude",
  17601. equal: "equal"
  17602. },
  17603. date: {
  17604. between: "bw",
  17605. notBetween: "nb",
  17606. equal: "eq",
  17607. notEqualTo: "ne",
  17608. earlierThan: "bf",
  17609. noEarlierThan: "nbf",
  17610. laterThan: "af",
  17611. noLaterThan: "naf"
  17612. },
  17613. validity: {
  17614. card: "card",
  17615. phone: "phone"
  17616. }
  17617. };
  17618. },{}],93:[function(require,module,exports){
  17619. "use strict";
  17620. Object.defineProperty(exports, "__esModule", {
  17621. value: true
  17622. });
  17623. exports.ToContext2D = exports.FromEMF = exports.UDOC = void 0;
  17624. exports.UDOC = {};
  17625. exports.UDOC.G = {
  17626. concat: function concat(p, r) {
  17627. for (var i = 0; i < r.cmds.length; i++) {
  17628. p.cmds.push(r.cmds[i]);
  17629. }
  17630. for (var i = 0; i < r.crds.length; i++) {
  17631. p.crds.push(r.crds[i]);
  17632. }
  17633. },
  17634. getBB: function getBB(ps) {
  17635. var x0 = 1e99,
  17636. y0 = 1e99,
  17637. x1 = -x0,
  17638. y1 = -y0;
  17639. for (var i = 0; i < ps.length; i += 2) {
  17640. var x = ps[i],
  17641. y = ps[i + 1];
  17642. if (x < x0) x0 = x;else if (x > x1) x1 = x;
  17643. if (y < y0) y0 = y;else if (y > y1) y1 = y;
  17644. }
  17645. return [x0, y0, x1, y1];
  17646. },
  17647. rectToPath: function rectToPath(r) {
  17648. return {
  17649. cmds: ["M", "L", "L", "L", "Z"],
  17650. crds: [r[0], r[1], r[2], r[1], r[2], r[3], r[0], r[3]]
  17651. };
  17652. },
  17653. // a inside b
  17654. insideBox: function insideBox(a, b) {
  17655. return b[0] <= a[0] && b[1] <= a[1] && a[2] <= b[2] && a[3] <= b[3];
  17656. },
  17657. isBox: function isBox(p, bb) {
  17658. var sameCrd8 = function sameCrd8(pcrd, crds) {
  17659. for (var o = 0; o < 8; o += 2) {
  17660. var eq = true;
  17661. for (var j = 0; j < 8; j++) {
  17662. if (Math.abs(crds[j] - pcrd[j + o & 7]) >= 2) {
  17663. eq = false;
  17664. break;
  17665. }
  17666. }
  17667. if (eq) return true;
  17668. }
  17669. return false;
  17670. };
  17671. if (p.cmds.length > 10) return false;
  17672. var cmds = p.cmds.join(""),
  17673. crds = p.crds;
  17674. var sameRect = false;
  17675. if (cmds == "MLLLZ" && crds.length == 8 || cmds == "MLLLLZ" && crds.length == 10) {
  17676. if (crds.length == 10) crds = crds.slice(0, 8);
  17677. var x0 = bb[0],
  17678. y0 = bb[1],
  17679. x1 = bb[2],
  17680. y1 = bb[3];
  17681. if (!sameRect) sameRect = sameCrd8(crds, [x0, y0, x1, y0, x1, y1, x0, y1]);
  17682. if (!sameRect) sameRect = sameCrd8(crds, [x0, y1, x1, y1, x1, y0, x0, y0]);
  17683. }
  17684. return sameRect;
  17685. },
  17686. boxArea: function boxArea(a) {
  17687. var w = a[2] - a[0],
  17688. h = a[3] - a[1];
  17689. return w * h;
  17690. },
  17691. newPath: function newPath(gst) {
  17692. gst.pth = {
  17693. cmds: [],
  17694. crds: []
  17695. };
  17696. },
  17697. moveTo: function moveTo(gst, x, y) {
  17698. var p = exports.UDOC.M.multPoint(gst.ctm, [x, y]); //if(gst.cpos[0]==p[0] && gst.cpos[1]==p[1]) return;
  17699. gst.pth.cmds.push("M");
  17700. gst.pth.crds.push(p[0], p[1]);
  17701. gst.cpos = p;
  17702. },
  17703. lineTo: function lineTo(gst, x, y) {
  17704. var p = exports.UDOC.M.multPoint(gst.ctm, [x, y]);
  17705. if (gst.cpos[0] == p[0] && gst.cpos[1] == p[1]) return;
  17706. gst.pth.cmds.push("L");
  17707. gst.pth.crds.push(p[0], p[1]);
  17708. gst.cpos = p;
  17709. },
  17710. curveTo: function curveTo(gst, x1, y1, x2, y2, x3, y3) {
  17711. var p;
  17712. p = exports.UDOC.M.multPoint(gst.ctm, [x1, y1]);
  17713. x1 = p[0];
  17714. y1 = p[1];
  17715. p = exports.UDOC.M.multPoint(gst.ctm, [x2, y2]);
  17716. x2 = p[0];
  17717. y2 = p[1];
  17718. p = exports.UDOC.M.multPoint(gst.ctm, [x3, y3]);
  17719. x3 = p[0];
  17720. y3 = p[1];
  17721. gst.cpos = p;
  17722. gst.pth.cmds.push("C");
  17723. gst.pth.crds.push(x1, y1, x2, y2, x3, y3);
  17724. },
  17725. closePath: function closePath(gst) {
  17726. gst.pth.cmds.push("Z");
  17727. },
  17728. arc: function arc(gst, x, y, r, a0, a1, neg) {
  17729. // circle from a0 counter-clock-wise to a1
  17730. if (neg) while (a1 > a0) {
  17731. a1 -= 2 * Math.PI;
  17732. } else while (a1 < a0) {
  17733. a1 += 2 * Math.PI;
  17734. }
  17735. var th = (a1 - a0) / 4;
  17736. var x0 = Math.cos(th / 2),
  17737. y0 = -Math.sin(th / 2);
  17738. var x1 = (4 - x0) / 3,
  17739. y1 = y0 == 0 ? y0 : (1 - x0) * (3 - x0) / (3 * y0);
  17740. var x2 = x1,
  17741. y2 = -y1;
  17742. var x3 = x0,
  17743. y3 = -y0;
  17744. var p0 = [x0, y0],
  17745. p1 = [x1, y1],
  17746. p2 = [x2, y2],
  17747. p3 = [x3, y3];
  17748. var pth = {
  17749. cmds: [gst.pth.cmds.length == 0 ? "M" : "L", "C", "C", "C", "C"],
  17750. crds: [x0, y0, x1, y1, x2, y2, x3, y3]
  17751. };
  17752. var rot = [1, 0, 0, 1, 0, 0];
  17753. exports.UDOC.M.rotate(rot, -th);
  17754. for (var i = 0; i < 3; i++) {
  17755. p1 = exports.UDOC.M.multPoint(rot, p1);
  17756. p2 = exports.UDOC.M.multPoint(rot, p2);
  17757. p3 = exports.UDOC.M.multPoint(rot, p3);
  17758. pth.crds.push(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
  17759. }
  17760. var sc = [r, 0, 0, r, x, y];
  17761. exports.UDOC.M.rotate(rot, -a0 + th / 2);
  17762. exports.UDOC.M.concat(rot, sc);
  17763. exports.UDOC.M.multArray(rot, pth.crds);
  17764. exports.UDOC.M.multArray(gst.ctm, pth.crds);
  17765. exports.UDOC.G.concat(gst.pth, pth);
  17766. var y = pth.crds.pop();
  17767. x = pth.crds.pop();
  17768. gst.cpos = [x, y];
  17769. },
  17770. toPoly: function toPoly(p) {
  17771. if (p.cmds[0] != "M" || p.cmds[p.cmds.length - 1] != "Z") return null;
  17772. for (var i = 1; i < p.cmds.length - 1; i++) {
  17773. if (p.cmds[i] != "L") return null;
  17774. }
  17775. var out = [],
  17776. cl = p.crds.length;
  17777. if (p.crds[0] == p.crds[cl - 2] && p.crds[1] == p.crds[cl - 1]) cl -= 2;
  17778. for (var i = 0; i < cl; i += 2) {
  17779. out.push([p.crds[i], p.crds[i + 1]]);
  17780. }
  17781. if (exports.UDOC.G.polyArea(p.crds) < 0) out.reverse();
  17782. return out;
  17783. },
  17784. fromPoly: function fromPoly(p) {
  17785. var o = {
  17786. cmds: [],
  17787. crds: []
  17788. };
  17789. for (var i = 0; i < p.length; i++) {
  17790. o.crds.push(p[i][0], p[i][1]);
  17791. o.cmds.push(i == 0 ? "M" : "L");
  17792. }
  17793. o.cmds.push("Z");
  17794. return o;
  17795. },
  17796. polyArea: function polyArea(p) {
  17797. if (p.length < 6) return 0;
  17798. var l = p.length - 2;
  17799. var sum = (p[0] - p[l]) * (p[l + 1] + p[1]);
  17800. for (var i = 0; i < l; i += 2) {
  17801. sum += (p[i + 2] - p[i]) * (p[i + 1] + p[i + 3]);
  17802. }
  17803. return -sum * 0.5;
  17804. },
  17805. polyClip: function polyClip(p0, p1) {
  17806. var cp1, cp2, s, e;
  17807. var inside = function inside(p) {
  17808. return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]);
  17809. };
  17810. var isc = function isc() {
  17811. var dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]],
  17812. dp = [s[0] - e[0], s[1] - e[1]],
  17813. n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
  17814. n2 = s[0] * e[1] - s[1] * e[0],
  17815. n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
  17816. return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3];
  17817. };
  17818. var out = p0;
  17819. cp1 = p1[p1.length - 1];
  17820. for (var j in p1) {
  17821. var cp2 = p1[j];
  17822. var inp = out;
  17823. out = [];
  17824. s = inp[inp.length - 1]; //last on the input list
  17825. for (var i in inp) {
  17826. var e = inp[i];
  17827. if (inside(e)) {
  17828. if (!inside(s)) {
  17829. out.push(isc());
  17830. }
  17831. out.push(e);
  17832. } else if (inside(s)) {
  17833. out.push(isc());
  17834. }
  17835. s = e;
  17836. }
  17837. cp1 = cp2;
  17838. }
  17839. return out;
  17840. }
  17841. };
  17842. exports.UDOC.M = {
  17843. getScale: function getScale(m) {
  17844. return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
  17845. },
  17846. translate: function translate(m, x, y) {
  17847. exports.UDOC.M.concat(m, [1, 0, 0, 1, x, y]);
  17848. },
  17849. rotate: function rotate(m, a) {
  17850. exports.UDOC.M.concat(m, [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a), 0, 0]);
  17851. },
  17852. scale: function scale(m, x, y) {
  17853. exports.UDOC.M.concat(m, [x, 0, 0, y, 0, 0]);
  17854. },
  17855. concat: function concat(m, w) {
  17856. var a = m[0],
  17857. b = m[1],
  17858. c = m[2],
  17859. d = m[3],
  17860. tx = m[4],
  17861. ty = m[5];
  17862. m[0] = a * w[0] + b * w[2];
  17863. m[1] = a * w[1] + b * w[3];
  17864. m[2] = c * w[0] + d * w[2];
  17865. m[3] = c * w[1] + d * w[3];
  17866. m[4] = tx * w[0] + ty * w[2] + w[4];
  17867. m[5] = tx * w[1] + ty * w[3] + w[5];
  17868. },
  17869. invert: function invert(m) {
  17870. var a = m[0],
  17871. b = m[1],
  17872. c = m[2],
  17873. d = m[3],
  17874. tx = m[4],
  17875. ty = m[5],
  17876. adbc = a * d - b * c;
  17877. m[0] = d / adbc;
  17878. m[1] = -b / adbc;
  17879. m[2] = -c / adbc;
  17880. m[3] = a / adbc;
  17881. m[4] = (c * ty - d * tx) / adbc;
  17882. m[5] = (b * tx - a * ty) / adbc;
  17883. },
  17884. multPoint: function multPoint(m, p) {
  17885. var x = p[0],
  17886. y = p[1];
  17887. return [x * m[0] + y * m[2] + m[4], x * m[1] + y * m[3] + m[5]];
  17888. },
  17889. multArray: function multArray(m, a) {
  17890. for (var i = 0; i < a.length; i += 2) {
  17891. var x = a[i],
  17892. y = a[i + 1];
  17893. a[i] = x * m[0] + y * m[2] + m[4];
  17894. a[i + 1] = x * m[1] + y * m[3] + m[5];
  17895. }
  17896. }
  17897. };
  17898. exports.UDOC.C = {
  17899. srgbGamma: function srgbGamma(x) {
  17900. return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055;
  17901. },
  17902. cmykToRgb: function cmykToRgb(clr) {
  17903. var c = clr[0],
  17904. m = clr[1],
  17905. y = clr[2],
  17906. k = clr[3]; // return [1-Math.min(1,c+k), 1-Math.min(1, m+k), 1-Math.min(1,y+k)];
  17907. var r = 255 + c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * (1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747);
  17908. var g = 255 + c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578);
  17909. var b = 255 + c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367);
  17910. return [Math.max(0, Math.min(1, r / 255)), Math.max(0, Math.min(1, g / 255)), Math.max(0, Math.min(1, b / 255))]; //var iK = 1-c[3];
  17911. //return [(1-c[0])*iK, (1-c[1])*iK, (1-c[2])*iK];
  17912. },
  17913. labToRgb: function labToRgb(lab) {
  17914. var k = 903.3,
  17915. e = 0.008856,
  17916. L = lab[0],
  17917. a = lab[1],
  17918. b = lab[2];
  17919. var fy = (L + 16) / 116,
  17920. fy3 = fy * fy * fy;
  17921. var fz = fy - b / 200,
  17922. fz3 = fz * fz * fz;
  17923. var fx = a / 500 + fy,
  17924. fx3 = fx * fx * fx;
  17925. var zr = fz3 > e ? fz3 : (116 * fz - 16) / k;
  17926. var yr = fy3 > e ? fy3 : (116 * fy - 16) / k;
  17927. var xr = fx3 > e ? fx3 : (116 * fx - 16) / k;
  17928. var X = xr * 96.72,
  17929. Y = yr * 100,
  17930. Z = zr * 81.427,
  17931. xyz = [X / 100, Y / 100, Z / 100];
  17932. var x2s = [3.1338561, -1.6168667, -0.4906146, -0.9787684, 1.9161415, 0.0334540, 0.0719453, -0.2289914, 1.4052427];
  17933. var rgb = [x2s[0] * xyz[0] + x2s[1] * xyz[1] + x2s[2] * xyz[2], x2s[3] * xyz[0] + x2s[4] * xyz[1] + x2s[5] * xyz[2], x2s[6] * xyz[0] + x2s[7] * xyz[1] + x2s[8] * xyz[2]];
  17934. for (var i = 0; i < 3; i++) {
  17935. rgb[i] = Math.max(0, Math.min(1, exports.UDOC.C.srgbGamma(rgb[i])));
  17936. }
  17937. return rgb;
  17938. }
  17939. };
  17940. exports.UDOC.getState = function (crds) {
  17941. return {
  17942. font: exports.UDOC.getFont(),
  17943. dd: {
  17944. flat: 1
  17945. },
  17946. space: "/DeviceGray",
  17947. // fill
  17948. ca: 1,
  17949. colr: [0, 0, 0],
  17950. sspace: "/DeviceGray",
  17951. // stroke
  17952. CA: 1,
  17953. COLR: [0, 0, 0],
  17954. bmode: "/Normal",
  17955. SA: false,
  17956. OPM: 0,
  17957. AIS: false,
  17958. OP: false,
  17959. op: false,
  17960. SMask: "/None",
  17961. lwidth: 1,
  17962. lcap: 0,
  17963. ljoin: 0,
  17964. mlimit: 10,
  17965. SM: 0.1,
  17966. doff: 0,
  17967. dash: [],
  17968. ctm: [1, 0, 0, 1, 0, 0],
  17969. cpos: [0, 0],
  17970. pth: {
  17971. cmds: [],
  17972. crds: []
  17973. },
  17974. cpth: crds ? exports.UDOC.G.rectToPath(crds) : null // clipping path
  17975. };
  17976. };
  17977. exports.UDOC.getFont = function () {
  17978. return {
  17979. Tc: 0,
  17980. Tw: 0,
  17981. Th: 100,
  17982. Tl: 0,
  17983. Tf: "Helvetica-Bold",
  17984. Tfs: 1,
  17985. Tmode: 0,
  17986. Trise: 0,
  17987. Tk: 0,
  17988. Tal: 0,
  17989. Tun: 0,
  17990. Tm: [1, 0, 0, 1, 0, 0],
  17991. Tlm: [1, 0, 0, 1, 0, 0],
  17992. Trm: [1, 0, 0, 1, 0, 0]
  17993. };
  17994. };
  17995. exports.FromEMF = function () {};
  17996. exports.FromEMF.Parse = function (buff, genv) {
  17997. buff = new Uint8Array(buff);
  17998. var off = 0; //console.log(buff.slice(0,32));
  17999. var prms = {
  18000. fill: false,
  18001. strk: false,
  18002. bb: [0, 0, 1, 1],
  18003. wbb: [0, 0, 1, 1],
  18004. fnt: {
  18005. nam: "Arial",
  18006. hgh: 25,
  18007. und: false,
  18008. orn: 0
  18009. },
  18010. tclr: [0, 0, 0],
  18011. talg: 0
  18012. },
  18013. gst,
  18014. tab = [],
  18015. sts = [];
  18016. var rI = exports.FromEMF.B.readShort,
  18017. rU = exports.FromEMF.B.readUshort,
  18018. rI32 = exports.FromEMF.B.readInt,
  18019. rU32 = exports.FromEMF.B.readUint,
  18020. rF32 = exports.FromEMF.B.readFloat;
  18021. var opn = 0;
  18022. while (true) {
  18023. var fnc = rU32(buff, off);
  18024. off += 4;
  18025. var fnm = exports.FromEMF.K[fnc];
  18026. var siz = rU32(buff, off);
  18027. off += 4; //if(gst && isNaN(gst.ctm[0])) throw "e";
  18028. //console.log(fnc,fnm,siz);
  18029. var loff = off; //if(opn++==253) break;
  18030. var obj = null,
  18031. oid = 0; //console.log(fnm, siz);
  18032. if (false) {} else if (fnm == "EOF") {
  18033. break;
  18034. } else if (fnm == "HEADER") {
  18035. prms.bb = exports.FromEMF._readBox(buff, loff);
  18036. loff += 16; //console.log(fnm, prms.bb);
  18037. genv.StartPage(prms.bb[0], prms.bb[1], prms.bb[2], prms.bb[3]);
  18038. gst = exports.UDOC.getState(prms.bb);
  18039. } else if (fnm == "SAVEDC") sts.push(JSON.stringify(gst), JSON.stringify(prms));else if (fnm == "RESTOREDC") {
  18040. var dif = rI32(buff, loff);
  18041. loff += 4;
  18042. while (dif < -1) {
  18043. sts.pop();
  18044. sts.pop();
  18045. }
  18046. prms = JSON.parse(sts.pop());
  18047. gst = JSON.parse(sts.pop());
  18048. } else if (fnm == "SELECTCLIPPATH") {
  18049. gst.cpth = JSON.parse(JSON.stringify(gst.pth));
  18050. } else if (["SETMAPMODE", "SETPOLYFILLMODE", "SETBKMODE"
  18051. /*,"SETVIEWPORTEXTEX"*/
  18052. , "SETICMMODE", "SETROP2", "EXTSELECTCLIPRGN"].indexOf(fnm) != -1) {} //else if(fnm=="INTERSECTCLIPRECT") { var r=prms.crct=FromEMF._readBox(buff, loff); /*var y0=r[1],y1=r[3]; if(y0>y1){r[1]=y1; r[3]=y0;}*/ console.log(prms.crct); }
  18053. else if (fnm == "SETMITERLIMIT") gst.mlimit = rU32(buff, loff);else if (fnm == "SETTEXTCOLOR") prms.tclr = [buff[loff] / 255, buff[loff + 1] / 255, buff[loff + 2] / 255];else if (fnm == "SETTEXTALIGN") prms.talg = rU32(buff, loff);else if (fnm == "SETVIEWPORTEXTEX" || fnm == "SETVIEWPORTORGEX") {
  18054. if (prms.vbb == null) prms.vbb = [];
  18055. var coff = fnm == "SETVIEWPORTORGEX" ? 0 : 2;
  18056. prms.vbb[coff] = rI32(buff, loff);
  18057. loff += 4;
  18058. prms.vbb[coff + 1] = rI32(buff, loff);
  18059. loff += 4; //console.log(prms.vbb);
  18060. if (fnm == "SETVIEWPORTEXTEX") exports.FromEMF._updateCtm(prms, gst);
  18061. } else if (fnm == "SETWINDOWEXTEX" || fnm == "SETWINDOWORGEX") {
  18062. var coff = fnm == "SETWINDOWORGEX" ? 0 : 2;
  18063. prms.wbb[coff] = rI32(buff, loff);
  18064. loff += 4;
  18065. prms.wbb[coff + 1] = rI32(buff, loff);
  18066. loff += 4;
  18067. if (fnm == "SETWINDOWEXTEX") exports.FromEMF._updateCtm(prms, gst);
  18068. } //else if(fnm=="SETMETARGN") {}
  18069. else if (fnm == "COMMENT") {
  18070. var ds = rU32(buff, loff);
  18071. loff += 4;
  18072. } else if (fnm == "SELECTOBJECT") {
  18073. var ind = rU32(buff, loff);
  18074. loff += 4; //console.log(ind.toString(16), tab, tab[ind]);
  18075. if (ind == 0x80000000) {
  18076. prms.fill = true;
  18077. gst.colr = [1, 1, 1];
  18078. } // white brush
  18079. else if (ind == 0x80000005) {
  18080. prms.fill = false;
  18081. } // null brush
  18082. else if (ind == 0x80000007) {
  18083. prms.strk = true;
  18084. prms.lwidth = 1;
  18085. gst.COLR = [0, 0, 0];
  18086. } // black pen
  18087. else if (ind == 0x80000008) {
  18088. prms.strk = false;
  18089. } // null pen
  18090. else if (ind == 0x8000000d) {} // system font
  18091. else if (ind == 0x8000000e) {} // device default font
  18092. else {
  18093. var co = tab[ind]; //console.log(ind, co);
  18094. if (co.t == "b") {
  18095. prms.fill = co.stl != 1;
  18096. if (co.stl == 0) {} else if (co.stl == 1) {} else throw co.stl + " e";
  18097. gst.colr = co.clr;
  18098. } else if (co.t == "p") {
  18099. prms.strk = co.stl != 5;
  18100. gst.lwidth = co.wid;
  18101. gst.COLR = co.clr;
  18102. } else if (co.t == "f") {
  18103. prms.fnt = co;
  18104. gst.font.Tf = co.nam;
  18105. gst.font.Tfs = Math.abs(co.hgh);
  18106. gst.font.Tun = co.und;
  18107. } else throw "e";
  18108. }
  18109. } else if (fnm == "DELETEOBJECT") {
  18110. var ind = rU32(buff, loff);
  18111. loff += 4;
  18112. if (tab[ind] != null) tab[ind] = null;else throw "e";
  18113. } else if (fnm == "CREATEBRUSHINDIRECT") {
  18114. oid = rU32(buff, loff);
  18115. loff += 4;
  18116. obj = {
  18117. t: "b"
  18118. };
  18119. obj.stl = rU32(buff, loff);
  18120. loff += 4;
  18121. obj.clr = [buff[loff] / 255, buff[loff + 1] / 255, buff[loff + 2] / 255];
  18122. loff += 4;
  18123. obj.htc = rU32(buff, loff);
  18124. loff += 4; //console.log(oid, obj);
  18125. } else if (fnm == "CREATEPEN" || fnm == "EXTCREATEPEN") {
  18126. oid = rU32(buff, loff);
  18127. loff += 4;
  18128. obj = {
  18129. t: "p"
  18130. };
  18131. if (fnm == "EXTCREATEPEN") {
  18132. loff += 16;
  18133. obj.stl = rU32(buff, loff);
  18134. loff += 4;
  18135. obj.wid = rU32(buff, loff);
  18136. loff += 4; //obj.stl = rU32(buff, loff);
  18137. loff += 4;
  18138. } else {
  18139. obj.stl = rU32(buff, loff);
  18140. loff += 4;
  18141. obj.wid = rU32(buff, loff);
  18142. loff += 4;
  18143. loff += 4;
  18144. }
  18145. obj.clr = [buff[loff] / 255, buff[loff + 1] / 255, buff[loff + 2] / 255];
  18146. loff += 4;
  18147. } else if (fnm == "EXTCREATEFONTINDIRECTW") {
  18148. oid = rU32(buff, loff);
  18149. loff += 4;
  18150. obj = {
  18151. t: "f",
  18152. nam: ""
  18153. };
  18154. obj.hgh = rI32(buff, loff);
  18155. loff += 4;
  18156. loff += 4 * 2;
  18157. obj.orn = rI32(buff, loff) / 10;
  18158. loff += 4;
  18159. var wgh = rU32(buff, loff);
  18160. loff += 4; //console.log(fnm, obj.orn, wgh);
  18161. //console.log(rU32(buff,loff), rU32(buff,loff+4), buff.slice(loff,loff+8));
  18162. obj.und = buff[loff + 1];
  18163. obj.stk = buff[loff + 2];
  18164. loff += 4 * 2;
  18165. while (rU(buff, loff) != 0) {
  18166. obj.nam += String.fromCharCode(rU(buff, loff));
  18167. loff += 2;
  18168. }
  18169. if (wgh > 500) obj.nam += "-Bold"; //console.log(wgh, obj.nam);
  18170. } else if (fnm == "EXTTEXTOUTW") {
  18171. //console.log(buff.slice(loff-8, loff-8+siz));
  18172. loff += 16;
  18173. var mod = rU32(buff, loff);
  18174. loff += 4; //console.log(mod);
  18175. var scx = rF32(buff, loff);
  18176. loff += 4;
  18177. var scy = rF32(buff, loff);
  18178. loff += 4;
  18179. var rfx = rI32(buff, loff);
  18180. loff += 4;
  18181. var rfy = rI32(buff, loff);
  18182. loff += 4; //console.log(mod, scx, scy,rfx,rfy);
  18183. gst.font.Tm = [1, 0, 0, -1, 0, 0];
  18184. exports.UDOC.M.rotate(gst.font.Tm, prms.fnt.orn * Math.PI / 180);
  18185. exports.UDOC.M.translate(gst.font.Tm, rfx, rfy);
  18186. var alg = prms.talg; //console.log(alg.toString(2));
  18187. if ((alg & 6) == 6) gst.font.Tal = 2;else if ((alg & 7) == 0) gst.font.Tal = 0;else throw alg + " e";
  18188. if ((alg & 24) == 24) {} // baseline
  18189. else if ((alg & 24) == 0) exports.UDOC.M.translate(gst.font.Tm, 0, gst.font.Tfs);else throw "e";
  18190. var crs = rU32(buff, loff);
  18191. loff += 4;
  18192. var ofs = rU32(buff, loff);
  18193. loff += 4;
  18194. var ops = rU32(buff, loff);
  18195. loff += 4; //if(ops!=0) throw "e";
  18196. //console.log(ofs,ops,crs);
  18197. loff += 16;
  18198. var ofD = rU32(buff, loff);
  18199. loff += 4; //console.log(ops, ofD, loff, ofs+off-8);
  18200. ofs += off - 8; //console.log(crs, ops);
  18201. var str = "";
  18202. for (var i = 0; i < crs; i++) {
  18203. var cc = rU(buff, ofs + i * 2);
  18204. str += String.fromCharCode(cc);
  18205. }
  18206. ;
  18207. var oclr = gst.colr;
  18208. gst.colr = prms.tclr; //console.log(str, gst.colr, gst.font.Tm);
  18209. //var otfs = gst.font.Tfs; gst.font.Tfs *= 1/gst.ctm[0];
  18210. genv.PutText(gst, str, str.length * gst.font.Tfs * 0.5);
  18211. gst.colr = oclr; //gst.font.Tfs = otfs;
  18212. //console.log(rfx, rfy, scx, ops, rcX, rcY, rcW, rcH, offDx, str);
  18213. } else if (fnm == "BEGINPATH") {
  18214. exports.UDOC.G.newPath(gst);
  18215. } else if (fnm == "ENDPATH") {} else if (fnm == "CLOSEFIGURE") exports.UDOC.G.closePath(gst);else if (fnm == "MOVETOEX") {
  18216. exports.UDOC.G.moveTo(gst, rI32(buff, loff), rI32(buff, loff + 4));
  18217. } else if (fnm == "LINETO") {
  18218. if (gst.pth.cmds.length == 0) {
  18219. var im = gst.ctm.slice(0);
  18220. exports.UDOC.M.invert(im);
  18221. var p = exports.UDOC.M.multPoint(im, gst.cpos);
  18222. exports.UDOC.G.moveTo(gst, p[0], p[1]);
  18223. }
  18224. exports.UDOC.G.lineTo(gst, rI32(buff, loff), rI32(buff, loff + 4));
  18225. } else if (fnm == "POLYGON" || fnm == "POLYGON16" || fnm == "POLYLINE" || fnm == "POLYLINE16" || fnm == "POLYLINETO" || fnm == "POLYLINETO16") {
  18226. loff += 16;
  18227. var ndf = fnm.startsWith("POLYGON"),
  18228. isTo = fnm.indexOf("TO") != -1;
  18229. var cnt = rU32(buff, loff);
  18230. loff += 4;
  18231. if (!isTo) exports.UDOC.G.newPath(gst);
  18232. loff = exports.FromEMF._drawPoly(buff, loff, cnt, gst, fnm.endsWith("16") ? 2 : 4, ndf, isTo);
  18233. if (!isTo) exports.FromEMF._draw(genv, gst, prms, ndf); //console.log(prms, gst.lwidth);
  18234. //console.log(JSON.parse(JSON.stringify(gst.pth)));
  18235. } else if (fnm == "POLYPOLYGON16") {
  18236. loff += 16;
  18237. var ndf = fnm.startsWith("POLYPOLYGON"),
  18238. isTo = fnm.indexOf("TO") != -1;
  18239. var nop = rU32(buff, loff);
  18240. loff += 4;
  18241. loff += 4;
  18242. var pi = loff;
  18243. loff += nop * 4;
  18244. if (!isTo) exports.UDOC.G.newPath(gst);
  18245. for (var i = 0; i < nop; i++) {
  18246. var ppp = rU(buff, pi + i * 4);
  18247. loff = exports.FromEMF._drawPoly(buff, loff, ppp, gst, fnm.endsWith("16") ? 2 : 4, ndf, isTo);
  18248. }
  18249. if (!isTo) exports.FromEMF._draw(genv, gst, prms, ndf);
  18250. } else if (fnm == "POLYBEZIER" || fnm == "POLYBEZIER16" || fnm == "POLYBEZIERTO" || fnm == "POLYBEZIERTO16") {
  18251. loff += 16;
  18252. var is16 = fnm.endsWith("16"),
  18253. rC = is16 ? rI : rI32,
  18254. nl = is16 ? 2 : 4;
  18255. var cnt = rU32(buff, loff);
  18256. loff += 4;
  18257. if (fnm.indexOf("TO") == -1) {
  18258. exports.UDOC.G.moveTo(gst, rC(buff, loff), rC(buff, loff + nl));
  18259. loff += 2 * nl;
  18260. cnt--;
  18261. }
  18262. while (cnt > 0) {
  18263. exports.UDOC.G.curveTo(gst, rC(buff, loff), rC(buff, loff + nl), rC(buff, loff + 2 * nl), rC(buff, loff + 3 * nl), rC(buff, loff + 4 * nl), rC(buff, loff + 5 * nl));
  18264. loff += 6 * nl;
  18265. cnt -= 3;
  18266. } //console.log(JSON.parse(JSON.stringify(gst.pth)));
  18267. } else if (fnm == "RECTANGLE" || fnm == "ELLIPSE") {
  18268. exports.UDOC.G.newPath(gst);
  18269. var bx = exports.FromEMF._readBox(buff, loff);
  18270. if (fnm == "RECTANGLE") {
  18271. exports.UDOC.G.moveTo(gst, bx[0], bx[1]);
  18272. exports.UDOC.G.lineTo(gst, bx[2], bx[1]);
  18273. exports.UDOC.G.lineTo(gst, bx[2], bx[3]);
  18274. exports.UDOC.G.lineTo(gst, bx[0], bx[3]);
  18275. } else {
  18276. var x = (bx[0] + bx[2]) / 2,
  18277. y = (bx[1] + bx[3]) / 2;
  18278. exports.UDOC.G.arc(gst, x, y, (bx[2] - bx[0]) / 2, 0, 2 * Math.PI, false);
  18279. }
  18280. exports.UDOC.G.closePath(gst);
  18281. exports.FromEMF._draw(genv, gst, prms, true); //console.log(prms, gst.lwidth);
  18282. } else if (fnm == "FILLPATH") genv.Fill(gst, false);else if (fnm == "STROKEPATH") genv.Stroke(gst);else if (fnm == "STROKEANDFILLPATH") {
  18283. genv.Fill(gst, false);
  18284. genv.Stroke(gst);
  18285. } else if (fnm == "SETWORLDTRANSFORM" || fnm == "MODIFYWORLDTRANSFORM") {
  18286. var mat = [];
  18287. for (var i = 0; i < 6; i++) {
  18288. mat.push(rF32(buff, loff + i * 4));
  18289. }
  18290. loff += 24; //console.log(fnm, gst.ctm.slice(0), mat);
  18291. if (fnm == "SETWORLDTRANSFORM") gst.ctm = mat;else {
  18292. var mod = rU32(buff, loff);
  18293. loff += 4;
  18294. if (mod == 2) {
  18295. var om = gst.ctm;
  18296. gst.ctm = mat;
  18297. exports.UDOC.M.concat(gst.ctm, om);
  18298. } else throw "e";
  18299. }
  18300. } else if (fnm == "SETSTRETCHBLTMODE") {
  18301. var sm = rU32(buff, loff);
  18302. loff += 4;
  18303. } else if (fnm == "STRETCHDIBITS") {
  18304. var bx = exports.FromEMF._readBox(buff, loff);
  18305. loff += 16;
  18306. var xD = rI32(buff, loff);
  18307. loff += 4;
  18308. var yD = rI32(buff, loff);
  18309. loff += 4;
  18310. var xS = rI32(buff, loff);
  18311. loff += 4;
  18312. var yS = rI32(buff, loff);
  18313. loff += 4;
  18314. var wS = rI32(buff, loff);
  18315. loff += 4;
  18316. var hS = rI32(buff, loff);
  18317. loff += 4;
  18318. var ofH = rU32(buff, loff) + off - 8;
  18319. loff += 4;
  18320. var szH = rU32(buff, loff);
  18321. loff += 4;
  18322. var ofB = rU32(buff, loff) + off - 8;
  18323. loff += 4;
  18324. var szB = rU32(buff, loff);
  18325. loff += 4;
  18326. var usg = rU32(buff, loff);
  18327. loff += 4;
  18328. if (usg != 0) throw "e";
  18329. var bop = rU32(buff, loff);
  18330. loff += 4;
  18331. var wD = rI32(buff, loff);
  18332. loff += 4;
  18333. var hD = rI32(buff, loff);
  18334. loff += 4; //console.log(bop, wD, hD);
  18335. //console.log(ofH, szH, ofB, szB, ofH+40);
  18336. //console.log(bx, xD,yD,wD,hD);
  18337. //console.log(xS,yS,wS,hS);
  18338. //console.log(ofH,szH,ofB,szB,usg,bop);
  18339. var hl = rU32(buff, ofH);
  18340. ofH += 4;
  18341. var w = rU32(buff, ofH);
  18342. ofH += 4;
  18343. var h = rU32(buff, ofH);
  18344. ofH += 4;
  18345. if (w != wS || h != hS) throw "e";
  18346. var ps = rU(buff, ofH);
  18347. ofH += 2;
  18348. var bc = rU(buff, ofH);
  18349. ofH += 2;
  18350. if (bc != 8 && bc != 24 && bc != 32) throw bc + " e";
  18351. var cpr = rU32(buff, ofH);
  18352. ofH += 4;
  18353. if (cpr != 0) throw cpr + " e";
  18354. var sz = rU32(buff, ofH);
  18355. ofH += 4;
  18356. var xpm = rU32(buff, ofH);
  18357. ofH += 4;
  18358. var ypm = rU32(buff, ofH);
  18359. ofH += 4;
  18360. var cu = rU32(buff, ofH);
  18361. ofH += 4;
  18362. var ci = rU32(buff, ofH);
  18363. ofH += 4; //console.log(hl, w, h, ps, bc, cpr, sz, xpm, ypm, cu, ci);
  18364. //console.log(hl,w,h,",",xS,yS,wS,hS,",",xD,yD,wD,hD,",",xpm,ypm);
  18365. var rl = Math.floor((w * ps * bc + 31 & ~31) / 8);
  18366. var img = new Uint8Array(w * h * 4);
  18367. if (bc == 8) {
  18368. for (var y = 0; y < h; y++) {
  18369. for (var x = 0; x < w; x++) {
  18370. var qi = y * w + x << 2,
  18371. ind = buff[ofB + (h - 1 - y) * rl + x] << 2;
  18372. img[qi] = buff[ofH + ind + 2];
  18373. img[qi + 1] = buff[ofH + ind + 1];
  18374. img[qi + 2] = buff[ofH + ind + 0];
  18375. img[qi + 3] = 255;
  18376. }
  18377. }
  18378. }
  18379. if (bc == 24) {
  18380. for (var y = 0; y < h; y++) {
  18381. for (var x = 0; x < w; x++) {
  18382. var qi = y * w + x << 2,
  18383. ti = ofB + (h - 1 - y) * rl + x * 3;
  18384. img[qi] = buff[ti + 2];
  18385. img[qi + 1] = buff[ti + 1];
  18386. img[qi + 2] = buff[ti + 0];
  18387. img[qi + 3] = 255;
  18388. }
  18389. }
  18390. }
  18391. if (bc == 32) {
  18392. for (var y = 0; y < h; y++) {
  18393. for (var x = 0; x < w; x++) {
  18394. var qi = y * w + x << 2,
  18395. ti = ofB + (h - 1 - y) * rl + x * 4;
  18396. img[qi] = buff[ti + 2];
  18397. img[qi + 1] = buff[ti + 1];
  18398. img[qi + 2] = buff[ti + 0];
  18399. img[qi + 3] = buff[ti + 3];
  18400. }
  18401. }
  18402. }
  18403. var ctm = gst.ctm.slice(0);
  18404. gst.ctm = [1, 0, 0, 1, 0, 0];
  18405. exports.UDOC.M.scale(gst.ctm, wD, -hD);
  18406. exports.UDOC.M.translate(gst.ctm, xD, yD + hD);
  18407. exports.UDOC.M.concat(gst.ctm, ctm);
  18408. genv.PutImage(gst, img, w, h);
  18409. gst.ctm = ctm;
  18410. } else {
  18411. console.log(fnm, siz);
  18412. }
  18413. if (obj != null) tab[oid] = obj;
  18414. off += siz - 8;
  18415. } //genv.Stroke(gst);
  18416. genv.ShowPage();
  18417. genv.Done();
  18418. };
  18419. exports.FromEMF._readBox = function (buff, off) {
  18420. var b = [];
  18421. for (var i = 0; i < 4; i++) {
  18422. b[i] = exports.FromEMF.B.readInt(buff, off + i * 4);
  18423. }
  18424. return b;
  18425. };
  18426. exports.FromEMF._updateCtm = function (prms, gst) {
  18427. var mat = [1, 0, 0, 1, 0, 0];
  18428. var wbb = prms.wbb,
  18429. bb = prms.bb,
  18430. vbb = prms.vbb && prms.vbb.length == 4 ? prms.vbb : prms.bb; //var y0 = bb[1], y1 = bb[3]; bb[1]=Math.min(y0,y1); bb[3]=Math.max(y0,y1);
  18431. exports.UDOC.M.translate(mat, -wbb[0], -wbb[1]);
  18432. exports.UDOC.M.scale(mat, 1 / wbb[2], 1 / wbb[3]);
  18433. exports.UDOC.M.scale(mat, vbb[2], vbb[3]); //UDOC.M.scale(mat, vbb[2]/(bb[2]-bb[0]), vbb[3]/(bb[3]-bb[1]));
  18434. //UDOC.M.scale(mat, bb[2]-bb[0],bb[3]-bb[1]);
  18435. gst.ctm = mat;
  18436. };
  18437. exports.FromEMF._draw = function (genv, gst, prms, needFill) {
  18438. if (prms.fill && needFill) genv.Fill(gst, false);
  18439. if (prms.strk && gst.lwidth != 0) genv.Stroke(gst);
  18440. };
  18441. exports.FromEMF._drawPoly = function (buff, off, ppp, gst, nl, clos, justLine) {
  18442. var rS = nl == 2 ? exports.FromEMF.B.readShort : exports.FromEMF.B.readInt;
  18443. for (var j = 0; j < ppp; j++) {
  18444. var px = rS(buff, off);
  18445. off += nl;
  18446. var py = rS(buff, off);
  18447. off += nl;
  18448. if (j == 0 && !justLine) exports.UDOC.G.moveTo(gst, px, py);else exports.UDOC.G.lineTo(gst, px, py);
  18449. }
  18450. if (clos) exports.UDOC.G.closePath(gst);
  18451. return off;
  18452. };
  18453. exports.FromEMF.B = {
  18454. uint8: new Uint8Array(4),
  18455. readShort: function readShort(buff, p) {
  18456. var u8 = exports.FromEMF.B.uint8;
  18457. u8[0] = buff[p];
  18458. u8[1] = buff[p + 1];
  18459. return exports.FromEMF.B.int16[0];
  18460. },
  18461. readUshort: function readUshort(buff, p) {
  18462. var u8 = exports.FromEMF.B.uint8;
  18463. u8[0] = buff[p];
  18464. u8[1] = buff[p + 1];
  18465. return exports.FromEMF.B.uint16[0];
  18466. },
  18467. readInt: function readInt(buff, p) {
  18468. var u8 = exports.FromEMF.B.uint8;
  18469. u8[0] = buff[p];
  18470. u8[1] = buff[p + 1];
  18471. u8[2] = buff[p + 2];
  18472. u8[3] = buff[p + 3];
  18473. return exports.FromEMF.B.int32[0];
  18474. },
  18475. readUint: function readUint(buff, p) {
  18476. var u8 = exports.FromEMF.B.uint8;
  18477. u8[0] = buff[p];
  18478. u8[1] = buff[p + 1];
  18479. u8[2] = buff[p + 2];
  18480. u8[3] = buff[p + 3];
  18481. return exports.FromEMF.B.uint32[0];
  18482. },
  18483. readFloat: function readFloat(buff, p) {
  18484. var u8 = exports.FromEMF.B.uint8;
  18485. u8[0] = buff[p];
  18486. u8[1] = buff[p + 1];
  18487. u8[2] = buff[p + 2];
  18488. u8[3] = buff[p + 3];
  18489. return exports.FromEMF.B.flot32[0];
  18490. },
  18491. readASCII: function readASCII(buff, p, l) {
  18492. var s = "";
  18493. for (var i = 0; i < l; i++) {
  18494. s += String.fromCharCode(buff[p + i]);
  18495. }
  18496. return s;
  18497. }
  18498. };
  18499. exports.FromEMF.B.int16 = new Int16Array(exports.FromEMF.B.uint8.buffer);
  18500. exports.FromEMF.B.uint16 = new Uint16Array(exports.FromEMF.B.uint8.buffer);
  18501. exports.FromEMF.B.int32 = new Int32Array(exports.FromEMF.B.uint8.buffer);
  18502. exports.FromEMF.B.uint32 = new Uint32Array(exports.FromEMF.B.uint8.buffer);
  18503. exports.FromEMF.B.flot32 = new Float32Array(exports.FromEMF.B.uint8.buffer);
  18504. exports.FromEMF.C = {
  18505. EMR_HEADER: 0x00000001,
  18506. EMR_POLYBEZIER: 0x00000002,
  18507. EMR_POLYGON: 0x00000003,
  18508. EMR_POLYLINE: 0x00000004,
  18509. EMR_POLYBEZIERTO: 0x00000005,
  18510. EMR_POLYLINETO: 0x00000006,
  18511. EMR_POLYPOLYLINE: 0x00000007,
  18512. EMR_POLYPOLYGON: 0x00000008,
  18513. EMR_SETWINDOWEXTEX: 0x00000009,
  18514. EMR_SETWINDOWORGEX: 0x0000000A,
  18515. EMR_SETVIEWPORTEXTEX: 0x0000000B,
  18516. EMR_SETVIEWPORTORGEX: 0x0000000C,
  18517. EMR_SETBRUSHORGEX: 0x0000000D,
  18518. EMR_EOF: 0x0000000E,
  18519. EMR_SETPIXELV: 0x0000000F,
  18520. EMR_SETMAPPERFLAGS: 0x00000010,
  18521. EMR_SETMAPMODE: 0x00000011,
  18522. EMR_SETBKMODE: 0x00000012,
  18523. EMR_SETPOLYFILLMODE: 0x00000013,
  18524. EMR_SETROP2: 0x00000014,
  18525. EMR_SETSTRETCHBLTMODE: 0x00000015,
  18526. EMR_SETTEXTALIGN: 0x00000016,
  18527. EMR_SETCOLORADJUSTMENT: 0x00000017,
  18528. EMR_SETTEXTCOLOR: 0x00000018,
  18529. EMR_SETBKCOLOR: 0x00000019,
  18530. EMR_OFFSETCLIPRGN: 0x0000001A,
  18531. EMR_MOVETOEX: 0x0000001B,
  18532. EMR_SETMETARGN: 0x0000001C,
  18533. EMR_EXCLUDECLIPRECT: 0x0000001D,
  18534. EMR_INTERSECTCLIPRECT: 0x0000001E,
  18535. EMR_SCALEVIEWPORTEXTEX: 0x0000001F,
  18536. EMR_SCALEWINDOWEXTEX: 0x00000020,
  18537. EMR_SAVEDC: 0x00000021,
  18538. EMR_RESTOREDC: 0x00000022,
  18539. EMR_SETWORLDTRANSFORM: 0x00000023,
  18540. EMR_MODIFYWORLDTRANSFORM: 0x00000024,
  18541. EMR_SELECTOBJECT: 0x00000025,
  18542. EMR_CREATEPEN: 0x00000026,
  18543. EMR_CREATEBRUSHINDIRECT: 0x00000027,
  18544. EMR_DELETEOBJECT: 0x00000028,
  18545. EMR_ANGLEARC: 0x00000029,
  18546. EMR_ELLIPSE: 0x0000002A,
  18547. EMR_RECTANGLE: 0x0000002B,
  18548. EMR_ROUNDRECT: 0x0000002C,
  18549. EMR_ARC: 0x0000002D,
  18550. EMR_CHORD: 0x0000002E,
  18551. EMR_PIE: 0x0000002F,
  18552. EMR_SELECTPALETTE: 0x00000030,
  18553. EMR_CREATEPALETTE: 0x00000031,
  18554. EMR_SETPALETTEENTRIES: 0x00000032,
  18555. EMR_RESIZEPALETTE: 0x00000033,
  18556. EMR_REALIZEPALETTE: 0x00000034,
  18557. EMR_EXTFLOODFILL: 0x00000035,
  18558. EMR_LINETO: 0x00000036,
  18559. EMR_ARCTO: 0x00000037,
  18560. EMR_POLYDRAW: 0x00000038,
  18561. EMR_SETARCDIRECTION: 0x00000039,
  18562. EMR_SETMITERLIMIT: 0x0000003A,
  18563. EMR_BEGINPATH: 0x0000003B,
  18564. EMR_ENDPATH: 0x0000003C,
  18565. EMR_CLOSEFIGURE: 0x0000003D,
  18566. EMR_FILLPATH: 0x0000003E,
  18567. EMR_STROKEANDFILLPATH: 0x0000003F,
  18568. EMR_STROKEPATH: 0x00000040,
  18569. EMR_FLATTENPATH: 0x00000041,
  18570. EMR_WIDENPATH: 0x00000042,
  18571. EMR_SELECTCLIPPATH: 0x00000043,
  18572. EMR_ABORTPATH: 0x00000044,
  18573. EMR_COMMENT: 0x00000046,
  18574. EMR_FILLRGN: 0x00000047,
  18575. EMR_FRAMERGN: 0x00000048,
  18576. EMR_INVERTRGN: 0x00000049,
  18577. EMR_PAINTRGN: 0x0000004A,
  18578. EMR_EXTSELECTCLIPRGN: 0x0000004B,
  18579. EMR_BITBLT: 0x0000004C,
  18580. EMR_STRETCHBLT: 0x0000004D,
  18581. EMR_MASKBLT: 0x0000004E,
  18582. EMR_PLGBLT: 0x0000004F,
  18583. EMR_SETDIBITSTODEVICE: 0x00000050,
  18584. EMR_STRETCHDIBITS: 0x00000051,
  18585. EMR_EXTCREATEFONTINDIRECTW: 0x00000052,
  18586. EMR_EXTTEXTOUTA: 0x00000053,
  18587. EMR_EXTTEXTOUTW: 0x00000054,
  18588. EMR_POLYBEZIER16: 0x00000055,
  18589. EMR_POLYGON16: 0x00000056,
  18590. EMR_POLYLINE16: 0x00000057,
  18591. EMR_POLYBEZIERTO16: 0x00000058,
  18592. EMR_POLYLINETO16: 0x00000059,
  18593. EMR_POLYPOLYLINE16: 0x0000005A,
  18594. EMR_POLYPOLYGON16: 0x0000005B,
  18595. EMR_POLYDRAW16: 0x0000005C,
  18596. EMR_CREATEMONOBRUSH: 0x0000005D,
  18597. EMR_CREATEDIBPATTERNBRUSHPT: 0x0000005E,
  18598. EMR_EXTCREATEPEN: 0x0000005F,
  18599. EMR_POLYTEXTOUTA: 0x00000060,
  18600. EMR_POLYTEXTOUTW: 0x00000061,
  18601. EMR_SETICMMODE: 0x00000062,
  18602. EMR_CREATECOLORSPACE: 0x00000063,
  18603. EMR_SETCOLORSPACE: 0x00000064,
  18604. EMR_DELETECOLORSPACE: 0x00000065,
  18605. EMR_GLSRECORD: 0x00000066,
  18606. EMR_GLSBOUNDEDRECORD: 0x00000067,
  18607. EMR_PIXELFORMAT: 0x00000068,
  18608. EMR_DRAWESCAPE: 0x00000069,
  18609. EMR_EXTESCAPE: 0x0000006A,
  18610. EMR_SMALLTEXTOUT: 0x0000006C,
  18611. EMR_FORCEUFIMAPPING: 0x0000006D,
  18612. EMR_NAMEDESCAPE: 0x0000006E,
  18613. EMR_COLORCORRECTPALETTE: 0x0000006F,
  18614. EMR_SETICMPROFILEA: 0x00000070,
  18615. EMR_SETICMPROFILEW: 0x00000071,
  18616. EMR_ALPHABLEND: 0x00000072,
  18617. EMR_SETLAYOUT: 0x00000073,
  18618. EMR_TRANSPARENTBLT: 0x00000074,
  18619. EMR_GRADIENTFILL: 0x00000076,
  18620. EMR_SETLINKEDUFIS: 0x00000077,
  18621. EMR_SETTEXTJUSTIFICATION: 0x00000078,
  18622. EMR_COLORMATCHTOTARGETW: 0x00000079,
  18623. EMR_CREATECOLORSPACEW: 0x0000007A
  18624. };
  18625. exports.FromEMF.K = []; // (function() {
  18626. // var inp, out, stt;
  18627. // inp = FromEMF.C; out = FromEMF.K; stt=4;
  18628. // for(var p in inp) out[inp[p]] = p.slice(stt);
  18629. // } )();
  18630. exports.ToContext2D = function (needPage, scale) {
  18631. this.canvas = document.createElement("canvas");
  18632. this.ctx = this.canvas.getContext("2d");
  18633. this.bb = null;
  18634. this.currPage = 0;
  18635. this.needPage = needPage;
  18636. this.scale = scale;
  18637. };
  18638. exports.ToContext2D.prototype.StartPage = function (x, y, w, h) {
  18639. if (this.currPage != this.needPage) return;
  18640. this.bb = [x, y, w, h];
  18641. var scl = this.scale,
  18642. dpr = window.devicePixelRatio;
  18643. var cnv = this.canvas,
  18644. ctx = this.ctx;
  18645. cnv.width = Math.round(w * scl);
  18646. cnv.height = Math.round(h * scl);
  18647. ctx.translate(0, h * scl);
  18648. ctx.scale(scl, -scl);
  18649. cnv.setAttribute("style", "border:1px solid; width:" + cnv.width / dpr + "px; height:" + cnv.height / dpr + "px");
  18650. };
  18651. exports.ToContext2D.prototype.Fill = function (gst, evenOdd) {
  18652. if (this.currPage != this.needPage) return;
  18653. var ctx = this.ctx;
  18654. ctx.beginPath();
  18655. this._setStyle(gst, ctx);
  18656. this._draw(gst.pth, ctx);
  18657. ctx.fill();
  18658. };
  18659. exports.ToContext2D.prototype.Stroke = function (gst) {
  18660. if (this.currPage != this.needPage) return;
  18661. var ctx = this.ctx;
  18662. ctx.beginPath();
  18663. this._setStyle(gst, ctx);
  18664. this._draw(gst.pth, ctx);
  18665. ctx.stroke();
  18666. };
  18667. exports.ToContext2D.prototype.PutText = function (gst, str, stw) {
  18668. if (this.currPage != this.needPage) return;
  18669. var scl = this._scale(gst.ctm);
  18670. var ctx = this.ctx;
  18671. this._setStyle(gst, ctx);
  18672. ctx.save();
  18673. var m = [1, 0, 0, -1, 0, 0];
  18674. this._concat(m, gst.font.Tm);
  18675. this._concat(m, gst.ctm); //console.log(str, m, gst); throw "e";
  18676. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  18677. ctx.fillText(str, 0, 0);
  18678. ctx.restore();
  18679. };
  18680. exports.ToContext2D.prototype.PutImage = function (gst, buff, w, h, msk) {
  18681. if (this.currPage != this.needPage) return;
  18682. var ctx = this.ctx;
  18683. if (buff.length == w * h * 4) {
  18684. buff = buff.slice(0);
  18685. if (msk && msk.length == w * h * 4) for (var i = 0; i < buff.length; i += 4) {
  18686. buff[i + 3] = msk[i + 1];
  18687. }
  18688. var cnv = document.createElement("canvas"),
  18689. cctx = cnv.getContext("2d");
  18690. cnv.width = w;
  18691. cnv.height = h;
  18692. var imgd = cctx.createImageData(w, h);
  18693. for (var i = 0; i < buff.length; i++) {
  18694. imgd.data[i] = buff[i];
  18695. }
  18696. cctx.putImageData(imgd, 0, 0);
  18697. ctx.save();
  18698. var m = [1, 0, 0, 1, 0, 0];
  18699. this._concat(m, [1 / w, 0, 0, -1 / h, 0, 1]);
  18700. this._concat(m, gst.ctm);
  18701. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  18702. ctx.drawImage(cnv, 0, 0);
  18703. ctx.restore();
  18704. }
  18705. };
  18706. exports.ToContext2D.prototype.ShowPage = function () {
  18707. this.currPage++;
  18708. };
  18709. exports.ToContext2D.prototype.Done = function () {};
  18710. function _flt(n) {
  18711. return "" + parseFloat(n.toFixed(2));
  18712. }
  18713. exports.ToContext2D.prototype._setStyle = function (gst, ctx) {
  18714. var scl = this._scale(gst.ctm);
  18715. ctx.fillStyle = this._getFill(gst.colr, gst.ca, ctx);
  18716. ctx.strokeStyle = this._getFill(gst.COLR, gst.CA, ctx);
  18717. ctx.lineCap = ["butt", "round", "square"][gst.lcap];
  18718. ctx.lineJoin = ["miter", "round", "bevel"][gst.ljoin];
  18719. ctx.lineWidth = gst.lwidth * scl;
  18720. var dsh = gst.dash.slice(0);
  18721. for (var i = 0; i < dsh.length; i++) {
  18722. dsh[i] = _flt(dsh[i] * scl);
  18723. }
  18724. ctx.setLineDash(dsh);
  18725. ctx.miterLimit = gst.mlimit * scl;
  18726. var fn = gst.font.Tf,
  18727. ln = fn.toLowerCase();
  18728. var p0 = ln.indexOf("bold") != -1 ? "bold " : "";
  18729. var p1 = ln.indexOf("italic") != -1 || ln.indexOf("oblique") != -1 ? "italic " : "";
  18730. ctx.font = p0 + p1 + gst.font.Tfs + "px \"" + fn + "\"";
  18731. };
  18732. exports.ToContext2D.prototype._getFill = function (colr, ca, ctx) {
  18733. if (colr.typ == null) return this._colr(colr, ca);else {
  18734. var grd = colr,
  18735. crd = grd.crds,
  18736. mat = grd.mat,
  18737. scl = this._scale(mat),
  18738. gf;
  18739. if (grd.typ == "lin") {
  18740. var p0 = this._multPoint(mat, crd.slice(0, 2)),
  18741. p1 = this._multPoint(mat, crd.slice(2));
  18742. gf = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  18743. } else if (grd.typ == "rad") {
  18744. var p0 = this._multPoint(mat, crd.slice(0, 2)),
  18745. p1 = this._multPoint(mat, crd.slice(3));
  18746. gf = ctx.createRadialGradient(p0[0], p0[1], crd[2] * scl, p1[0], p1[1], crd[5] * scl);
  18747. }
  18748. for (var i = 0; i < grd.grad.length; i++) {
  18749. gf.addColorStop(grd.grad[i][0], this._colr(grd.grad[i][1], ca));
  18750. }
  18751. return gf;
  18752. }
  18753. };
  18754. exports.ToContext2D.prototype._colr = function (c, a) {
  18755. return "rgba(" + Math.round(c[0] * 255) + "," + Math.round(c[1] * 255) + "," + Math.round(c[2] * 255) + "," + a + ")";
  18756. };
  18757. exports.ToContext2D.prototype._scale = function (m) {
  18758. return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
  18759. };
  18760. exports.ToContext2D.prototype._concat = function (m, w) {
  18761. var a = m[0],
  18762. b = m[1],
  18763. c = m[2],
  18764. d = m[3],
  18765. tx = m[4],
  18766. ty = m[5];
  18767. m[0] = a * w[0] + b * w[2];
  18768. m[1] = a * w[1] + b * w[3];
  18769. m[2] = c * w[0] + d * w[2];
  18770. m[3] = c * w[1] + d * w[3];
  18771. m[4] = tx * w[0] + ty * w[2] + w[4];
  18772. m[5] = tx * w[1] + ty * w[3] + w[5];
  18773. };
  18774. exports.ToContext2D.prototype._multPoint = function (m, p) {
  18775. var x = p[0],
  18776. y = p[1];
  18777. return [x * m[0] + y * m[2] + m[4], x * m[1] + y * m[3] + m[5]];
  18778. }, exports.ToContext2D.prototype._draw = function (path, ctx) {
  18779. var c = 0,
  18780. crds = path.crds;
  18781. for (var j = 0; j < path.cmds.length; j++) {
  18782. var cmd = path.cmds[j];
  18783. if (cmd == "M") {
  18784. ctx.moveTo(crds[c], crds[c + 1]);
  18785. c += 2;
  18786. } else if (cmd == "L") {
  18787. ctx.lineTo(crds[c], crds[c + 1]);
  18788. c += 2;
  18789. } else if (cmd == "C") {
  18790. ctx.bezierCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3], crds[c + 4], crds[c + 5]);
  18791. c += 6;
  18792. } else if (cmd == "Q") {
  18793. ctx.quadraticCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3]);
  18794. c += 4;
  18795. } else if (cmd == "Z") {
  18796. ctx.closePath();
  18797. }
  18798. }
  18799. };
  18800. },{}],94:[function(require,module,exports){
  18801. "use strict";
  18802. Object.defineProperty(exports, "__esModule", {
  18803. value: true
  18804. });
  18805. exports.getMultiFormulaValue = exports.getPeelOffX14 = exports.getTransR1C1ToSequence = exports.getSingleSequenceToNum = exports.getSqrefRawArrFormat = exports.getRegionSequence = exports.getMultiSequenceToNum = exports.getBinaryContent = exports.isContainMultiType = exports.isKoera = exports.isJapanese = exports.isChinese = exports.fromulaRef = exports.escapeCharacter = exports.generateRandomIndex = exports.LightenDarkenColor = exports.getRowHeightPixel = exports.getColumnWidthPixel = exports.getXmlAttibute = exports.getPxByEMUs = exports.getptToPxRatioByDPI = exports.getcellrange = exports.getRangetxt = void 0;
  18806. var constant_1 = require("./constant");
  18807. function getRangetxt(range, sheettxt) {
  18808. var row0 = range["row"][0],
  18809. row1 = range["row"][1];
  18810. var column0 = range["column"][0],
  18811. column1 = range["column"][1];
  18812. if (row0 == null && row1 == null) {
  18813. return sheettxt + chatatABC(column0) + ":" + chatatABC(column1);
  18814. } else if (column0 == null && column1 == null) {
  18815. return sheettxt + (row0 + 1) + ":" + (row1 + 1);
  18816. } else {
  18817. if (column0 == column1 && row0 == row1) {
  18818. return sheettxt + chatatABC(column0) + (row0 + 1);
  18819. } else {
  18820. return sheettxt + chatatABC(column0) + (row0 + 1) + ":" + chatatABC(column1) + (row1 + 1);
  18821. }
  18822. }
  18823. }
  18824. exports.getRangetxt = getRangetxt;
  18825. function getcellrange(txt, sheets, sheetId) {
  18826. if (sheets === void 0) {
  18827. sheets = {};
  18828. }
  18829. if (sheetId === void 0) {
  18830. sheetId = "1";
  18831. }
  18832. var val = txt.split("!");
  18833. var sheettxt = "",
  18834. rangetxt = "",
  18835. sheetIndex = -1;
  18836. if (val.length > 1) {
  18837. sheettxt = val[0];
  18838. rangetxt = val[1];
  18839. var si = sheets[sheettxt];
  18840. if (si == null) {
  18841. sheetIndex = parseInt(sheetId);
  18842. } else {
  18843. sheetIndex = parseInt(si);
  18844. }
  18845. } else {
  18846. sheetIndex = parseInt(sheetId);
  18847. rangetxt = val[0];
  18848. }
  18849. if (rangetxt.indexOf(":") == -1) {
  18850. var row = parseInt(rangetxt.replace(/[^0-9]/g, "")) - 1;
  18851. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  18852. if (!isNaN(row) && !isNaN(col)) {
  18853. return {
  18854. "row": [row, row],
  18855. "column": [col, col],
  18856. "sheetIndex": sheetIndex
  18857. };
  18858. } else {
  18859. return null;
  18860. }
  18861. } else {
  18862. var rangetxtArray = rangetxt.split(":");
  18863. var row = [],
  18864. col = [];
  18865. row[0] = parseInt(rangetxtArray[0].replace(/[^0-9]/g, "")) - 1;
  18866. row[1] = parseInt(rangetxtArray[1].replace(/[^0-9]/g, "")) - 1; // if (isNaN(row[0])) {
  18867. // row[0] = 0;
  18868. // }
  18869. // if (isNaN(row[1])) {
  18870. // row[1] = sheetdata.length - 1;
  18871. // }
  18872. if (row[0] > row[1]) {
  18873. return null;
  18874. }
  18875. col[0] = ABCatNum(rangetxtArray[0].replace(/[^A-Za-z]/g, ""));
  18876. col[1] = ABCatNum(rangetxtArray[1].replace(/[^A-Za-z]/g, "")); // if (isNaN(col[0])) {
  18877. // col[0] = 0;
  18878. // }
  18879. // if (isNaN(col[1])) {
  18880. // col[1] = sheetdata[0].length - 1;
  18881. // }
  18882. if (col[0] > col[1]) {
  18883. return null;
  18884. }
  18885. return {
  18886. "row": row,
  18887. "column": col,
  18888. "sheetIndex": sheetIndex
  18889. };
  18890. }
  18891. }
  18892. exports.getcellrange = getcellrange; //列下标 字母转数字
  18893. function ABCatNum(abc) {
  18894. abc = abc.toUpperCase();
  18895. var abc_len = abc.length;
  18896. if (abc_len == 0) {
  18897. return NaN;
  18898. }
  18899. var abc_array = abc.split("");
  18900. var wordlen = constant_1.columeHeader_word.length;
  18901. var ret = 0;
  18902. for (var i = abc_len - 1; i >= 0; i--) {
  18903. if (i == abc_len - 1) {
  18904. ret += constant_1.columeHeader_word_index[abc_array[i]];
  18905. } else {
  18906. ret += Math.pow(wordlen, abc_len - i - 1) * (constant_1.columeHeader_word_index[abc_array[i]] + 1);
  18907. }
  18908. }
  18909. return ret;
  18910. } //列下标 数字转字母
  18911. function chatatABC(index) {
  18912. var wordlen = constant_1.columeHeader_word.length;
  18913. if (index < wordlen) {
  18914. return constant_1.columeHeader_word[index];
  18915. } else {
  18916. var last = 0,
  18917. pre = 0,
  18918. ret = "";
  18919. var i = 1,
  18920. n = 0;
  18921. while (index >= wordlen / (wordlen - 1) * (Math.pow(wordlen, i++) - 1)) {
  18922. n = i;
  18923. }
  18924. var index_ab = index - wordlen / (wordlen - 1) * (Math.pow(wordlen, n - 1) - 1); //970
  18925. last = index_ab + 1;
  18926. for (var x = n; x > 0; x--) {
  18927. var last1 = last,
  18928. x1 = x; //-702=268, 3
  18929. if (x == 1) {
  18930. last1 = last1 % wordlen;
  18931. if (last1 == 0) {
  18932. last1 = 26;
  18933. }
  18934. return ret + constant_1.columeHeader_word[last1 - 1];
  18935. }
  18936. last1 = Math.ceil(last1 / Math.pow(wordlen, x - 1)); //last1 = last1 % wordlen;
  18937. ret += constant_1.columeHeader_word[last1 - 1];
  18938. if (x > 1) {
  18939. last = last - (last1 - 1) * wordlen;
  18940. }
  18941. }
  18942. }
  18943. }
  18944. /**
  18945. * @return ratio, default 0.75 1in = 2.54cm = 25.4mm = 72pt = 6pc, pt = 1/72 In, px = 1/dpi In
  18946. */
  18947. function getptToPxRatioByDPI() {
  18948. return 72 / 96;
  18949. }
  18950. exports.getptToPxRatioByDPI = getptToPxRatioByDPI;
  18951. /**
  18952. * @emus EMUs, Excel drawing unit
  18953. * @return pixel
  18954. */
  18955. function getPxByEMUs(emus) {
  18956. if (emus == null) {
  18957. return 0;
  18958. }
  18959. var inch = emus / 914400;
  18960. var pt = inch * 72;
  18961. var px = pt / getptToPxRatioByDPI();
  18962. return px;
  18963. }
  18964. exports.getPxByEMUs = getPxByEMUs;
  18965. /**
  18966. * @dom xml attribute object
  18967. * @attr attribute name
  18968. * @d if attribute is null, return default value
  18969. * @return attribute value
  18970. */
  18971. function getXmlAttibute(dom, attr, d) {
  18972. var value = dom[attr];
  18973. value = value == null ? d : value;
  18974. return value;
  18975. }
  18976. exports.getXmlAttibute = getXmlAttibute;
  18977. /**
  18978. * @columnWidth Excel column width
  18979. * @return pixel column width
  18980. */
  18981. function getColumnWidthPixel(columnWidth) {
  18982. var pix = Math.round((columnWidth - 0.83) * 8 + 5);
  18983. return pix;
  18984. }
  18985. exports.getColumnWidthPixel = getColumnWidthPixel;
  18986. /**
  18987. * @rowHeight Excel row height
  18988. * @return pixel row height
  18989. */
  18990. function getRowHeightPixel(rowHeight) {
  18991. var pix = Math.round(rowHeight / getptToPxRatioByDPI());
  18992. return pix;
  18993. }
  18994. exports.getRowHeightPixel = getRowHeightPixel;
  18995. function LightenDarkenColor(sixColor, tint) {
  18996. var hex = sixColor.substring(sixColor.length - 6, sixColor.length);
  18997. var rgbArray = hexToRgbArray("#" + hex);
  18998. var hslArray = rgbToHsl(rgbArray[0], rgbArray[1], rgbArray[2]);
  18999. if (tint > 0) {
  19000. hslArray[2] = hslArray[2] * (1.0 - tint) + tint;
  19001. } else if (tint < 0) {
  19002. hslArray[2] = hslArray[2] * (1.0 + tint);
  19003. } else {
  19004. return "#" + hex;
  19005. }
  19006. var newRgbArray = hslToRgb(hslArray[0], hslArray[1], hslArray[2]);
  19007. return rgbToHex("RGB(" + newRgbArray.join(",") + ")");
  19008. }
  19009. exports.LightenDarkenColor = LightenDarkenColor;
  19010. function rgbToHex(rgb) {
  19011. //十六进制颜色值的正则表达式
  19012. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是rgb颜色表示
  19013. if (/^(rgb|RGB)/.test(rgb)) {
  19014. var aColor = rgb.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
  19015. var strHex = "#";
  19016. for (var i = 0; i < aColor.length; i++) {
  19017. var hex = Number(aColor[i]).toString(16);
  19018. if (hex.length < 2) {
  19019. hex = '0' + hex;
  19020. }
  19021. strHex += hex;
  19022. }
  19023. if (strHex.length !== 7) {
  19024. strHex = rgb;
  19025. }
  19026. return strHex;
  19027. } else if (reg.test(rgb)) {
  19028. var aNum = rgb.replace(/#/, "").split("");
  19029. if (aNum.length === 6) {
  19030. return rgb;
  19031. } else if (aNum.length === 3) {
  19032. var numHex = "#";
  19033. for (var i = 0; i < aNum.length; i += 1) {
  19034. numHex += aNum[i] + aNum[i];
  19035. }
  19036. return numHex;
  19037. }
  19038. }
  19039. return rgb;
  19040. }
  19041. function hexToRgb(hex) {
  19042. var sColor = hex.toLowerCase(); //十六进制颜色值的正则表达式
  19043. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是16进制颜色
  19044. if (sColor && reg.test(sColor)) {
  19045. if (sColor.length === 4) {
  19046. var sColorNew = "#";
  19047. for (var i = 1; i < 4; i += 1) {
  19048. sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
  19049. }
  19050. sColor = sColorNew;
  19051. } //处理六位的颜色值
  19052. var sColorChange = [];
  19053. for (var i = 1; i < 7; i += 2) {
  19054. sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
  19055. }
  19056. return "RGB(" + sColorChange.join(",") + ")";
  19057. }
  19058. return sColor;
  19059. }
  19060. function hexToRgbArray(hex) {
  19061. var sColor = hex.toLowerCase(); //十六进制颜色值的正则表达式
  19062. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是16进制颜色
  19063. if (sColor && reg.test(sColor)) {
  19064. if (sColor.length === 4) {
  19065. var sColorNew = "#";
  19066. for (var i = 1; i < 4; i += 1) {
  19067. sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
  19068. }
  19069. sColor = sColorNew;
  19070. } //处理六位的颜色值
  19071. var sColorChange = [];
  19072. for (var i = 1; i < 7; i += 2) {
  19073. sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
  19074. }
  19075. return sColorChange;
  19076. }
  19077. return null;
  19078. }
  19079. /**
  19080. * HSL颜色值转换为RGB.
  19081. * 换算公式改编自 http://en.wikipedia.org/wiki/HSL_color_space.
  19082. * h, s, 和 l 设定在 [0, 1] 之间
  19083. * 返回的 r, g, 和 b 在 [0, 255]之间
  19084. *
  19085. * @param Number h 色相
  19086. * @param Number s 饱和度
  19087. * @param Number l 亮度
  19088. * @return Array RGB色值数值
  19089. */
  19090. function hslToRgb(h, s, l) {
  19091. var r, g, b;
  19092. if (s == 0) {
  19093. r = g = b = l; // achromatic
  19094. } else {
  19095. var hue2rgb = function hue2rgb(p, q, t) {
  19096. if (t < 0) t += 1;
  19097. if (t > 1) t -= 1;
  19098. if (t < 1 / 6) return p + (q - p) * 6 * t;
  19099. if (t < 1 / 2) return q;
  19100. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  19101. return p;
  19102. };
  19103. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  19104. var p = 2 * l - q;
  19105. r = hue2rgb(p, q, h + 1 / 3);
  19106. g = hue2rgb(p, q, h);
  19107. b = hue2rgb(p, q, h - 1 / 3);
  19108. }
  19109. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  19110. }
  19111. /**
  19112. * RGB 颜色值转换为 HSL.
  19113. * 转换公式参考自 http://en.wikipedia.org/wiki/HSL_color_space.
  19114. * r, g, 和 b 需要在 [0, 255] 范围内
  19115. * 返回的 h, s, 和 l 在 [0, 1] 之间
  19116. *
  19117. * @param Number r 红色色值
  19118. * @param Number g 绿色色值
  19119. * @param Number b 蓝色色值
  19120. * @return Array HSL各值数组
  19121. */
  19122. function rgbToHsl(r, g, b) {
  19123. r /= 255, g /= 255, b /= 255;
  19124. var max = Math.max(r, g, b),
  19125. min = Math.min(r, g, b);
  19126. var h,
  19127. s,
  19128. l = (max + min) / 2;
  19129. if (max == min) {
  19130. h = s = 0; // achromatic
  19131. } else {
  19132. var d = max - min;
  19133. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  19134. switch (max) {
  19135. case r:
  19136. h = (g - b) / d + (g < b ? 6 : 0);
  19137. break;
  19138. case g:
  19139. h = (b - r) / d + 2;
  19140. break;
  19141. case b:
  19142. h = (r - g) / d + 4;
  19143. break;
  19144. }
  19145. h /= 6;
  19146. }
  19147. return [h, s, l];
  19148. }
  19149. function generateRandomIndex(prefix) {
  19150. if (prefix == null) {
  19151. prefix = "Sheet";
  19152. }
  19153. var userAgent = window.navigator.userAgent.replace(/[^a-zA-Z0-9]/g, "").split("");
  19154. var mid = "";
  19155. for (var i = 0; i < 5; i++) {
  19156. mid += userAgent[Math.round(Math.random() * (userAgent.length - 1))];
  19157. }
  19158. var time = new Date().getTime();
  19159. return prefix + "_" + mid + "_" + time;
  19160. }
  19161. exports.generateRandomIndex = generateRandomIndex;
  19162. function escapeCharacter(str) {
  19163. if (str == null || str.length == 0) {
  19164. return str;
  19165. }
  19166. return str.replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ').replace(/&apos;/g, "'").replace(/&iexcl;/g, "¡").replace(/&cent;/g, "¢").replace(/&pound;/g, "£").replace(/&curren;/g, "¤").replace(/&yen;/g, "¥").replace(/&brvbar;/g, "¦").replace(/&sect;/g, "§").replace(/&uml;/g, "¨").replace(/&copy;/g, "©").replace(/&ordf;/g, "ª").replace(/&laquo;/g, "«").replace(/&not;/g, "¬").replace(/&shy;/g, "­").replace(/&reg;/g, "®").replace(/&macr;/g, "¯").replace(/&deg;/g, "°").replace(/&plusmn;/g, "±").replace(/&sup2;/g, "²").replace(/&sup3;/g, "³").replace(/&acute;/g, "´").replace(/&micro;/g, "µ").replace(/&para;/g, "¶").replace(/&middot;/g, "·").replace(/&cedil;/g, "¸").replace(/&sup1;/g, "¹").replace(/&ordm;/g, "º").replace(/&raquo;/g, "»").replace(/&frac14;/g, "¼").replace(/&frac12;/g, "½").replace(/&frac34;/g, "¾").replace(/&iquest;/g, "¿").replace(/&times;/g, "×").replace(/&divide;/g, "÷").replace(/&Agrave;/g, "À").replace(/&Aacute;/g, "Á").replace(/&Acirc;/g, "Â").replace(/&Atilde;/g, "Ã").replace(/&Auml;/g, "Ä").replace(/&Aring;/g, "Å").replace(/&AElig;/g, "Æ").replace(/&Ccedil;/g, "Ç").replace(/&Egrave;/g, "È").replace(/&Eacute;/g, "É").replace(/&Ecirc;/g, "Ê").replace(/&Euml;/g, "Ë").replace(/&Igrave;/g, "Ì").replace(/&Iacute;/g, "Í").replace(/&Icirc;/g, "Î").replace(/&Iuml;/g, "Ï").replace(/&ETH;/g, "Ð").replace(/&Ntilde;/g, "Ñ").replace(/&Ograve;/g, "Ò").replace(/&Oacute;/g, "Ó").replace(/&Ocirc;/g, "Ô").replace(/&Otilde;/g, "Õ").replace(/&Ouml;/g, "Ö").replace(/&Oslash;/g, "Ø").replace(/&Ugrave;/g, "Ù").replace(/&Uacute;/g, "Ú").replace(/&Ucirc;/g, "Û").replace(/&Uuml;/g, "Ü").replace(/&Yacute;/g, "Ý").replace(/&THORN;/g, "Þ").replace(/&szlig;/g, "ß").replace(/&agrave;/g, "à").replace(/&aacute;/g, "á").replace(/&acirc;/g, "â").replace(/&atilde;/g, "ã").replace(/&auml;/g, "ä").replace(/&aring;/g, "å").replace(/&aelig;/g, "æ").replace(/&ccedil;/g, "ç").replace(/&egrave;/g, "è").replace(/&eacute;/g, "é").replace(/&ecirc;/g, "ê").replace(/&euml;/g, "ë").replace(/&igrave;/g, "ì").replace(/&iacute;/g, "í").replace(/&icirc;/g, "î").replace(/&iuml;/g, "ï").replace(/&eth;/g, "ð").replace(/&ntilde;/g, "ñ").replace(/&ograve;/g, "ò").replace(/&oacute;/g, "ó").replace(/&ocirc;/g, "ô").replace(/&otilde;/g, "õ").replace(/&ouml;/g, "ö").replace(/&oslash;/g, "ø").replace(/&ugrave;/g, "ù").replace(/&uacute;/g, "ú").replace(/&ucirc;/g, "û").replace(/&uuml;/g, "ü").replace(/&yacute;/g, "ý").replace(/&thorn;/g, "þ").replace(/&yuml;/g, "ÿ");
  19167. }
  19168. exports.escapeCharacter = escapeCharacter;
  19169. var fromulaRef =
  19170. /** @class */
  19171. function () {
  19172. function fromulaRef() {}
  19173. fromulaRef.trim = function (str) {
  19174. if (str == null) {
  19175. str = "";
  19176. }
  19177. return str.replace(/(^\s*)|(\s*$)/g, "");
  19178. };
  19179. fromulaRef.functionCopy = function (txt, mode, step) {
  19180. var _this = this;
  19181. if (_this.operatorjson == null) {
  19182. var arr = _this.operator.split("|"),
  19183. op = {};
  19184. for (var i_1 = 0; i_1 < arr.length; i_1++) {
  19185. op[arr[i_1].toString()] = 1;
  19186. }
  19187. _this.operatorjson = op;
  19188. }
  19189. if (mode == null) {
  19190. mode = "down";
  19191. }
  19192. if (step == null) {
  19193. step = 1;
  19194. }
  19195. if (txt.substr(0, 1) == "=") {
  19196. txt = txt.substr(1);
  19197. }
  19198. var funcstack = txt.split("");
  19199. var i = 0,
  19200. str = "",
  19201. function_str = "",
  19202. ispassby = true;
  19203. var matchConfig = {
  19204. "bracket": 0,
  19205. "comma": 0,
  19206. "squote": 0,
  19207. "dquote": 0
  19208. };
  19209. while (i < funcstack.length) {
  19210. var s = funcstack[i];
  19211. if (s == "(" && matchConfig.dquote == 0) {
  19212. matchConfig.bracket += 1;
  19213. if (str.length > 0) {
  19214. function_str += str + "(";
  19215. } else {
  19216. function_str += "(";
  19217. }
  19218. str = "";
  19219. } else if (s == ")" && matchConfig.dquote == 0) {
  19220. matchConfig.bracket -= 1;
  19221. function_str += _this.functionCopy(str, mode, step) + ")";
  19222. str = "";
  19223. } else if (s == '"' && matchConfig.squote == 0) {
  19224. if (matchConfig.dquote > 0) {
  19225. function_str += str + '"';
  19226. matchConfig.dquote -= 1;
  19227. str = "";
  19228. } else {
  19229. matchConfig.dquote += 1;
  19230. str += '"';
  19231. }
  19232. } else if (s == ',' && matchConfig.dquote == 0) {
  19233. function_str += _this.functionCopy(str, mode, step) + ',';
  19234. str = "";
  19235. } else if (s == '&' && matchConfig.dquote == 0) {
  19236. if (str.length > 0) {
  19237. function_str += _this.functionCopy(str, mode, step) + "&";
  19238. str = "";
  19239. } else {
  19240. function_str += "&";
  19241. }
  19242. } else if (s in _this.operatorjson && matchConfig.dquote == 0) {
  19243. var s_next = "";
  19244. if (i + 1 < funcstack.length) {
  19245. s_next = funcstack[i + 1];
  19246. }
  19247. var p = i - 1,
  19248. s_pre = null;
  19249. if (p >= 0) {
  19250. do {
  19251. s_pre = funcstack[p--];
  19252. } while (p >= 0 && s_pre == " ");
  19253. }
  19254. if (s + s_next in _this.operatorjson) {
  19255. if (str.length > 0) {
  19256. function_str += _this.functionCopy(str, mode, step) + s + s_next;
  19257. str = "";
  19258. } else {
  19259. function_str += s + s_next;
  19260. }
  19261. i++;
  19262. } else if (!/[^0-9]/.test(s_next) && s == "-" && (s_pre == "(" || s_pre == null || s_pre == "," || s_pre == " " || s_pre in _this.operatorjson)) {
  19263. str += s;
  19264. } else {
  19265. if (str.length > 0) {
  19266. function_str += _this.functionCopy(str, mode, step) + s;
  19267. str = "";
  19268. } else {
  19269. function_str += s;
  19270. }
  19271. }
  19272. } else {
  19273. str += s;
  19274. }
  19275. if (i == funcstack.length - 1) {
  19276. if (_this.iscelldata(_this.trim(str))) {
  19277. if (mode == "down") {
  19278. function_str += _this.downparam(_this.trim(str), step);
  19279. } else if (mode == "up") {
  19280. function_str += _this.upparam(_this.trim(str), step);
  19281. } else if (mode == "left") {
  19282. function_str += _this.leftparam(_this.trim(str), step);
  19283. } else if (mode == "right") {
  19284. function_str += _this.rightparam(_this.trim(str), step);
  19285. }
  19286. } else {
  19287. function_str += _this.trim(str);
  19288. }
  19289. }
  19290. i++;
  19291. }
  19292. return function_str;
  19293. };
  19294. fromulaRef.downparam = function (txt, step) {
  19295. return this.updateparam("d", txt, step);
  19296. };
  19297. fromulaRef.upparam = function (txt, step) {
  19298. return this.updateparam("u", txt, step);
  19299. };
  19300. fromulaRef.leftparam = function (txt, step) {
  19301. return this.updateparam("l", txt, step);
  19302. };
  19303. fromulaRef.rightparam = function (txt, step) {
  19304. return this.updateparam("r", txt, step);
  19305. };
  19306. fromulaRef.updateparam = function (orient, txt, step) {
  19307. var _this = this;
  19308. var val = txt.split("!"),
  19309. rangetxt,
  19310. prefix = "";
  19311. if (val.length > 1) {
  19312. rangetxt = val[1];
  19313. prefix = val[0] + "!";
  19314. } else {
  19315. rangetxt = val[0];
  19316. }
  19317. if (rangetxt.indexOf(":") == -1) {
  19318. var row = parseInt(rangetxt.replace(/[^0-9]/g, ""));
  19319. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  19320. var freezonFuc = _this.isfreezonFuc(rangetxt);
  19321. var $row = freezonFuc[0] ? "$" : "",
  19322. $col = freezonFuc[1] ? "$" : "";
  19323. if (orient == "u" && !freezonFuc[0]) {
  19324. row -= step;
  19325. } else if (orient == "r" && !freezonFuc[1]) {
  19326. col += step;
  19327. } else if (orient == "l" && !freezonFuc[1]) {
  19328. col -= step;
  19329. } else if (!freezonFuc[0]) {
  19330. row += step;
  19331. }
  19332. if (row < 0 || col < 0) {
  19333. return _this.error.r;
  19334. }
  19335. if (!isNaN(row) && !isNaN(col)) {
  19336. return prefix + $col + chatatABC(col) + $row + row;
  19337. } else if (!isNaN(row)) {
  19338. return prefix + $row + row;
  19339. } else if (!isNaN(col)) {
  19340. return prefix + $col + chatatABC(col);
  19341. } else {
  19342. return txt;
  19343. }
  19344. } else {
  19345. rangetxt = rangetxt.split(":");
  19346. var row = [],
  19347. col = [];
  19348. row[0] = parseInt(rangetxt[0].replace(/[^0-9]/g, ""));
  19349. row[1] = parseInt(rangetxt[1].replace(/[^0-9]/g, ""));
  19350. if (row[0] > row[1]) {
  19351. return txt;
  19352. }
  19353. col[0] = ABCatNum(rangetxt[0].replace(/[^A-Za-z]/g, ""));
  19354. col[1] = ABCatNum(rangetxt[1].replace(/[^A-Za-z]/g, ""));
  19355. if (col[0] > col[1]) {
  19356. return txt;
  19357. }
  19358. var freezonFuc0 = _this.isfreezonFuc(rangetxt[0]);
  19359. var freezonFuc1 = _this.isfreezonFuc(rangetxt[1]);
  19360. var $row0 = freezonFuc0[0] ? "$" : "",
  19361. $col0 = freezonFuc0[1] ? "$" : "";
  19362. var $row1 = freezonFuc1[0] ? "$" : "",
  19363. $col1 = freezonFuc1[1] ? "$" : "";
  19364. if (orient == "u") {
  19365. if (!freezonFuc0[0]) {
  19366. row[0] -= step;
  19367. }
  19368. if (!freezonFuc1[0]) {
  19369. row[1] -= step;
  19370. }
  19371. } else if (orient == "r") {
  19372. if (!freezonFuc0[1]) {
  19373. col[0] += step;
  19374. }
  19375. if (!freezonFuc1[1]) {
  19376. col[1] += step;
  19377. }
  19378. } else if (orient == "l") {
  19379. if (!freezonFuc0[1]) {
  19380. col[0] -= step;
  19381. }
  19382. if (!freezonFuc1[1]) {
  19383. col[1] -= step;
  19384. }
  19385. } else {
  19386. if (!freezonFuc0[0]) {
  19387. row[0] += step;
  19388. }
  19389. if (!freezonFuc1[0]) {
  19390. row[1] += step;
  19391. }
  19392. }
  19393. if (row[0] < 0 || col[0] < 0) {
  19394. return _this.error.r;
  19395. }
  19396. if (isNaN(col[0]) && isNaN(col[1])) {
  19397. return prefix + $row0 + row[0] + ":" + $row1 + row[1];
  19398. } else if (isNaN(row[0]) && isNaN(row[1])) {
  19399. return prefix + $col0 + chatatABC(col[0]) + ":" + $col1 + chatatABC(col[1]);
  19400. } else {
  19401. return prefix + $col0 + chatatABC(col[0]) + $row0 + row[0] + ":" + $col1 + chatatABC(col[1]) + $row1 + row[1];
  19402. }
  19403. }
  19404. };
  19405. fromulaRef.iscelldata = function (txt) {
  19406. var val = txt.split("!"),
  19407. rangetxt;
  19408. if (val.length > 1) {
  19409. rangetxt = val[1];
  19410. } else {
  19411. rangetxt = val[0];
  19412. }
  19413. var reg_cell = /^(([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+))$/g; //增加正则判断单元格为字母+数字的格式:如 A1:B3
  19414. var reg_cellRange = /^(((([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+)))|((([a-zA-Z]+)|([$][a-zA-Z]+))))$/g; //增加正则判断单元格为字母+数字或字母的格式:如 A1:B3,A:A
  19415. if (rangetxt.indexOf(":") == -1) {
  19416. var row = parseInt(rangetxt.replace(/[^0-9]/g, "")) - 1;
  19417. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  19418. if (!isNaN(row) && !isNaN(col) && rangetxt.toString().match(reg_cell)) {
  19419. return true;
  19420. } else if (!isNaN(row)) {
  19421. return false;
  19422. } else if (!isNaN(col)) {
  19423. return false;
  19424. } else {
  19425. return false;
  19426. }
  19427. } else {
  19428. reg_cellRange = /^(((([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+)))|((([a-zA-Z]+)|([$][a-zA-Z]+)))|((([0-9]+)|([$][0-9]+s))))$/g;
  19429. rangetxt = rangetxt.split(":");
  19430. var row = [],
  19431. col = [];
  19432. row[0] = parseInt(rangetxt[0].replace(/[^0-9]/g, "")) - 1;
  19433. row[1] = parseInt(rangetxt[1].replace(/[^0-9]/g, "")) - 1;
  19434. if (row[0] > row[1]) {
  19435. return false;
  19436. }
  19437. col[0] = ABCatNum(rangetxt[0].replace(/[^A-Za-z]/g, ""));
  19438. col[1] = ABCatNum(rangetxt[1].replace(/[^A-Za-z]/g, ""));
  19439. if (col[0] > col[1]) {
  19440. return false;
  19441. }
  19442. if (rangetxt[0].toString().match(reg_cellRange) && rangetxt[1].toString().match(reg_cellRange)) {
  19443. return true;
  19444. } else {
  19445. return false;
  19446. }
  19447. }
  19448. };
  19449. fromulaRef.isfreezonFuc = function (txt) {
  19450. var row = txt.replace(/[^0-9]/g, "");
  19451. var col = txt.replace(/[^A-Za-z]/g, "");
  19452. var row$ = txt.substr(txt.indexOf(row) - 1, 1);
  19453. var col$ = txt.substr(txt.indexOf(col) - 1, 1);
  19454. var ret = [false, false];
  19455. if (row$ == "$") {
  19456. ret[0] = true;
  19457. }
  19458. if (col$ == "$") {
  19459. ret[1] = true;
  19460. }
  19461. return ret;
  19462. };
  19463. fromulaRef.operator = '==|!=|<>|<=|>=|=|+|-|>|<|/|*|%|&|^';
  19464. fromulaRef.error = {
  19465. v: "#VALUE!",
  19466. n: "#NAME?",
  19467. na: "#N/A",
  19468. r: "#REF!",
  19469. d: "#DIV/0!",
  19470. nm: "#NUM!",
  19471. nl: "#NULL!",
  19472. sp: "#SPILL!" //数组范围有其它值
  19473. };
  19474. fromulaRef.operatorjson = null;
  19475. return fromulaRef;
  19476. }();
  19477. exports.fromulaRef = fromulaRef;
  19478. function isChinese(temp) {
  19479. var re = /[^\u4e00-\u9fa5]/;
  19480. var reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
  19481. if (reg.test(temp)) return true;
  19482. if (re.test(temp)) return false;
  19483. return true;
  19484. }
  19485. exports.isChinese = isChinese;
  19486. function isJapanese(temp) {
  19487. var re = /[^\u0800-\u4e00]/;
  19488. if (re.test(temp)) return false;
  19489. return true;
  19490. }
  19491. exports.isJapanese = isJapanese;
  19492. function isKoera(chr) {
  19493. if (chr > 0x3130 && chr < 0x318F || chr >= 0xAC00 && chr <= 0xD7A3) {
  19494. return true;
  19495. }
  19496. return false;
  19497. }
  19498. exports.isKoera = isKoera;
  19499. function isContainMultiType(str) {
  19500. var isUnicode = false;
  19501. if (escape(str).indexOf("%u") > -1) {
  19502. isUnicode = true;
  19503. }
  19504. var isNot = false;
  19505. var reg = /[0-9a-z]/gi;
  19506. if (reg.test(str)) {
  19507. isNot = true;
  19508. }
  19509. var reEnSign = /[\x00-\xff]+/g;
  19510. if (reEnSign.test(str)) {
  19511. isNot = true;
  19512. }
  19513. if (isUnicode && isNot) {
  19514. return true;
  19515. }
  19516. return false;
  19517. }
  19518. exports.isContainMultiType = isContainMultiType;
  19519. function getBinaryContent(path, options) {
  19520. var promise, resolve, reject;
  19521. var callback;
  19522. if (!options) {
  19523. options = {};
  19524. } // taken from jQuery
  19525. var createStandardXHR = function createStandardXHR() {
  19526. try {
  19527. return new window.XMLHttpRequest();
  19528. } catch (e) {}
  19529. };
  19530. var createActiveXHR = function createActiveXHR() {
  19531. try {
  19532. return new window.ActiveXObject("Microsoft.XMLHTTP");
  19533. } catch (e) {}
  19534. }; // Create the request object
  19535. var createXHR = typeof window !== "undefined" && window.ActiveXObject ?
  19536. /* Microsoft failed to properly
  19537. * implement the XMLHttpRequest in IE7 (can't request local files),
  19538. * so we use the ActiveXObject when it is available
  19539. * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
  19540. * we need a fallback.
  19541. */
  19542. function () {
  19543. return createStandardXHR() || createActiveXHR();
  19544. } : // For all other browsers, use the standard XMLHttpRequest object
  19545. createStandardXHR; // backward compatible callback
  19546. if (typeof options === "function") {
  19547. callback = options;
  19548. options = {};
  19549. } else if (typeof options.callback === 'function') {
  19550. // callback inside options object
  19551. callback = options.callback;
  19552. }
  19553. resolve = function resolve(data) {
  19554. callback(null, data);
  19555. };
  19556. reject = function reject(err) {
  19557. callback(err, null);
  19558. };
  19559. try {
  19560. var xhr = createXHR();
  19561. xhr.open('GET', path, true); // recent browsers
  19562. if ("responseType" in xhr) {
  19563. xhr.responseType = "arraybuffer";
  19564. } // older browser
  19565. if (xhr.overrideMimeType) {
  19566. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  19567. }
  19568. xhr.onreadystatechange = function (event) {
  19569. // use `xhr` and not `this`... thanks IE
  19570. if (xhr.readyState === 4) {
  19571. if (xhr.status === 200 || xhr.status === 0) {
  19572. try {
  19573. resolve(function (xhr) {
  19574. // for xhr.responseText, the 0xFF mask is applied by JSZip
  19575. return xhr.response || xhr.responseText;
  19576. }(xhr));
  19577. } catch (err) {
  19578. reject(new Error(err));
  19579. }
  19580. } else {
  19581. reject(new Error("Ajax error for " + path + " : " + this.status + " " + this.statusText));
  19582. }
  19583. }
  19584. };
  19585. if (options.progress) {
  19586. xhr.onprogress = function (e) {
  19587. options.progress({
  19588. path: path,
  19589. originalEvent: e,
  19590. percent: e.loaded / e.total * 100,
  19591. loaded: e.loaded,
  19592. total: e.total
  19593. });
  19594. };
  19595. }
  19596. xhr.send();
  19597. } catch (e) {
  19598. reject(new Error(e), null);
  19599. } // returns a promise or undefined depending on whether a callback was
  19600. // provided
  19601. return promise;
  19602. }
  19603. exports.getBinaryContent = getBinaryContent;
  19604. /**
  19605. * multi sequence conversion
  19606. * example:
  19607. * 1、E14 -> 13_4
  19608. * 2、E14 J14 O14 T14 Y14 AD14 AI14 AN14 AS14 AX14 ->
  19609. * ['13_4', '13_9','13_14', '13_19', '13_24', '13_3', '13_8', '13_13', '13_18', '13_23']
  19610. * 3、E46:E47 -> ['45_4', '46_4']
  19611. *
  19612. * @param {string} sqref - before sequence
  19613. * @returns {string[]}
  19614. */
  19615. function getMultiSequenceToNum(sqref) {
  19616. if (!sqref || (sqref === null || sqref === void 0 ? void 0 : sqref.length) <= 0) return [];
  19617. sqref = sqref.toUpperCase();
  19618. var sqrefRawArr = sqref.split(" ");
  19619. var sqrefArr = sqrefRawArr.filter(function (e) {
  19620. return e && e.trim();
  19621. });
  19622. var sqrefLastArr = getSqrefRawArrFormat(sqrefArr);
  19623. var resArr = [];
  19624. for (var i = 0; i < sqrefLastArr.length; i++) {
  19625. var _res = getSingleSequenceToNum(sqrefLastArr[i]);
  19626. if (_res) resArr.push(_res);
  19627. }
  19628. return resArr;
  19629. }
  19630. exports.getMultiSequenceToNum = getMultiSequenceToNum;
  19631. /**
  19632. * get region sequence
  19633. * example:
  19634. * 1、[A1:C2'] -> ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']
  19635. *
  19636. * @param {string[]} arr - formats arr
  19637. * @returns {string[]} - after arr
  19638. */
  19639. function getRegionSequence(arr) {
  19640. var _a, _b;
  19641. var formatArr = [];
  19642. var regEn = new RegExp(/[A-Z]+|[0-9]+/g);
  19643. var startArr = (_a = arr[0]) === null || _a === void 0 ? void 0 : _a.match(regEn);
  19644. var lastArr = (_b = arr[1]) === null || _b === void 0 ? void 0 : _b.match(regEn);
  19645. var columnMax = Math.max.apply(Math, [ABCatNum(startArr[0]), ABCatNum(lastArr[0])]);
  19646. var columnMin = Math.min.apply(Math, [ABCatNum(startArr[0]), ABCatNum(lastArr[0])]);
  19647. var rowMax = Math.max.apply(Math, [parseInt(startArr[1]), parseInt(lastArr[1])]);
  19648. var rowMin = Math.min.apply(Math, [parseInt(startArr[1]), parseInt(lastArr[1])]);
  19649. for (var i = columnMin; i <= columnMax; i++) {
  19650. for (var j = rowMin; j <= rowMax; j++) {
  19651. formatArr.push("" + chatatABC(i) + j);
  19652. }
  19653. }
  19654. return formatArr;
  19655. }
  19656. exports.getRegionSequence = getRegionSequence;
  19657. /**
  19658. * unified processing of conversion formats
  19659. * example:
  19660. * 1、['E38', 'A1:C2'] -> ['E38', 'A1', 'A2', 'B1', 'B2', 'C1', 'C2']
  19661. *
  19662. * @param {string[]} arr - formats arr
  19663. * @returns {string[]} - after arr
  19664. */
  19665. function getSqrefRawArrFormat(arr) {
  19666. arr === null || arr === void 0 ? void 0 : arr.map(function (el) {
  19667. if (el.includes(":")) {
  19668. var tempArr = el.split(":");
  19669. if ((tempArr === null || tempArr === void 0 ? void 0 : tempArr.length) === 2) {
  19670. arr = arr.concat(getRegionSequence(tempArr));
  19671. arr.splice(arr.indexOf(el), 1);
  19672. }
  19673. }
  19674. });
  19675. var resultArr = arr.filter(function (value, index, array) {
  19676. return array.indexOf(value) === index;
  19677. });
  19678. return resultArr;
  19679. }
  19680. exports.getSqrefRawArrFormat = getSqrefRawArrFormat;
  19681. /**
  19682. * single sequence to number
  19683. * example:
  19684. * 1、A1 -> 0_0
  19685. * 2、ES14 -> 13_4
  19686. *
  19687. * @param {string} sqref - before sequence
  19688. * @returns {string} - after sequence
  19689. */
  19690. function getSingleSequenceToNum(sqref) {
  19691. var sqrefArray = sqref.match(/[A-Z]+|[0-9]+/g);
  19692. var sqrefLen = sqrefArray.length;
  19693. var regEn = new RegExp("^[A-Z]+$");
  19694. var ret = "";
  19695. for (var i = sqrefLen - 1; i >= 0; i--) {
  19696. var cur = sqrefArray[i];
  19697. if (regEn.test(cur)) {
  19698. ret += ABCatNum(cur) + "_";
  19699. } else {
  19700. ret += parseInt(cur) - 1 + "_";
  19701. }
  19702. }
  19703. return ret.substring(0, ret.length - 1);
  19704. }
  19705. exports.getSingleSequenceToNum = getSingleSequenceToNum;
  19706. /**
  19707. * R1C1 to Sequence
  19708. * example: sheet2!R1C1 => sheet!A1
  19709. *
  19710. * @param {string} value - R1C1 value
  19711. * @returns
  19712. */
  19713. function getTransR1C1ToSequence(value) {
  19714. if (!value && (value === null || value === void 0 ? void 0 : value.length) <= 0) return "";
  19715. var len = value.length;
  19716. var index = value.lastIndexOf("!");
  19717. var valueArr = [value.slice(0, index), value.slice(index + 1, len)];
  19718. var repStr = valueArr[1] || "";
  19719. var indexR = repStr.indexOf("R");
  19720. var indexC = repStr.indexOf("C");
  19721. var row = Number(repStr.slice(indexR + 1, indexC));
  19722. var column = chatatABC(Number(repStr.slice(indexC + 1, repStr === null || repStr === void 0 ? void 0 : repStr.length)) - 1);
  19723. return valueArr[0] + "!" + column + row;
  19724. }
  19725. exports.getTransR1C1ToSequence = getTransR1C1ToSequence;
  19726. /**
  19727. * strip x14 format data
  19728. *
  19729. * @param {string} value
  19730. * @returns {Object} - { formula, sqref }
  19731. */
  19732. function getPeelOffX14(value) {
  19733. var _a;
  19734. if (!value || (value === null || value === void 0 ? void 0 : value.length) <= 0) return {}; // formula
  19735. var formulaReg = new RegExp("</x14:formula[^]>", "g");
  19736. var lastIndex = (_a = value.match(formulaReg)) === null || _a === void 0 ? void 0 : _a.length;
  19737. var lastValue = "</x14:formula" + lastIndex + ">";
  19738. var lastValueEnd = value.indexOf(lastValue);
  19739. var formulaValue = value.substring(0, lastValueEnd + lastValue.length);
  19740. formulaValue = formulaValue.replace(/<xm:f>/g, "").replace(/<\/xm:f>/g, "").replace(/x14:/g, "").replace(/\/x14:/g, "");
  19741. var formula = formulaValue; // sqref
  19742. var xmSqrefLen = "<xm:sqref>".length;
  19743. var sqrefStart = value.indexOf("<xm:sqref>");
  19744. var sqrefEnd = value.indexOf("</xm:sqref>");
  19745. var sqref = value.substring(sqrefStart + xmSqrefLen, sqrefEnd);
  19746. return {
  19747. formula: formula,
  19748. sqref: sqref
  19749. };
  19750. }
  19751. exports.getPeelOffX14 = getPeelOffX14;
  19752. /**
  19753. * get the value in the formula
  19754. *
  19755. * @param {string} value - extracted value
  19756. * @returns {string[]}
  19757. */
  19758. function getMultiFormulaValue(value) {
  19759. var _a, _b;
  19760. if (!value || (value === null || value === void 0 ? void 0 : value.length) <= 0) return [];
  19761. var lenReg = new RegExp("formula", "g");
  19762. var len = (((_a = value.match(lenReg)) === null || _a === void 0 ? void 0 : _a.length) || 0) / 2;
  19763. if (len === 0) return [];
  19764. var retArr = [];
  19765. for (var i = 1; i <= len; i++) {
  19766. var startLen = (_b = "<formula" + i + ">") === null || _b === void 0 ? void 0 : _b.length;
  19767. var start = value.indexOf("<formula" + i + ">");
  19768. var end = value.indexOf("</formula" + i + ">");
  19769. var _value = value.substring(start + startLen, end);
  19770. retArr.push(escapeCharacter(_value.replace(/&quot;|^\"|\"$/g, "")));
  19771. }
  19772. return retArr;
  19773. }
  19774. exports.getMultiFormulaValue = getMultiFormulaValue;
  19775. },{"./constant":92}],95:[function(require,module,exports){
  19776. "use strict";
  19777. Object.defineProperty(exports, "__esModule", {
  19778. value: true
  19779. });
  19780. exports.LuckyExcel = void 0;
  19781. var LuckyFile_1 = require("./ToLuckySheet/LuckyFile"); // import {SecurityDoor,Car} from './content';
  19782. var HandleZip_1 = require("./HandleZip"); // //demo
  19783. // function demoHandler(){
  19784. // let upload = document.getElementById("Luckyexcel-demo-file");
  19785. // let selectADemo = document.getElementById("Luckyexcel-select-demo");
  19786. // let downlodDemo = document.getElementById("Luckyexcel-downlod-file");
  19787. // let mask = document.getElementById("lucky-mask-demo");
  19788. // if(upload){
  19789. // window.onload = () => {
  19790. // upload.addEventListener("change", function(evt){
  19791. // var files:FileList = (evt.target as any).files;
  19792. // if(files==null || files.length==0){
  19793. // alert("No files wait for import");
  19794. // return;
  19795. // }
  19796. // let name = files[0].name;
  19797. // let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
  19798. // if(suffix!="xlsx"){
  19799. // alert("Currently only supports the import of xlsx files");
  19800. // return;
  19801. // }
  19802. // LuckyExcel.transformExcelToLucky(files[0], function(exportJson:any, luckysheetfile:string){
  19803. // if(exportJson.sheets==null || exportJson.sheets.length==0){
  19804. // alert("Failed to read the content of the excel file, currently does not support xls files!");
  19805. // return;
  19806. // }
  19807. // console.log(exportJson, luckysheetfile);
  19808. // window.luckysheet.destroy();
  19809. // window.luckysheet.create({
  19810. // container: 'luckysheet', //luckysheet is the container id
  19811. // showinfobar:false,
  19812. // data:exportJson.sheets,
  19813. // title:exportJson.info.name,
  19814. // userInfo:exportJson.info.name.creator
  19815. // });
  19816. // });
  19817. // });
  19818. // selectADemo.addEventListener("change", function(evt){
  19819. // var obj:any = selectADemo;
  19820. // var index = obj.selectedIndex;
  19821. // var value = obj.options[index].value;
  19822. // var name = obj.options[index].innerHTML;
  19823. // if(value==""){
  19824. // return;
  19825. // }
  19826. // mask.style.display = "flex";
  19827. // LuckyExcel.transformExcelToLuckyByUrl(value, name, function(exportJson:any, luckysheetfile:string){
  19828. // if(exportJson.sheets==null || exportJson.sheets.length==0){
  19829. // alert("Failed to read the content of the excel file, currently does not support xls files!");
  19830. // return;
  19831. // }
  19832. // console.log(exportJson, luckysheetfile);
  19833. // mask.style.display = "none";
  19834. // window.luckysheet.destroy();
  19835. // window.luckysheet.create({
  19836. // container: 'luckysheet', //luckysheet is the container id
  19837. // showinfobar:false,
  19838. // data:exportJson.sheets,
  19839. // title:exportJson.info.name,
  19840. // userInfo:exportJson.info.name.creator
  19841. // });
  19842. // });
  19843. // });
  19844. // downlodDemo.addEventListener("click", function(evt){
  19845. // var obj:any = selectADemo;
  19846. // var index = obj.selectedIndex;
  19847. // var value = obj.options[index].value;
  19848. // if(value.length==0){
  19849. // alert("Please select a demo file");
  19850. // return;
  19851. // }
  19852. // var elemIF:any = document.getElementById("Lucky-download-frame");
  19853. // if(elemIF==null){
  19854. // elemIF = document.createElement("iframe");
  19855. // elemIF.style.display = "none";
  19856. // elemIF.id = "Lucky-download-frame";
  19857. // document.body.appendChild(elemIF);
  19858. // }
  19859. // elemIF.src = value;
  19860. // // elemIF.parentNode.removeChild(elemIF);
  19861. // });
  19862. // }
  19863. // }
  19864. // }
  19865. // demoHandler();
  19866. // api
  19867. var LuckyExcel =
  19868. /** @class */
  19869. function () {
  19870. function LuckyExcel() {}
  19871. LuckyExcel.transformExcelToLucky = function (excelFile, callback, errorHandler) {
  19872. var handleZip = new HandleZip_1.HandleZip(excelFile);
  19873. handleZip.unzipFile(function (files) {
  19874. var luckyFile = new LuckyFile_1.LuckyFile(files, excelFile.name);
  19875. var luckysheetfile = luckyFile.Parse();
  19876. var exportJson = JSON.parse(luckysheetfile);
  19877. if (callback != undefined) {
  19878. callback(exportJson, luckysheetfile);
  19879. }
  19880. }, function (err) {
  19881. if (errorHandler) {
  19882. errorHandler(err);
  19883. } else {
  19884. console.error(err);
  19885. }
  19886. });
  19887. };
  19888. LuckyExcel.transformExcelToLuckyByUrl = function (url, name, callBack, errorHandler) {
  19889. var handleZip = new HandleZip_1.HandleZip();
  19890. handleZip.unzipFileByUrl(url, function (files) {
  19891. var luckyFile = new LuckyFile_1.LuckyFile(files, name);
  19892. var luckysheetfile = luckyFile.Parse();
  19893. var exportJson = JSON.parse(luckysheetfile);
  19894. if (callBack != undefined) {
  19895. callBack(exportJson, luckysheetfile);
  19896. }
  19897. }, function (err) {
  19898. if (errorHandler) {
  19899. errorHandler(err);
  19900. } else {
  19901. console.error(err);
  19902. }
  19903. });
  19904. };
  19905. LuckyExcel.transformLuckyToExcel = function (LuckyFile, callBack, errorHandler) {};
  19906. return LuckyExcel;
  19907. }();
  19908. exports.LuckyExcel = LuckyExcel;
  19909. },{"./HandleZip":85,"./ToLuckySheet/LuckyFile":88}],96:[function(require,module,exports){
  19910. "use strict";
  19911. var main_1 = require("./main");
  19912. module.exports = main_1.LuckyExcel;
  19913. },{"./main":95}]},{},[96])(96)
  19914. });
  19915. //# sourceMappingURL=luckyexcel.umd.js.map