luckSheetExcel.js 1007 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904
  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 () {
  2. 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 })()({
  3. 1: [function (require, module, exports) {
  4. 'use strict'
  5. exports.byteLength = byteLength
  6. exports.toByteArray = toByteArray
  7. exports.fromByteArray = fromByteArray
  8. var lookup = []
  9. var revLookup = []
  10. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  11. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  12. for (var i = 0, len = code.length; i < len; ++i) {
  13. lookup[i] = code[i]
  14. revLookup[code.charCodeAt(i)] = i
  15. }
  16. String.prototype.startsWith = String.prototype.startsWith || function (str) {
  17. var reg = new RegExp("^" + str);
  18. return reg.test(this);
  19. }
  20. String.prototype.endsWith = String.prototype.endsWith || function (str) {
  21. var reg = new RegExp(str + "$");
  22. return reg.test(this);
  23. }
  24. // Support decoding URL-safe base64 strings, as Node.js does.
  25. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  26. revLookup['-'.charCodeAt(0)] = 62
  27. revLookup['_'.charCodeAt(0)] = 63
  28. function getLens(b64) {
  29. var len = b64.length
  30. if (len % 4 > 0) {
  31. throw new Error('Invalid string. Length must be a multiple of 4')
  32. }
  33. // Trim off extra bytes after placeholder bytes are found
  34. // See: https://github.com/beatgammit/base64-js/issues/42
  35. var validLen = b64.indexOf('=')
  36. if (validLen === -1) validLen = len
  37. var placeHoldersLen = validLen === len
  38. ? 0
  39. : 4 - (validLen % 4)
  40. return [validLen, placeHoldersLen]
  41. }
  42. // base64 is 4/3 + up to two characters of the original data
  43. function byteLength(b64) {
  44. var lens = getLens(b64)
  45. var validLen = lens[0]
  46. var placeHoldersLen = lens[1]
  47. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  48. }
  49. function _byteLength(b64, validLen, placeHoldersLen) {
  50. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  51. }
  52. function toByteArray(b64) {
  53. var tmp
  54. var lens = getLens(b64)
  55. var validLen = lens[0]
  56. var placeHoldersLen = lens[1]
  57. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  58. var curByte = 0
  59. // if there are placeholders, only get up to the last complete 4 chars
  60. var len = placeHoldersLen > 0
  61. ? validLen - 4
  62. : validLen
  63. var i
  64. for (i = 0; i < len; i += 4) {
  65. tmp =
  66. (revLookup[b64.charCodeAt(i)] << 18) |
  67. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  68. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  69. revLookup[b64.charCodeAt(i + 3)]
  70. arr[curByte++] = (tmp >> 16) & 0xFF
  71. arr[curByte++] = (tmp >> 8) & 0xFF
  72. arr[curByte++] = tmp & 0xFF
  73. }
  74. if (placeHoldersLen === 2) {
  75. tmp =
  76. (revLookup[b64.charCodeAt(i)] << 2) |
  77. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  78. arr[curByte++] = tmp & 0xFF
  79. }
  80. if (placeHoldersLen === 1) {
  81. tmp =
  82. (revLookup[b64.charCodeAt(i)] << 10) |
  83. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  84. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  85. arr[curByte++] = (tmp >> 8) & 0xFF
  86. arr[curByte++] = tmp & 0xFF
  87. }
  88. return arr
  89. }
  90. function tripletToBase64(num) {
  91. return lookup[num >> 18 & 0x3F] +
  92. lookup[num >> 12 & 0x3F] +
  93. lookup[num >> 6 & 0x3F] +
  94. lookup[num & 0x3F]
  95. }
  96. function encodeChunk(uint8, start, end) {
  97. var tmp
  98. var output = []
  99. for (var i = start; i < end; i += 3) {
  100. tmp =
  101. ((uint8[i] << 16) & 0xFF0000) +
  102. ((uint8[i + 1] << 8) & 0xFF00) +
  103. (uint8[i + 2] & 0xFF)
  104. output.push(tripletToBase64(tmp))
  105. }
  106. return output.join('')
  107. }
  108. function fromByteArray(uint8) {
  109. var tmp
  110. var len = uint8.length
  111. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  112. var parts = []
  113. var maxChunkLength = 16383 // must be multiple of 3
  114. // go through the array every three bytes, we'll deal with trailing stuff later
  115. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  116. parts.push(encodeChunk(
  117. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  118. ))
  119. }
  120. // pad the end with zeros, but make sure to not forget the extra bytes
  121. if (extraBytes === 1) {
  122. tmp = uint8[len - 1]
  123. parts.push(
  124. lookup[tmp >> 2] +
  125. lookup[(tmp << 4) & 0x3F] +
  126. '=='
  127. )
  128. } else if (extraBytes === 2) {
  129. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  130. parts.push(
  131. lookup[tmp >> 10] +
  132. lookup[(tmp >> 4) & 0x3F] +
  133. lookup[(tmp << 2) & 0x3F] +
  134. '='
  135. )
  136. }
  137. return parts.join('')
  138. }
  139. }, {}], 2: [function (require, module, exports) {
  140. }, {}], 3: [function (require, module, exports) {
  141. (function (Buffer) {
  142. /*!
  143. * The buffer module from node.js, for the browser.
  144. *
  145. * @author Feross Aboukhadijeh <https://feross.org>
  146. * @license MIT
  147. */
  148. /* eslint-disable no-proto */
  149. 'use strict'
  150. var base64 = require('base64-js')
  151. var ieee754 = require('ieee754')
  152. exports.Buffer = Buffer
  153. exports.SlowBuffer = SlowBuffer
  154. exports.INSPECT_MAX_BYTES = 50
  155. var K_MAX_LENGTH = 0x7fffffff
  156. exports.kMaxLength = K_MAX_LENGTH
  157. /**
  158. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  159. * === true Use Uint8Array implementation (fastest)
  160. * === false Print warning and recommend using `buffer` v4.x which has an Object
  161. * implementation (most compatible, even IE6)
  162. *
  163. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  164. * Opera 11.6+, iOS 4.2+.
  165. *
  166. * We report that the browser does not support typed arrays if the are not subclassable
  167. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  168. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  169. * for __proto__ and has a buggy typed array implementation.
  170. */
  171. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  172. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  173. typeof console.error === 'function') {
  174. console.error(
  175. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  176. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  177. )
  178. }
  179. function typedArraySupport() {
  180. // Can typed array instances can be augmented?
  181. try {
  182. var arr = new Uint8Array(1)
  183. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  184. return arr.foo() === 42
  185. } catch (e) {
  186. return false
  187. }
  188. }
  189. Object.defineProperty(Buffer.prototype, 'parent', {
  190. enumerable: true,
  191. get: function () {
  192. if (!Buffer.isBuffer(this)) return undefined
  193. return this.buffer
  194. }
  195. })
  196. Object.defineProperty(Buffer.prototype, 'offset', {
  197. enumerable: true,
  198. get: function () {
  199. if (!Buffer.isBuffer(this)) return undefined
  200. return this.byteOffset
  201. }
  202. })
  203. function createBuffer(length) {
  204. if (length > K_MAX_LENGTH) {
  205. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  206. }
  207. // Return an augmented `Uint8Array` instance
  208. var buf = new Uint8Array(length)
  209. buf.__proto__ = Buffer.prototype
  210. return buf
  211. }
  212. /**
  213. * The Buffer constructor returns instances of `Uint8Array` that have their
  214. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  215. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  216. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  217. * returns a single octet.
  218. *
  219. * The `Uint8Array` prototype remains unmodified.
  220. */
  221. function Buffer(arg, encodingOrOffset, length) {
  222. // Common case.
  223. if (typeof arg === 'number') {
  224. if (typeof encodingOrOffset === 'string') {
  225. throw new TypeError(
  226. 'The "string" argument must be of type string. Received type number'
  227. )
  228. }
  229. return allocUnsafe(arg)
  230. }
  231. return from(arg, encodingOrOffset, length)
  232. }
  233. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  234. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  235. Buffer[Symbol.species] === Buffer) {
  236. Object.defineProperty(Buffer, Symbol.species, {
  237. value: null,
  238. configurable: true,
  239. enumerable: false,
  240. writable: false
  241. })
  242. }
  243. Buffer.poolSize = 8192 // not used by this implementation
  244. function from(value, encodingOrOffset, length) {
  245. if (typeof value === 'string') {
  246. return fromString(value, encodingOrOffset)
  247. }
  248. if (ArrayBuffer.isView(value)) {
  249. return fromArrayLike(value)
  250. }
  251. if (value == null) {
  252. throw TypeError(
  253. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  254. 'or Array-like Object. Received type ' + (typeof value)
  255. )
  256. }
  257. if (isInstance(value, ArrayBuffer) ||
  258. (value && isInstance(value.buffer, ArrayBuffer))) {
  259. return fromArrayBuffer(value, encodingOrOffset, length)
  260. }
  261. if (typeof value === 'number') {
  262. throw new TypeError(
  263. 'The "value" argument must not be of type number. Received type number'
  264. )
  265. }
  266. var valueOf = value.valueOf && value.valueOf()
  267. if (valueOf != null && valueOf !== value) {
  268. return Buffer.from(valueOf, encodingOrOffset, length)
  269. }
  270. var b = fromObject(value)
  271. if (b) return b
  272. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  273. typeof value[Symbol.toPrimitive] === 'function') {
  274. return Buffer.from(
  275. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  276. )
  277. }
  278. throw new TypeError(
  279. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  280. 'or Array-like Object. Received type ' + (typeof value)
  281. )
  282. }
  283. /**
  284. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  285. * if value is a number.
  286. * Buffer.from(str[, encoding])
  287. * Buffer.from(array)
  288. * Buffer.from(buffer)
  289. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  290. **/
  291. Buffer.from = function (value, encodingOrOffset, length) {
  292. return from(value, encodingOrOffset, length)
  293. }
  294. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  295. // https://github.com/feross/buffer/pull/148
  296. Buffer.prototype.__proto__ = Uint8Array.prototype
  297. Buffer.__proto__ = Uint8Array
  298. function assertSize(size) {
  299. if (typeof size !== 'number') {
  300. throw new TypeError('"size" argument must be of type number')
  301. } else if (size < 0) {
  302. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  303. }
  304. }
  305. function alloc(size, fill, encoding) {
  306. assertSize(size)
  307. if (size <= 0) {
  308. return createBuffer(size)
  309. }
  310. if (fill !== undefined) {
  311. // Only pay attention to encoding if it's a string. This
  312. // prevents accidentally sending in a number that would
  313. // be interpretted as a start offset.
  314. return typeof encoding === 'string'
  315. ? createBuffer(size).fill(fill, encoding)
  316. : createBuffer(size).fill(fill)
  317. }
  318. return createBuffer(size)
  319. }
  320. /**
  321. * Creates a new filled Buffer instance.
  322. * alloc(size[, fill[, encoding]])
  323. **/
  324. Buffer.alloc = function (size, fill, encoding) {
  325. return alloc(size, fill, encoding)
  326. }
  327. function allocUnsafe(size) {
  328. assertSize(size)
  329. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  330. }
  331. /**
  332. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  333. * */
  334. Buffer.allocUnsafe = function (size) {
  335. return allocUnsafe(size)
  336. }
  337. /**
  338. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  339. */
  340. Buffer.allocUnsafeSlow = function (size) {
  341. return allocUnsafe(size)
  342. }
  343. function fromString(string, encoding) {
  344. if (typeof encoding !== 'string' || encoding === '') {
  345. encoding = 'utf8'
  346. }
  347. if (!Buffer.isEncoding(encoding)) {
  348. throw new TypeError('Unknown encoding: ' + encoding)
  349. }
  350. var length = byteLength(string, encoding) | 0
  351. var buf = createBuffer(length)
  352. var actual = buf.write(string, encoding)
  353. if (actual !== length) {
  354. // Writing a hex string, for example, that contains invalid characters will
  355. // cause everything after the first invalid character to be ignored. (e.g.
  356. // 'abxxcd' will be treated as 'ab')
  357. buf = buf.slice(0, actual)
  358. }
  359. return buf
  360. }
  361. function fromArrayLike(array) {
  362. var length = array.length < 0 ? 0 : checked(array.length) | 0
  363. var buf = createBuffer(length)
  364. for (var i = 0; i < length; i += 1) {
  365. buf[i] = array[i] & 255
  366. }
  367. return buf
  368. }
  369. function fromArrayBuffer(array, byteOffset, length) {
  370. if (byteOffset < 0 || array.byteLength < byteOffset) {
  371. throw new RangeError('"offset" is outside of buffer bounds')
  372. }
  373. if (array.byteLength < byteOffset + (length || 0)) {
  374. throw new RangeError('"length" is outside of buffer bounds')
  375. }
  376. var buf
  377. if (byteOffset === undefined && length === undefined) {
  378. buf = new Uint8Array(array)
  379. } else if (length === undefined) {
  380. buf = new Uint8Array(array, byteOffset)
  381. } else {
  382. buf = new Uint8Array(array, byteOffset, length)
  383. }
  384. // Return an augmented `Uint8Array` instance
  385. buf.__proto__ = Buffer.prototype
  386. return buf
  387. }
  388. function fromObject(obj) {
  389. if (Buffer.isBuffer(obj)) {
  390. var len = checked(obj.length) | 0
  391. var buf = createBuffer(len)
  392. if (buf.length === 0) {
  393. return buf
  394. }
  395. obj.copy(buf, 0, 0, len)
  396. return buf
  397. }
  398. if (obj.length !== undefined) {
  399. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  400. return createBuffer(0)
  401. }
  402. return fromArrayLike(obj)
  403. }
  404. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  405. return fromArrayLike(obj.data)
  406. }
  407. }
  408. function checked(length) {
  409. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  410. // length is NaN (which is otherwise coerced to zero.)
  411. if (length >= K_MAX_LENGTH) {
  412. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  413. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  414. }
  415. return length | 0
  416. }
  417. function SlowBuffer(length) {
  418. if (+length != length) { // eslint-disable-line eqeqeq
  419. length = 0
  420. }
  421. return Buffer.alloc(+length)
  422. }
  423. Buffer.isBuffer = function isBuffer(b) {
  424. return b != null && b._isBuffer === true &&
  425. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  426. }
  427. Buffer.compare = function compare(a, b) {
  428. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  429. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  430. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  431. throw new TypeError(
  432. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  433. )
  434. }
  435. if (a === b) return 0
  436. var x = a.length
  437. var y = b.length
  438. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  439. if (a[i] !== b[i]) {
  440. x = a[i]
  441. y = b[i]
  442. break
  443. }
  444. }
  445. if (x < y) return -1
  446. if (y < x) return 1
  447. return 0
  448. }
  449. Buffer.isEncoding = function isEncoding(encoding) {
  450. switch (String(encoding).toLowerCase()) {
  451. case 'hex':
  452. case 'utf8':
  453. case 'utf-8':
  454. case 'ascii':
  455. case 'latin1':
  456. case 'binary':
  457. case 'base64':
  458. case 'ucs2':
  459. case 'ucs-2':
  460. case 'utf16le':
  461. case 'utf-16le':
  462. return true
  463. default:
  464. return false
  465. }
  466. }
  467. Buffer.concat = function concat(list, length) {
  468. if (!Array.isArray(list)) {
  469. throw new TypeError('"list" argument must be an Array of Buffers')
  470. }
  471. if (list.length === 0) {
  472. return Buffer.alloc(0)
  473. }
  474. var i
  475. if (length === undefined) {
  476. length = 0
  477. for (i = 0; i < list.length; ++i) {
  478. length += list[i].length
  479. }
  480. }
  481. var buffer = Buffer.allocUnsafe(length)
  482. var pos = 0
  483. for (i = 0; i < list.length; ++i) {
  484. var buf = list[i]
  485. if (isInstance(buf, Uint8Array)) {
  486. buf = Buffer.from(buf)
  487. }
  488. if (!Buffer.isBuffer(buf)) {
  489. throw new TypeError('"list" argument must be an Array of Buffers')
  490. }
  491. buf.copy(buffer, pos)
  492. pos += buf.length
  493. }
  494. return buffer
  495. }
  496. function byteLength(string, encoding) {
  497. if (Buffer.isBuffer(string)) {
  498. return string.length
  499. }
  500. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  501. return string.byteLength
  502. }
  503. if (typeof string !== 'string') {
  504. throw new TypeError(
  505. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  506. 'Received type ' + typeof string
  507. )
  508. }
  509. var len = string.length
  510. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  511. if (!mustMatch && len === 0) return 0
  512. // Use a for loop to avoid recursion
  513. var loweredCase = false
  514. for (; ;) {
  515. switch (encoding) {
  516. case 'ascii':
  517. case 'latin1':
  518. case 'binary':
  519. return len
  520. case 'utf8':
  521. case 'utf-8':
  522. return utf8ToBytes(string).length
  523. case 'ucs2':
  524. case 'ucs-2':
  525. case 'utf16le':
  526. case 'utf-16le':
  527. return len * 2
  528. case 'hex':
  529. return len >>> 1
  530. case 'base64':
  531. return base64ToBytes(string).length
  532. default:
  533. if (loweredCase) {
  534. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  535. }
  536. encoding = ('' + encoding).toLowerCase()
  537. loweredCase = true
  538. }
  539. }
  540. }
  541. Buffer.byteLength = byteLength
  542. function slowToString(encoding, start, end) {
  543. var loweredCase = false
  544. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  545. // property of a typed array.
  546. // This behaves neither like String nor Uint8Array in that we set start/end
  547. // to their upper/lower bounds if the value passed is out of range.
  548. // undefined is handled specially as per ECMA-262 6th Edition,
  549. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  550. if (start === undefined || start < 0) {
  551. start = 0
  552. }
  553. // Return early if start > this.length. Done here to prevent potential uint32
  554. // coercion fail below.
  555. if (start > this.length) {
  556. return ''
  557. }
  558. if (end === undefined || end > this.length) {
  559. end = this.length
  560. }
  561. if (end <= 0) {
  562. return ''
  563. }
  564. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  565. end >>>= 0
  566. start >>>= 0
  567. if (end <= start) {
  568. return ''
  569. }
  570. if (!encoding) encoding = 'utf8'
  571. while (true) {
  572. switch (encoding) {
  573. case 'hex':
  574. return hexSlice(this, start, end)
  575. case 'utf8':
  576. case 'utf-8':
  577. return utf8Slice(this, start, end)
  578. case 'ascii':
  579. return asciiSlice(this, start, end)
  580. case 'latin1':
  581. case 'binary':
  582. return latin1Slice(this, start, end)
  583. case 'base64':
  584. return base64Slice(this, start, end)
  585. case 'ucs2':
  586. case 'ucs-2':
  587. case 'utf16le':
  588. case 'utf-16le':
  589. return utf16leSlice(this, start, end)
  590. default:
  591. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  592. encoding = (encoding + '').toLowerCase()
  593. loweredCase = true
  594. }
  595. }
  596. }
  597. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  598. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  599. // reliably in a browserify context because there could be multiple different
  600. // copies of the 'buffer' package in use. This method works even for Buffer
  601. // instances that were created from another copy of the `buffer` package.
  602. // See: https://github.com/feross/buffer/issues/154
  603. Buffer.prototype._isBuffer = true
  604. function swap(b, n, m) {
  605. var i = b[n]
  606. b[n] = b[m]
  607. b[m] = i
  608. }
  609. Buffer.prototype.swap16 = function swap16() {
  610. var len = this.length
  611. if (len % 2 !== 0) {
  612. throw new RangeError('Buffer size must be a multiple of 16-bits')
  613. }
  614. for (var i = 0; i < len; i += 2) {
  615. swap(this, i, i + 1)
  616. }
  617. return this
  618. }
  619. Buffer.prototype.swap32 = function swap32() {
  620. var len = this.length
  621. if (len % 4 !== 0) {
  622. throw new RangeError('Buffer size must be a multiple of 32-bits')
  623. }
  624. for (var i = 0; i < len; i += 4) {
  625. swap(this, i, i + 3)
  626. swap(this, i + 1, i + 2)
  627. }
  628. return this
  629. }
  630. Buffer.prototype.swap64 = function swap64() {
  631. var len = this.length
  632. if (len % 8 !== 0) {
  633. throw new RangeError('Buffer size must be a multiple of 64-bits')
  634. }
  635. for (var i = 0; i < len; i += 8) {
  636. swap(this, i, i + 7)
  637. swap(this, i + 1, i + 6)
  638. swap(this, i + 2, i + 5)
  639. swap(this, i + 3, i + 4)
  640. }
  641. return this
  642. }
  643. Buffer.prototype.toString = function toString() {
  644. var length = this.length
  645. if (length === 0) return ''
  646. if (arguments.length === 0) return utf8Slice(this, 0, length)
  647. return slowToString.apply(this, arguments)
  648. }
  649. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  650. Buffer.prototype.equals = function equals(b) {
  651. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  652. if (this === b) return true
  653. return Buffer.compare(this, b) === 0
  654. }
  655. Buffer.prototype.inspect = function inspect() {
  656. var str = ''
  657. var max = exports.INSPECT_MAX_BYTES
  658. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  659. if (this.length > max) str += ' ... '
  660. return '<Buffer ' + str + '>'
  661. }
  662. Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  663. if (isInstance(target, Uint8Array)) {
  664. target = Buffer.from(target, target.offset, target.byteLength)
  665. }
  666. if (!Buffer.isBuffer(target)) {
  667. throw new TypeError(
  668. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  669. 'Received type ' + (typeof target)
  670. )
  671. }
  672. if (start === undefined) {
  673. start = 0
  674. }
  675. if (end === undefined) {
  676. end = target ? target.length : 0
  677. }
  678. if (thisStart === undefined) {
  679. thisStart = 0
  680. }
  681. if (thisEnd === undefined) {
  682. thisEnd = this.length
  683. }
  684. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  685. throw new RangeError('out of range index')
  686. }
  687. if (thisStart >= thisEnd && start >= end) {
  688. return 0
  689. }
  690. if (thisStart >= thisEnd) {
  691. return -1
  692. }
  693. if (start >= end) {
  694. return 1
  695. }
  696. start >>>= 0
  697. end >>>= 0
  698. thisStart >>>= 0
  699. thisEnd >>>= 0
  700. if (this === target) return 0
  701. var x = thisEnd - thisStart
  702. var y = end - start
  703. var len = Math.min(x, y)
  704. var thisCopy = this.slice(thisStart, thisEnd)
  705. var targetCopy = target.slice(start, end)
  706. for (var i = 0; i < len; ++i) {
  707. if (thisCopy[i] !== targetCopy[i]) {
  708. x = thisCopy[i]
  709. y = targetCopy[i]
  710. break
  711. }
  712. }
  713. if (x < y) return -1
  714. if (y < x) return 1
  715. return 0
  716. }
  717. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  718. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  719. //
  720. // Arguments:
  721. // - buffer - a Buffer to search
  722. // - val - a string, Buffer, or number
  723. // - byteOffset - an index into `buffer`; will be clamped to an int32
  724. // - encoding - an optional encoding, relevant is val is a string
  725. // - dir - true for indexOf, false for lastIndexOf
  726. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  727. // Empty buffer means no match
  728. if (buffer.length === 0) return -1
  729. // Normalize byteOffset
  730. if (typeof byteOffset === 'string') {
  731. encoding = byteOffset
  732. byteOffset = 0
  733. } else if (byteOffset > 0x7fffffff) {
  734. byteOffset = 0x7fffffff
  735. } else if (byteOffset < -0x80000000) {
  736. byteOffset = -0x80000000
  737. }
  738. byteOffset = +byteOffset // Coerce to Number.
  739. if (numberIsNaN(byteOffset)) {
  740. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  741. byteOffset = dir ? 0 : (buffer.length - 1)
  742. }
  743. // Normalize byteOffset: negative offsets start from the end of the buffer
  744. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  745. if (byteOffset >= buffer.length) {
  746. if (dir) return -1
  747. else byteOffset = buffer.length - 1
  748. } else if (byteOffset < 0) {
  749. if (dir) byteOffset = 0
  750. else return -1
  751. }
  752. // Normalize val
  753. if (typeof val === 'string') {
  754. val = Buffer.from(val, encoding)
  755. }
  756. // Finally, search either indexOf (if dir is true) or lastIndexOf
  757. if (Buffer.isBuffer(val)) {
  758. // Special case: looking for empty string/buffer always fails
  759. if (val.length === 0) {
  760. return -1
  761. }
  762. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  763. } else if (typeof val === 'number') {
  764. val = val & 0xFF // Search for a byte value [0-255]
  765. if (typeof Uint8Array.prototype.indexOf === 'function') {
  766. if (dir) {
  767. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  768. } else {
  769. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  770. }
  771. }
  772. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  773. }
  774. throw new TypeError('val must be string, number or Buffer')
  775. }
  776. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  777. var indexSize = 1
  778. var arrLength = arr.length
  779. var valLength = val.length
  780. if (encoding !== undefined) {
  781. encoding = String(encoding).toLowerCase()
  782. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  783. encoding === 'utf16le' || encoding === 'utf-16le') {
  784. if (arr.length < 2 || val.length < 2) {
  785. return -1
  786. }
  787. indexSize = 2
  788. arrLength /= 2
  789. valLength /= 2
  790. byteOffset /= 2
  791. }
  792. }
  793. function read(buf, i) {
  794. if (indexSize === 1) {
  795. return buf[i]
  796. } else {
  797. return buf.readUInt16BE(i * indexSize)
  798. }
  799. }
  800. var i
  801. if (dir) {
  802. var foundIndex = -1
  803. for (i = byteOffset; i < arrLength; i++) {
  804. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  805. if (foundIndex === -1) foundIndex = i
  806. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  807. } else {
  808. if (foundIndex !== -1) i -= i - foundIndex
  809. foundIndex = -1
  810. }
  811. }
  812. } else {
  813. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  814. for (i = byteOffset; i >= 0; i--) {
  815. var found = true
  816. for (var j = 0; j < valLength; j++) {
  817. if (read(arr, i + j) !== read(val, j)) {
  818. found = false
  819. break
  820. }
  821. }
  822. if (found) return i
  823. }
  824. }
  825. return -1
  826. }
  827. Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  828. return this.indexOf(val, byteOffset, encoding) !== -1
  829. }
  830. Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  831. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  832. }
  833. Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  834. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  835. }
  836. function hexWrite(buf, string, offset, length) {
  837. offset = Number(offset) || 0
  838. var remaining = buf.length - offset
  839. if (!length) {
  840. length = remaining
  841. } else {
  842. length = Number(length)
  843. if (length > remaining) {
  844. length = remaining
  845. }
  846. }
  847. var strLen = string.length
  848. if (length > strLen / 2) {
  849. length = strLen / 2
  850. }
  851. for (var i = 0; i < length; ++i) {
  852. var parsed = parseInt(string.substr(i * 2, 2), 16)
  853. if (numberIsNaN(parsed)) return i
  854. buf[offset + i] = parsed
  855. }
  856. return i
  857. }
  858. function utf8Write(buf, string, offset, length) {
  859. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  860. }
  861. function asciiWrite(buf, string, offset, length) {
  862. return blitBuffer(asciiToBytes(string), buf, offset, length)
  863. }
  864. function latin1Write(buf, string, offset, length) {
  865. return asciiWrite(buf, string, offset, length)
  866. }
  867. function base64Write(buf, string, offset, length) {
  868. return blitBuffer(base64ToBytes(string), buf, offset, length)
  869. }
  870. function ucs2Write(buf, string, offset, length) {
  871. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  872. }
  873. Buffer.prototype.write = function write(string, offset, length, encoding) {
  874. // Buffer#write(string)
  875. if (offset === undefined) {
  876. encoding = 'utf8'
  877. length = this.length
  878. offset = 0
  879. // Buffer#write(string, encoding)
  880. } else if (length === undefined && typeof offset === 'string') {
  881. encoding = offset
  882. length = this.length
  883. offset = 0
  884. // Buffer#write(string, offset[, length][, encoding])
  885. } else if (isFinite(offset)) {
  886. offset = offset >>> 0
  887. if (isFinite(length)) {
  888. length = length >>> 0
  889. if (encoding === undefined) encoding = 'utf8'
  890. } else {
  891. encoding = length
  892. length = undefined
  893. }
  894. } else {
  895. throw new Error(
  896. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  897. )
  898. }
  899. var remaining = this.length - offset
  900. if (length === undefined || length > remaining) length = remaining
  901. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  902. throw new RangeError('Attempt to write outside buffer bounds')
  903. }
  904. if (!encoding) encoding = 'utf8'
  905. var loweredCase = false
  906. for (; ;) {
  907. switch (encoding) {
  908. case 'hex':
  909. return hexWrite(this, string, offset, length)
  910. case 'utf8':
  911. case 'utf-8':
  912. return utf8Write(this, string, offset, length)
  913. case 'ascii':
  914. return asciiWrite(this, string, offset, length)
  915. case 'latin1':
  916. case 'binary':
  917. return latin1Write(this, string, offset, length)
  918. case 'base64':
  919. // Warning: maxLength not taken into account in base64Write
  920. return base64Write(this, string, offset, length)
  921. case 'ucs2':
  922. case 'ucs-2':
  923. case 'utf16le':
  924. case 'utf-16le':
  925. return ucs2Write(this, string, offset, length)
  926. default:
  927. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  928. encoding = ('' + encoding).toLowerCase()
  929. loweredCase = true
  930. }
  931. }
  932. }
  933. Buffer.prototype.toJSON = function toJSON() {
  934. return {
  935. type: 'Buffer',
  936. data: Array.prototype.slice.call(this._arr || this, 0)
  937. }
  938. }
  939. function base64Slice(buf, start, end) {
  940. if (start === 0 && end === buf.length) {
  941. return base64.fromByteArray(buf)
  942. } else {
  943. return base64.fromByteArray(buf.slice(start, end))
  944. }
  945. }
  946. function utf8Slice(buf, start, end) {
  947. end = Math.min(buf.length, end)
  948. var res = []
  949. var i = start
  950. while (i < end) {
  951. var firstByte = buf[i]
  952. var codePoint = null
  953. var bytesPerSequence = (firstByte > 0xEF) ? 4
  954. : (firstByte > 0xDF) ? 3
  955. : (firstByte > 0xBF) ? 2
  956. : 1
  957. if (i + bytesPerSequence <= end) {
  958. var secondByte, thirdByte, fourthByte, tempCodePoint
  959. switch (bytesPerSequence) {
  960. case 1:
  961. if (firstByte < 0x80) {
  962. codePoint = firstByte
  963. }
  964. break
  965. case 2:
  966. secondByte = buf[i + 1]
  967. if ((secondByte & 0xC0) === 0x80) {
  968. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  969. if (tempCodePoint > 0x7F) {
  970. codePoint = tempCodePoint
  971. }
  972. }
  973. break
  974. case 3:
  975. secondByte = buf[i + 1]
  976. thirdByte = buf[i + 2]
  977. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  978. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  979. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  980. codePoint = tempCodePoint
  981. }
  982. }
  983. break
  984. case 4:
  985. secondByte = buf[i + 1]
  986. thirdByte = buf[i + 2]
  987. fourthByte = buf[i + 3]
  988. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  989. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  990. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  991. codePoint = tempCodePoint
  992. }
  993. }
  994. }
  995. }
  996. if (codePoint === null) {
  997. // we did not generate a valid codePoint so insert a
  998. // replacement char (U+FFFD) and advance only 1 byte
  999. codePoint = 0xFFFD
  1000. bytesPerSequence = 1
  1001. } else if (codePoint > 0xFFFF) {
  1002. // encode to utf16 (surrogate pair dance)
  1003. codePoint -= 0x10000
  1004. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1005. codePoint = 0xDC00 | codePoint & 0x3FF
  1006. }
  1007. res.push(codePoint)
  1008. i += bytesPerSequence
  1009. }
  1010. return decodeCodePointsArray(res)
  1011. }
  1012. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1013. // the lowest limit is Chrome, with 0x10000 args.
  1014. // We go 1 magnitude less, for safety
  1015. var MAX_ARGUMENTS_LENGTH = 0x1000
  1016. function decodeCodePointsArray(codePoints) {
  1017. var len = codePoints.length
  1018. if (len <= MAX_ARGUMENTS_LENGTH) {
  1019. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1020. }
  1021. // Decode in chunks to avoid "call stack size exceeded".
  1022. var res = ''
  1023. var i = 0
  1024. while (i < len) {
  1025. res += String.fromCharCode.apply(
  1026. String,
  1027. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1028. )
  1029. }
  1030. return res
  1031. }
  1032. function asciiSlice(buf, start, end) {
  1033. var ret = ''
  1034. end = Math.min(buf.length, end)
  1035. for (var i = start; i < end; ++i) {
  1036. ret += String.fromCharCode(buf[i] & 0x7F)
  1037. }
  1038. return ret
  1039. }
  1040. function latin1Slice(buf, start, end) {
  1041. var ret = ''
  1042. end = Math.min(buf.length, end)
  1043. for (var i = start; i < end; ++i) {
  1044. ret += String.fromCharCode(buf[i])
  1045. }
  1046. return ret
  1047. }
  1048. function hexSlice(buf, start, end) {
  1049. var len = buf.length
  1050. if (!start || start < 0) start = 0
  1051. if (!end || end < 0 || end > len) end = len
  1052. var out = ''
  1053. for (var i = start; i < end; ++i) {
  1054. out += toHex(buf[i])
  1055. }
  1056. return out
  1057. }
  1058. function utf16leSlice(buf, start, end) {
  1059. var bytes = buf.slice(start, end)
  1060. var res = ''
  1061. for (var i = 0; i < bytes.length; i += 2) {
  1062. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  1063. }
  1064. return res
  1065. }
  1066. Buffer.prototype.slice = function slice(start, end) {
  1067. var len = this.length
  1068. start = ~~start
  1069. end = end === undefined ? len : ~~end
  1070. if (start < 0) {
  1071. start += len
  1072. if (start < 0) start = 0
  1073. } else if (start > len) {
  1074. start = len
  1075. }
  1076. if (end < 0) {
  1077. end += len
  1078. if (end < 0) end = 0
  1079. } else if (end > len) {
  1080. end = len
  1081. }
  1082. if (end < start) end = start
  1083. var newBuf = this.subarray(start, end)
  1084. // Return an augmented `Uint8Array` instance
  1085. newBuf.__proto__ = Buffer.prototype
  1086. return newBuf
  1087. }
  1088. /*
  1089. * Need to make sure that buffer isn't trying to write out of bounds.
  1090. */
  1091. function checkOffset(offset, ext, length) {
  1092. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1093. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1094. }
  1095. Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
  1096. offset = offset >>> 0
  1097. byteLength = byteLength >>> 0
  1098. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1099. var val = this[offset]
  1100. var mul = 1
  1101. var i = 0
  1102. while (++i < byteLength && (mul *= 0x100)) {
  1103. val += this[offset + i] * mul
  1104. }
  1105. return val
  1106. }
  1107. Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
  1108. offset = offset >>> 0
  1109. byteLength = byteLength >>> 0
  1110. if (!noAssert) {
  1111. checkOffset(offset, byteLength, this.length)
  1112. }
  1113. var val = this[offset + --byteLength]
  1114. var mul = 1
  1115. while (byteLength > 0 && (mul *= 0x100)) {
  1116. val += this[offset + --byteLength] * mul
  1117. }
  1118. return val
  1119. }
  1120. Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  1121. offset = offset >>> 0
  1122. if (!noAssert) checkOffset(offset, 1, this.length)
  1123. return this[offset]
  1124. }
  1125. Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  1126. offset = offset >>> 0
  1127. if (!noAssert) checkOffset(offset, 2, this.length)
  1128. return this[offset] | (this[offset + 1] << 8)
  1129. }
  1130. Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  1131. offset = offset >>> 0
  1132. if (!noAssert) checkOffset(offset, 2, this.length)
  1133. return (this[offset] << 8) | this[offset + 1]
  1134. }
  1135. Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  1136. offset = offset >>> 0
  1137. if (!noAssert) checkOffset(offset, 4, this.length)
  1138. return ((this[offset]) |
  1139. (this[offset + 1] << 8) |
  1140. (this[offset + 2] << 16)) +
  1141. (this[offset + 3] * 0x1000000)
  1142. }
  1143. Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  1144. offset = offset >>> 0
  1145. if (!noAssert) checkOffset(offset, 4, this.length)
  1146. return (this[offset] * 0x1000000) +
  1147. ((this[offset + 1] << 16) |
  1148. (this[offset + 2] << 8) |
  1149. this[offset + 3])
  1150. }
  1151. Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
  1152. offset = offset >>> 0
  1153. byteLength = byteLength >>> 0
  1154. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1155. var val = this[offset]
  1156. var mul = 1
  1157. var i = 0
  1158. while (++i < byteLength && (mul *= 0x100)) {
  1159. val += this[offset + i] * mul
  1160. }
  1161. mul *= 0x80
  1162. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1163. return val
  1164. }
  1165. Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
  1166. offset = offset >>> 0
  1167. byteLength = byteLength >>> 0
  1168. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1169. var i = byteLength
  1170. var mul = 1
  1171. var val = this[offset + --i]
  1172. while (i > 0 && (mul *= 0x100)) {
  1173. val += this[offset + --i] * mul
  1174. }
  1175. mul *= 0x80
  1176. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1177. return val
  1178. }
  1179. Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  1180. offset = offset >>> 0
  1181. if (!noAssert) checkOffset(offset, 1, this.length)
  1182. if (!(this[offset] & 0x80)) return (this[offset])
  1183. return ((0xff - this[offset] + 1) * -1)
  1184. }
  1185. Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  1186. offset = offset >>> 0
  1187. if (!noAssert) checkOffset(offset, 2, this.length)
  1188. var val = this[offset] | (this[offset + 1] << 8)
  1189. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1190. }
  1191. Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  1192. offset = offset >>> 0
  1193. if (!noAssert) checkOffset(offset, 2, this.length)
  1194. var val = this[offset + 1] | (this[offset] << 8)
  1195. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1196. }
  1197. Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  1198. offset = offset >>> 0
  1199. if (!noAssert) checkOffset(offset, 4, this.length)
  1200. return (this[offset]) |
  1201. (this[offset + 1] << 8) |
  1202. (this[offset + 2] << 16) |
  1203. (this[offset + 3] << 24)
  1204. }
  1205. Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  1206. offset = offset >>> 0
  1207. if (!noAssert) checkOffset(offset, 4, this.length)
  1208. return (this[offset] << 24) |
  1209. (this[offset + 1] << 16) |
  1210. (this[offset + 2] << 8) |
  1211. (this[offset + 3])
  1212. }
  1213. Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  1214. offset = offset >>> 0
  1215. if (!noAssert) checkOffset(offset, 4, this.length)
  1216. return ieee754.read(this, offset, true, 23, 4)
  1217. }
  1218. Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  1219. offset = offset >>> 0
  1220. if (!noAssert) checkOffset(offset, 4, this.length)
  1221. return ieee754.read(this, offset, false, 23, 4)
  1222. }
  1223. Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  1224. offset = offset >>> 0
  1225. if (!noAssert) checkOffset(offset, 8, this.length)
  1226. return ieee754.read(this, offset, true, 52, 8)
  1227. }
  1228. Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  1229. offset = offset >>> 0
  1230. if (!noAssert) checkOffset(offset, 8, this.length)
  1231. return ieee754.read(this, offset, false, 52, 8)
  1232. }
  1233. function checkInt(buf, value, offset, ext, max, min) {
  1234. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1235. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1236. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1237. }
  1238. Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
  1239. value = +value
  1240. offset = offset >>> 0
  1241. byteLength = byteLength >>> 0
  1242. if (!noAssert) {
  1243. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1244. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1245. }
  1246. var mul = 1
  1247. var i = 0
  1248. this[offset] = value & 0xFF
  1249. while (++i < byteLength && (mul *= 0x100)) {
  1250. this[offset + i] = (value / mul) & 0xFF
  1251. }
  1252. return offset + byteLength
  1253. }
  1254. Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
  1255. value = +value
  1256. offset = offset >>> 0
  1257. byteLength = byteLength >>> 0
  1258. if (!noAssert) {
  1259. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1260. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1261. }
  1262. var i = byteLength - 1
  1263. var mul = 1
  1264. this[offset + i] = value & 0xFF
  1265. while (--i >= 0 && (mul *= 0x100)) {
  1266. this[offset + i] = (value / mul) & 0xFF
  1267. }
  1268. return offset + byteLength
  1269. }
  1270. Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  1271. value = +value
  1272. offset = offset >>> 0
  1273. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1274. this[offset] = (value & 0xff)
  1275. return offset + 1
  1276. }
  1277. Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  1278. value = +value
  1279. offset = offset >>> 0
  1280. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1281. this[offset] = (value & 0xff)
  1282. this[offset + 1] = (value >>> 8)
  1283. return offset + 2
  1284. }
  1285. Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  1286. value = +value
  1287. offset = offset >>> 0
  1288. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1289. this[offset] = (value >>> 8)
  1290. this[offset + 1] = (value & 0xff)
  1291. return offset + 2
  1292. }
  1293. Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  1294. value = +value
  1295. offset = offset >>> 0
  1296. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1297. this[offset + 3] = (value >>> 24)
  1298. this[offset + 2] = (value >>> 16)
  1299. this[offset + 1] = (value >>> 8)
  1300. this[offset] = (value & 0xff)
  1301. return offset + 4
  1302. }
  1303. Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  1304. value = +value
  1305. offset = offset >>> 0
  1306. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1307. this[offset] = (value >>> 24)
  1308. this[offset + 1] = (value >>> 16)
  1309. this[offset + 2] = (value >>> 8)
  1310. this[offset + 3] = (value & 0xff)
  1311. return offset + 4
  1312. }
  1313. Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
  1314. value = +value
  1315. offset = offset >>> 0
  1316. if (!noAssert) {
  1317. var limit = Math.pow(2, (8 * byteLength) - 1)
  1318. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1319. }
  1320. var i = 0
  1321. var mul = 1
  1322. var sub = 0
  1323. this[offset] = value & 0xFF
  1324. while (++i < byteLength && (mul *= 0x100)) {
  1325. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1326. sub = 1
  1327. }
  1328. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1329. }
  1330. return offset + byteLength
  1331. }
  1332. Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
  1333. value = +value
  1334. offset = offset >>> 0
  1335. if (!noAssert) {
  1336. var limit = Math.pow(2, (8 * byteLength) - 1)
  1337. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1338. }
  1339. var i = byteLength - 1
  1340. var mul = 1
  1341. var sub = 0
  1342. this[offset + i] = value & 0xFF
  1343. while (--i >= 0 && (mul *= 0x100)) {
  1344. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1345. sub = 1
  1346. }
  1347. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1348. }
  1349. return offset + byteLength
  1350. }
  1351. Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  1352. value = +value
  1353. offset = offset >>> 0
  1354. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1355. if (value < 0) value = 0xff + value + 1
  1356. this[offset] = (value & 0xff)
  1357. return offset + 1
  1358. }
  1359. Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  1360. value = +value
  1361. offset = offset >>> 0
  1362. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1363. this[offset] = (value & 0xff)
  1364. this[offset + 1] = (value >>> 8)
  1365. return offset + 2
  1366. }
  1367. Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  1368. value = +value
  1369. offset = offset >>> 0
  1370. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1371. this[offset] = (value >>> 8)
  1372. this[offset + 1] = (value & 0xff)
  1373. return offset + 2
  1374. }
  1375. Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  1376. value = +value
  1377. offset = offset >>> 0
  1378. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1379. this[offset] = (value & 0xff)
  1380. this[offset + 1] = (value >>> 8)
  1381. this[offset + 2] = (value >>> 16)
  1382. this[offset + 3] = (value >>> 24)
  1383. return offset + 4
  1384. }
  1385. Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  1386. value = +value
  1387. offset = offset >>> 0
  1388. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1389. if (value < 0) value = 0xffffffff + value + 1
  1390. this[offset] = (value >>> 24)
  1391. this[offset + 1] = (value >>> 16)
  1392. this[offset + 2] = (value >>> 8)
  1393. this[offset + 3] = (value & 0xff)
  1394. return offset + 4
  1395. }
  1396. function checkIEEE754(buf, value, offset, ext, max, min) {
  1397. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1398. if (offset < 0) throw new RangeError('Index out of range')
  1399. }
  1400. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  1401. value = +value
  1402. offset = offset >>> 0
  1403. if (!noAssert) {
  1404. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1405. }
  1406. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1407. return offset + 4
  1408. }
  1409. Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  1410. return writeFloat(this, value, offset, true, noAssert)
  1411. }
  1412. Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  1413. return writeFloat(this, value, offset, false, noAssert)
  1414. }
  1415. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  1416. value = +value
  1417. offset = offset >>> 0
  1418. if (!noAssert) {
  1419. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1420. }
  1421. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1422. return offset + 8
  1423. }
  1424. Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  1425. return writeDouble(this, value, offset, true, noAssert)
  1426. }
  1427. Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  1428. return writeDouble(this, value, offset, false, noAssert)
  1429. }
  1430. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1431. Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  1432. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  1433. if (!start) start = 0
  1434. if (!end && end !== 0) end = this.length
  1435. if (targetStart >= target.length) targetStart = target.length
  1436. if (!targetStart) targetStart = 0
  1437. if (end > 0 && end < start) end = start
  1438. // Copy 0 bytes; we're done
  1439. if (end === start) return 0
  1440. if (target.length === 0 || this.length === 0) return 0
  1441. // Fatal error conditions
  1442. if (targetStart < 0) {
  1443. throw new RangeError('targetStart out of bounds')
  1444. }
  1445. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  1446. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1447. // Are we oob?
  1448. if (end > this.length) end = this.length
  1449. if (target.length - targetStart < end - start) {
  1450. end = target.length - targetStart + start
  1451. }
  1452. var len = end - start
  1453. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  1454. // Use built-in when available, missing from IE11
  1455. this.copyWithin(targetStart, start, end)
  1456. } else if (this === target && start < targetStart && targetStart < end) {
  1457. // descending copy from end
  1458. for (var i = len - 1; i >= 0; --i) {
  1459. target[i + targetStart] = this[i + start]
  1460. }
  1461. } else {
  1462. Uint8Array.prototype.set.call(
  1463. target,
  1464. this.subarray(start, end),
  1465. targetStart
  1466. )
  1467. }
  1468. return len
  1469. }
  1470. // Usage:
  1471. // buffer.fill(number[, offset[, end]])
  1472. // buffer.fill(buffer[, offset[, end]])
  1473. // buffer.fill(string[, offset[, end]][, encoding])
  1474. Buffer.prototype.fill = function fill(val, start, end, encoding) {
  1475. // Handle string cases:
  1476. if (typeof val === 'string') {
  1477. if (typeof start === 'string') {
  1478. encoding = start
  1479. start = 0
  1480. end = this.length
  1481. } else if (typeof end === 'string') {
  1482. encoding = end
  1483. end = this.length
  1484. }
  1485. if (encoding !== undefined && typeof encoding !== 'string') {
  1486. throw new TypeError('encoding must be a string')
  1487. }
  1488. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1489. throw new TypeError('Unknown encoding: ' + encoding)
  1490. }
  1491. if (val.length === 1) {
  1492. var code = val.charCodeAt(0)
  1493. if ((encoding === 'utf8' && code < 128) ||
  1494. encoding === 'latin1') {
  1495. // Fast path: If `val` fits into a single byte, use that numeric value.
  1496. val = code
  1497. }
  1498. }
  1499. } else if (typeof val === 'number') {
  1500. val = val & 255
  1501. }
  1502. // Invalid ranges are not set to a default, so can range check early.
  1503. if (start < 0 || this.length < start || this.length < end) {
  1504. throw new RangeError('Out of range index')
  1505. }
  1506. if (end <= start) {
  1507. return this
  1508. }
  1509. start = start >>> 0
  1510. end = end === undefined ? this.length : end >>> 0
  1511. if (!val) val = 0
  1512. var i
  1513. if (typeof val === 'number') {
  1514. for (i = start; i < end; ++i) {
  1515. this[i] = val
  1516. }
  1517. } else {
  1518. var bytes = Buffer.isBuffer(val)
  1519. ? val
  1520. : Buffer.from(val, encoding)
  1521. var len = bytes.length
  1522. if (len === 0) {
  1523. throw new TypeError('The value "' + val +
  1524. '" is invalid for argument "value"')
  1525. }
  1526. for (i = 0; i < end - start; ++i) {
  1527. this[i + start] = bytes[i % len]
  1528. }
  1529. }
  1530. return this
  1531. }
  1532. // HELPER FUNCTIONS
  1533. // ================
  1534. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  1535. function base64clean(str) {
  1536. // Node takes equal signs as end of the Base64 encoding
  1537. str = str.split('=')[0]
  1538. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1539. str = str.trim().replace(INVALID_BASE64_RE, '')
  1540. // Node converts strings with length < 2 to ''
  1541. if (str.length < 2) return ''
  1542. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1543. while (str.length % 4 !== 0) {
  1544. str = str + '='
  1545. }
  1546. return str
  1547. }
  1548. function toHex(n) {
  1549. if (n < 16) return '0' + n.toString(16)
  1550. return n.toString(16)
  1551. }
  1552. function utf8ToBytes(string, units) {
  1553. units = units || Infinity
  1554. var codePoint
  1555. var length = string.length
  1556. var leadSurrogate = null
  1557. var bytes = []
  1558. for (var i = 0; i < length; ++i) {
  1559. codePoint = string.charCodeAt(i)
  1560. // is surrogate component
  1561. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1562. // last char was a lead
  1563. if (!leadSurrogate) {
  1564. // no lead yet
  1565. if (codePoint > 0xDBFF) {
  1566. // unexpected trail
  1567. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1568. continue
  1569. } else if (i + 1 === length) {
  1570. // unpaired lead
  1571. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1572. continue
  1573. }
  1574. // valid lead
  1575. leadSurrogate = codePoint
  1576. continue
  1577. }
  1578. // 2 leads in a row
  1579. if (codePoint < 0xDC00) {
  1580. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1581. leadSurrogate = codePoint
  1582. continue
  1583. }
  1584. // valid surrogate pair
  1585. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1586. } else if (leadSurrogate) {
  1587. // valid bmp char, but last char was a lead
  1588. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1589. }
  1590. leadSurrogate = null
  1591. // encode utf8
  1592. if (codePoint < 0x80) {
  1593. if ((units -= 1) < 0) break
  1594. bytes.push(codePoint)
  1595. } else if (codePoint < 0x800) {
  1596. if ((units -= 2) < 0) break
  1597. bytes.push(
  1598. codePoint >> 0x6 | 0xC0,
  1599. codePoint & 0x3F | 0x80
  1600. )
  1601. } else if (codePoint < 0x10000) {
  1602. if ((units -= 3) < 0) break
  1603. bytes.push(
  1604. codePoint >> 0xC | 0xE0,
  1605. codePoint >> 0x6 & 0x3F | 0x80,
  1606. codePoint & 0x3F | 0x80
  1607. )
  1608. } else if (codePoint < 0x110000) {
  1609. if ((units -= 4) < 0) break
  1610. bytes.push(
  1611. codePoint >> 0x12 | 0xF0,
  1612. codePoint >> 0xC & 0x3F | 0x80,
  1613. codePoint >> 0x6 & 0x3F | 0x80,
  1614. codePoint & 0x3F | 0x80
  1615. )
  1616. } else {
  1617. throw new Error('Invalid code point')
  1618. }
  1619. }
  1620. return bytes
  1621. }
  1622. function asciiToBytes(str) {
  1623. var byteArray = []
  1624. for (var i = 0; i < str.length; ++i) {
  1625. // Node's code seems to be doing this and not & 0x7F..
  1626. byteArray.push(str.charCodeAt(i) & 0xFF)
  1627. }
  1628. return byteArray
  1629. }
  1630. function utf16leToBytes(str, units) {
  1631. var c, hi, lo
  1632. var byteArray = []
  1633. for (var i = 0; i < str.length; ++i) {
  1634. if ((units -= 2) < 0) break
  1635. c = str.charCodeAt(i)
  1636. hi = c >> 8
  1637. lo = c % 256
  1638. byteArray.push(lo)
  1639. byteArray.push(hi)
  1640. }
  1641. return byteArray
  1642. }
  1643. function base64ToBytes(str) {
  1644. return base64.toByteArray(base64clean(str))
  1645. }
  1646. function blitBuffer(src, dst, offset, length) {
  1647. for (var i = 0; i < length; ++i) {
  1648. if ((i + offset >= dst.length) || (i >= src.length)) break
  1649. dst[i + offset] = src[i]
  1650. }
  1651. return i
  1652. }
  1653. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  1654. // the `instanceof` check but they should be treated as of that type.
  1655. // See: https://github.com/feross/buffer/issues/166
  1656. function isInstance(obj, type) {
  1657. return obj instanceof type ||
  1658. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  1659. obj.constructor.name === type.name)
  1660. }
  1661. function numberIsNaN(obj) {
  1662. // For IE11 support
  1663. return obj !== obj // eslint-disable-line no-self-compare
  1664. }
  1665. }).call(this, require("buffer").Buffer)
  1666. }, { "base64-js": 1, "buffer": 3, "ieee754": 6 }], 4: [function (require, module, exports) {
  1667. (function (Buffer) {
  1668. // Copyright Joyent, Inc. and other Node contributors.
  1669. //
  1670. // Permission is hereby granted, free of charge, to any person obtaining a
  1671. // copy of this software and associated documentation files (the
  1672. // "Software"), to deal in the Software without restriction, including
  1673. // without limitation the rights to use, copy, modify, merge, publish,
  1674. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1675. // persons to whom the Software is furnished to do so, subject to the
  1676. // following conditions:
  1677. //
  1678. // The above copyright notice and this permission notice shall be included
  1679. // in all copies or substantial portions of the Software.
  1680. //
  1681. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1682. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1683. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1684. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1685. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1686. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1687. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1688. // NOTE: These type checking functions intentionally don't use `instanceof`
  1689. // because it is fragile and can be easily faked with `Object.create()`.
  1690. function isArray(arg) {
  1691. if (Array.isArray) {
  1692. return Array.isArray(arg);
  1693. }
  1694. return objectToString(arg) === '[object Array]';
  1695. }
  1696. exports.isArray = isArray;
  1697. function isBoolean(arg) {
  1698. return typeof arg === 'boolean';
  1699. }
  1700. exports.isBoolean = isBoolean;
  1701. function isNull(arg) {
  1702. return arg === null;
  1703. }
  1704. exports.isNull = isNull;
  1705. function isNullOrUndefined(arg) {
  1706. return arg == null;
  1707. }
  1708. exports.isNullOrUndefined = isNullOrUndefined;
  1709. function isNumber(arg) {
  1710. return typeof arg === 'number';
  1711. }
  1712. exports.isNumber = isNumber;
  1713. function isString(arg) {
  1714. return typeof arg === 'string';
  1715. }
  1716. exports.isString = isString;
  1717. function isSymbol(arg) {
  1718. return typeof arg === 'symbol';
  1719. }
  1720. exports.isSymbol = isSymbol;
  1721. function isUndefined(arg) {
  1722. return arg === void 0;
  1723. }
  1724. exports.isUndefined = isUndefined;
  1725. function isRegExp(re) {
  1726. return objectToString(re) === '[object RegExp]';
  1727. }
  1728. exports.isRegExp = isRegExp;
  1729. function isObject(arg) {
  1730. return typeof arg === 'object' && arg !== null;
  1731. }
  1732. exports.isObject = isObject;
  1733. function isDate(d) {
  1734. return objectToString(d) === '[object Date]';
  1735. }
  1736. exports.isDate = isDate;
  1737. function isError(e) {
  1738. return (objectToString(e) === '[object Error]' || e instanceof Error);
  1739. }
  1740. exports.isError = isError;
  1741. function isFunction(arg) {
  1742. return typeof arg === 'function';
  1743. }
  1744. exports.isFunction = isFunction;
  1745. function isPrimitive(arg) {
  1746. return arg === null ||
  1747. typeof arg === 'boolean' ||
  1748. typeof arg === 'number' ||
  1749. typeof arg === 'string' ||
  1750. typeof arg === 'symbol' || // ES6 symbol
  1751. typeof arg === 'undefined';
  1752. }
  1753. exports.isPrimitive = isPrimitive;
  1754. exports.isBuffer = Buffer.isBuffer;
  1755. function objectToString(o) {
  1756. return Object.prototype.toString.call(o);
  1757. }
  1758. }).call(this, { "isBuffer": require("../../is-buffer/index.js") })
  1759. }, { "../../is-buffer/index.js": 9 }], 5: [function (require, module, exports) {
  1760. // Copyright Joyent, Inc. and other Node contributors.
  1761. //
  1762. // Permission is hereby granted, free of charge, to any person obtaining a
  1763. // copy of this software and associated documentation files (the
  1764. // "Software"), to deal in the Software without restriction, including
  1765. // without limitation the rights to use, copy, modify, merge, publish,
  1766. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1767. // persons to whom the Software is furnished to do so, subject to the
  1768. // following conditions:
  1769. //
  1770. // The above copyright notice and this permission notice shall be included
  1771. // in all copies or substantial portions of the Software.
  1772. //
  1773. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1774. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1775. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1776. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1777. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1778. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1779. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1780. var objectCreate = Object.create || objectCreatePolyfill
  1781. var objectKeys = Object.keys || objectKeysPolyfill
  1782. var bind = Function.prototype.bind || functionBindPolyfill
  1783. function EventEmitter() {
  1784. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  1785. this._events = objectCreate(null);
  1786. this._eventsCount = 0;
  1787. }
  1788. this._maxListeners = this._maxListeners || undefined;
  1789. }
  1790. module.exports = EventEmitter;
  1791. // Backwards-compat with node 0.10.x
  1792. EventEmitter.EventEmitter = EventEmitter;
  1793. EventEmitter.prototype._events = undefined;
  1794. EventEmitter.prototype._maxListeners = undefined;
  1795. // By default EventEmitters will print a warning if more than 10 listeners are
  1796. // added to it. This is a useful default which helps finding memory leaks.
  1797. var defaultMaxListeners = 10;
  1798. var hasDefineProperty;
  1799. try {
  1800. var o = {};
  1801. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  1802. hasDefineProperty = o.x === 0;
  1803. } catch (err) { hasDefineProperty = false }
  1804. if (hasDefineProperty) {
  1805. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  1806. enumerable: true,
  1807. get: function () {
  1808. return defaultMaxListeners;
  1809. },
  1810. set: function (arg) {
  1811. // check whether the input is a positive number (whose value is zero or
  1812. // greater and not a NaN).
  1813. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  1814. throw new TypeError('"defaultMaxListeners" must be a positive number');
  1815. defaultMaxListeners = arg;
  1816. }
  1817. });
  1818. } else {
  1819. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  1820. }
  1821. // Obviously not all Emitters should be limited to 10. This function allows
  1822. // that to be increased. Set to zero for unlimited.
  1823. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  1824. if (typeof n !== 'number' || n < 0 || isNaN(n))
  1825. throw new TypeError('"n" argument must be a positive number');
  1826. this._maxListeners = n;
  1827. return this;
  1828. };
  1829. function $getMaxListeners(that) {
  1830. if (that._maxListeners === undefined)
  1831. return EventEmitter.defaultMaxListeners;
  1832. return that._maxListeners;
  1833. }
  1834. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  1835. return $getMaxListeners(this);
  1836. };
  1837. // These standalone emit* functions are used to optimize calling of event
  1838. // handlers for fast cases because emit() itself often has a variable number of
  1839. // arguments and can be deoptimized because of that. These functions always have
  1840. // the same number of arguments and thus do not get deoptimized, so the code
  1841. // inside them can execute faster.
  1842. function emitNone(handler, isFn, self) {
  1843. if (isFn)
  1844. handler.call(self);
  1845. else {
  1846. var len = handler.length;
  1847. var listeners = arrayClone(handler, len);
  1848. for (var i = 0; i < len; ++i)
  1849. listeners[i].call(self);
  1850. }
  1851. }
  1852. function emitOne(handler, isFn, self, arg1) {
  1853. if (isFn)
  1854. handler.call(self, arg1);
  1855. else {
  1856. var len = handler.length;
  1857. var listeners = arrayClone(handler, len);
  1858. for (var i = 0; i < len; ++i)
  1859. listeners[i].call(self, arg1);
  1860. }
  1861. }
  1862. function emitTwo(handler, isFn, self, arg1, arg2) {
  1863. if (isFn)
  1864. handler.call(self, arg1, arg2);
  1865. else {
  1866. var len = handler.length;
  1867. var listeners = arrayClone(handler, len);
  1868. for (var i = 0; i < len; ++i)
  1869. listeners[i].call(self, arg1, arg2);
  1870. }
  1871. }
  1872. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  1873. if (isFn)
  1874. handler.call(self, arg1, arg2, arg3);
  1875. else {
  1876. var len = handler.length;
  1877. var listeners = arrayClone(handler, len);
  1878. for (var i = 0; i < len; ++i)
  1879. listeners[i].call(self, arg1, arg2, arg3);
  1880. }
  1881. }
  1882. function emitMany(handler, isFn, self, args) {
  1883. if (isFn)
  1884. handler.apply(self, args);
  1885. else {
  1886. var len = handler.length;
  1887. var listeners = arrayClone(handler, len);
  1888. for (var i = 0; i < len; ++i)
  1889. listeners[i].apply(self, args);
  1890. }
  1891. }
  1892. EventEmitter.prototype.emit = function emit(type) {
  1893. var er, handler, len, args, i, events;
  1894. var doError = (type === 'error');
  1895. events = this._events;
  1896. if (events)
  1897. doError = (doError && events.error == null);
  1898. else if (!doError)
  1899. return false;
  1900. // If there is no 'error' event listener then throw.
  1901. if (doError) {
  1902. if (arguments.length > 1)
  1903. er = arguments[1];
  1904. if (er instanceof Error) {
  1905. throw er; // Unhandled 'error' event
  1906. } else {
  1907. // At least give some kind of context to the user
  1908. var err = new Error('Unhandled "error" event. (' + er + ')');
  1909. err.context = er;
  1910. throw err;
  1911. }
  1912. return false;
  1913. }
  1914. handler = events[type];
  1915. if (!handler)
  1916. return false;
  1917. var isFn = typeof handler === 'function';
  1918. len = arguments.length;
  1919. switch (len) {
  1920. // fast cases
  1921. case 1:
  1922. emitNone(handler, isFn, this);
  1923. break;
  1924. case 2:
  1925. emitOne(handler, isFn, this, arguments[1]);
  1926. break;
  1927. case 3:
  1928. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  1929. break;
  1930. case 4:
  1931. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  1932. break;
  1933. // slower
  1934. default:
  1935. args = new Array(len - 1);
  1936. for (i = 1; i < len; i++)
  1937. args[i - 1] = arguments[i];
  1938. emitMany(handler, isFn, this, args);
  1939. }
  1940. return true;
  1941. };
  1942. function _addListener(target, type, listener, prepend) {
  1943. var m;
  1944. var events;
  1945. var existing;
  1946. if (typeof listener !== 'function')
  1947. throw new TypeError('"listener" argument must be a function');
  1948. events = target._events;
  1949. if (!events) {
  1950. events = target._events = objectCreate(null);
  1951. target._eventsCount = 0;
  1952. } else {
  1953. // To avoid recursion in the case that type === "newListener"! Before
  1954. // adding it to the listeners, first emit "newListener".
  1955. if (events.newListener) {
  1956. target.emit('newListener', type,
  1957. listener.listener ? listener.listener : listener);
  1958. // Re-assign `events` because a newListener handler could have caused the
  1959. // this._events to be assigned to a new object
  1960. events = target._events;
  1961. }
  1962. existing = events[type];
  1963. }
  1964. if (!existing) {
  1965. // Optimize the case of one listener. Don't need the extra array object.
  1966. existing = events[type] = listener;
  1967. ++target._eventsCount;
  1968. } else {
  1969. if (typeof existing === 'function') {
  1970. // Adding the second element, need to change to array.
  1971. existing = events[type] =
  1972. prepend ? [listener, existing] : [existing, listener];
  1973. } else {
  1974. // If we've already got an array, just append.
  1975. if (prepend) {
  1976. existing.unshift(listener);
  1977. } else {
  1978. existing.push(listener);
  1979. }
  1980. }
  1981. // Check for listener leak
  1982. if (!existing.warned) {
  1983. m = $getMaxListeners(target);
  1984. if (m && m > 0 && existing.length > m) {
  1985. existing.warned = true;
  1986. var w = new Error('Possible EventEmitter memory leak detected. ' +
  1987. existing.length + ' "' + String(type) + '" listeners ' +
  1988. 'added. Use emitter.setMaxListeners() to ' +
  1989. 'increase limit.');
  1990. w.name = 'MaxListenersExceededWarning';
  1991. w.emitter = target;
  1992. w.type = type;
  1993. w.count = existing.length;
  1994. if (typeof console === 'object' && console.warn) {
  1995. console.warn('%s: %s', w.name, w.message);
  1996. }
  1997. }
  1998. }
  1999. }
  2000. return target;
  2001. }
  2002. EventEmitter.prototype.addListener = function addListener(type, listener) {
  2003. return _addListener(this, type, listener, false);
  2004. };
  2005. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  2006. EventEmitter.prototype.prependListener =
  2007. function prependListener(type, listener) {
  2008. return _addListener(this, type, listener, true);
  2009. };
  2010. function onceWrapper() {
  2011. if (!this.fired) {
  2012. this.target.removeListener(this.type, this.wrapFn);
  2013. this.fired = true;
  2014. switch (arguments.length) {
  2015. case 0:
  2016. return this.listener.call(this.target);
  2017. case 1:
  2018. return this.listener.call(this.target, arguments[0]);
  2019. case 2:
  2020. return this.listener.call(this.target, arguments[0], arguments[1]);
  2021. case 3:
  2022. return this.listener.call(this.target, arguments[0], arguments[1],
  2023. arguments[2]);
  2024. default:
  2025. var args = new Array(arguments.length);
  2026. for (var i = 0; i < args.length; ++i)
  2027. args[i] = arguments[i];
  2028. this.listener.apply(this.target, args);
  2029. }
  2030. }
  2031. }
  2032. function _onceWrap(target, type, listener) {
  2033. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  2034. var wrapped = bind.call(onceWrapper, state);
  2035. wrapped.listener = listener;
  2036. state.wrapFn = wrapped;
  2037. return wrapped;
  2038. }
  2039. EventEmitter.prototype.once = function once(type, listener) {
  2040. if (typeof listener !== 'function')
  2041. throw new TypeError('"listener" argument must be a function');
  2042. this.on(type, _onceWrap(this, type, listener));
  2043. return this;
  2044. };
  2045. EventEmitter.prototype.prependOnceListener =
  2046. function prependOnceListener(type, listener) {
  2047. if (typeof listener !== 'function')
  2048. throw new TypeError('"listener" argument must be a function');
  2049. this.prependListener(type, _onceWrap(this, type, listener));
  2050. return this;
  2051. };
  2052. // Emits a 'removeListener' event if and only if the listener was removed.
  2053. EventEmitter.prototype.removeListener =
  2054. function removeListener(type, listener) {
  2055. var list, events, position, i, originalListener;
  2056. if (typeof listener !== 'function')
  2057. throw new TypeError('"listener" argument must be a function');
  2058. events = this._events;
  2059. if (!events)
  2060. return this;
  2061. list = events[type];
  2062. if (!list)
  2063. return this;
  2064. if (list === listener || list.listener === listener) {
  2065. if (--this._eventsCount === 0)
  2066. this._events = objectCreate(null);
  2067. else {
  2068. delete events[type];
  2069. if (events.removeListener)
  2070. this.emit('removeListener', type, list.listener || listener);
  2071. }
  2072. } else if (typeof list !== 'function') {
  2073. position = -1;
  2074. for (i = list.length - 1; i >= 0; i--) {
  2075. if (list[i] === listener || list[i].listener === listener) {
  2076. originalListener = list[i].listener;
  2077. position = i;
  2078. break;
  2079. }
  2080. }
  2081. if (position < 0)
  2082. return this;
  2083. if (position === 0)
  2084. list.shift();
  2085. else
  2086. spliceOne(list, position);
  2087. if (list.length === 1)
  2088. events[type] = list[0];
  2089. if (events.removeListener)
  2090. this.emit('removeListener', type, originalListener || listener);
  2091. }
  2092. return this;
  2093. };
  2094. EventEmitter.prototype.removeAllListeners =
  2095. function removeAllListeners(type) {
  2096. var listeners, events, i;
  2097. events = this._events;
  2098. if (!events)
  2099. return this;
  2100. // not listening for removeListener, no need to emit
  2101. if (!events.removeListener) {
  2102. if (arguments.length === 0) {
  2103. this._events = objectCreate(null);
  2104. this._eventsCount = 0;
  2105. } else if (events[type]) {
  2106. if (--this._eventsCount === 0)
  2107. this._events = objectCreate(null);
  2108. else
  2109. delete events[type];
  2110. }
  2111. return this;
  2112. }
  2113. // emit removeListener for all listeners on all events
  2114. if (arguments.length === 0) {
  2115. var keys = objectKeys(events);
  2116. var key;
  2117. for (i = 0; i < keys.length; ++i) {
  2118. key = keys[i];
  2119. if (key === 'removeListener') continue;
  2120. this.removeAllListeners(key);
  2121. }
  2122. this.removeAllListeners('removeListener');
  2123. this._events = objectCreate(null);
  2124. this._eventsCount = 0;
  2125. return this;
  2126. }
  2127. listeners = events[type];
  2128. if (typeof listeners === 'function') {
  2129. this.removeListener(type, listeners);
  2130. } else if (listeners) {
  2131. // LIFO order
  2132. for (i = listeners.length - 1; i >= 0; i--) {
  2133. this.removeListener(type, listeners[i]);
  2134. }
  2135. }
  2136. return this;
  2137. };
  2138. function _listeners(target, type, unwrap) {
  2139. var events = target._events;
  2140. if (!events)
  2141. return [];
  2142. var evlistener = events[type];
  2143. if (!evlistener)
  2144. return [];
  2145. if (typeof evlistener === 'function')
  2146. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  2147. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  2148. }
  2149. EventEmitter.prototype.listeners = function listeners(type) {
  2150. return _listeners(this, type, true);
  2151. };
  2152. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  2153. return _listeners(this, type, false);
  2154. };
  2155. EventEmitter.listenerCount = function (emitter, type) {
  2156. if (typeof emitter.listenerCount === 'function') {
  2157. return emitter.listenerCount(type);
  2158. } else {
  2159. return listenerCount.call(emitter, type);
  2160. }
  2161. };
  2162. EventEmitter.prototype.listenerCount = listenerCount;
  2163. function listenerCount(type) {
  2164. var events = this._events;
  2165. if (events) {
  2166. var evlistener = events[type];
  2167. if (typeof evlistener === 'function') {
  2168. return 1;
  2169. } else if (evlistener) {
  2170. return evlistener.length;
  2171. }
  2172. }
  2173. return 0;
  2174. }
  2175. EventEmitter.prototype.eventNames = function eventNames() {
  2176. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  2177. };
  2178. // About 1.5x faster than the two-arg version of Array#splice().
  2179. function spliceOne(list, index) {
  2180. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  2181. list[i] = list[k];
  2182. list.pop();
  2183. }
  2184. function arrayClone(arr, n) {
  2185. var copy = new Array(n);
  2186. for (var i = 0; i < n; ++i)
  2187. copy[i] = arr[i];
  2188. return copy;
  2189. }
  2190. function unwrapListeners(arr) {
  2191. var ret = new Array(arr.length);
  2192. for (var i = 0; i < ret.length; ++i) {
  2193. ret[i] = arr[i].listener || arr[i];
  2194. }
  2195. return ret;
  2196. }
  2197. function objectCreatePolyfill(proto) {
  2198. var F = function () { };
  2199. F.prototype = proto;
  2200. return new F;
  2201. }
  2202. function objectKeysPolyfill(obj) {
  2203. var keys = [];
  2204. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  2205. keys.push(k);
  2206. }
  2207. return k;
  2208. }
  2209. function functionBindPolyfill(context) {
  2210. var fn = this;
  2211. return function () {
  2212. return fn.apply(context, arguments);
  2213. };
  2214. }
  2215. }, {}], 6: [function (require, module, exports) {
  2216. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2217. var e, m
  2218. var eLen = (nBytes * 8) - mLen - 1
  2219. var eMax = (1 << eLen) - 1
  2220. var eBias = eMax >> 1
  2221. var nBits = -7
  2222. var i = isLE ? (nBytes - 1) : 0
  2223. var d = isLE ? -1 : 1
  2224. var s = buffer[offset + i]
  2225. i += d
  2226. e = s & ((1 << (-nBits)) - 1)
  2227. s >>= (-nBits)
  2228. nBits += eLen
  2229. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) { }
  2230. m = e & ((1 << (-nBits)) - 1)
  2231. e >>= (-nBits)
  2232. nBits += mLen
  2233. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) { }
  2234. if (e === 0) {
  2235. e = 1 - eBias
  2236. } else if (e === eMax) {
  2237. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2238. } else {
  2239. m = m + Math.pow(2, mLen)
  2240. e = e - eBias
  2241. }
  2242. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2243. }
  2244. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2245. var e, m, c
  2246. var eLen = (nBytes * 8) - mLen - 1
  2247. var eMax = (1 << eLen) - 1
  2248. var eBias = eMax >> 1
  2249. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2250. var i = isLE ? 0 : (nBytes - 1)
  2251. var d = isLE ? 1 : -1
  2252. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2253. value = Math.abs(value)
  2254. if (isNaN(value) || value === Infinity) {
  2255. m = isNaN(value) ? 1 : 0
  2256. e = eMax
  2257. } else {
  2258. e = Math.floor(Math.log(value) / Math.LN2)
  2259. if (value * (c = Math.pow(2, -e)) < 1) {
  2260. e--
  2261. c *= 2
  2262. }
  2263. if (e + eBias >= 1) {
  2264. value += rt / c
  2265. } else {
  2266. value += rt * Math.pow(2, 1 - eBias)
  2267. }
  2268. if (value * c >= 2) {
  2269. e++
  2270. c /= 2
  2271. }
  2272. if (e + eBias >= eMax) {
  2273. m = 0
  2274. e = eMax
  2275. } else if (e + eBias >= 1) {
  2276. m = ((value * c) - 1) * Math.pow(2, mLen)
  2277. e = e + eBias
  2278. } else {
  2279. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2280. e = 0
  2281. }
  2282. }
  2283. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) { }
  2284. e = (e << mLen) | m
  2285. eLen += mLen
  2286. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) { }
  2287. buffer[offset + i - d] |= s * 128
  2288. }
  2289. }, {}], 7: [function (require, module, exports) {
  2290. (function (global) {
  2291. 'use strict';
  2292. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  2293. var scheduleDrain;
  2294. {
  2295. if (Mutation) {
  2296. var called = 0;
  2297. var observer = new Mutation(nextTick);
  2298. var element = global.document.createTextNode('');
  2299. observer.observe(element, {
  2300. characterData: true
  2301. });
  2302. scheduleDrain = function () {
  2303. element.data = (called = ++called % 2);
  2304. };
  2305. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  2306. var channel = new global.MessageChannel();
  2307. channel.port1.onmessage = nextTick;
  2308. scheduleDrain = function () {
  2309. channel.port2.postMessage(0);
  2310. };
  2311. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  2312. scheduleDrain = function () {
  2313. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  2314. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  2315. var scriptEl = global.document.createElement('script');
  2316. scriptEl.onreadystatechange = function () {
  2317. nextTick();
  2318. scriptEl.onreadystatechange = null;
  2319. scriptEl.parentNode.removeChild(scriptEl);
  2320. scriptEl = null;
  2321. };
  2322. global.document.documentElement.appendChild(scriptEl);
  2323. };
  2324. } else {
  2325. scheduleDrain = function () {
  2326. setTimeout(nextTick, 0);
  2327. };
  2328. }
  2329. }
  2330. var draining;
  2331. var queue = [];
  2332. //named nextTick for less confusing stack traces
  2333. function nextTick() {
  2334. draining = true;
  2335. var i, oldQueue;
  2336. var len = queue.length;
  2337. while (len) {
  2338. oldQueue = queue;
  2339. queue = [];
  2340. i = -1;
  2341. while (++i < len) {
  2342. oldQueue[i]();
  2343. }
  2344. len = queue.length;
  2345. }
  2346. draining = false;
  2347. }
  2348. module.exports = immediate;
  2349. function immediate(task) {
  2350. if (queue.push(task) === 1 && !draining) {
  2351. scheduleDrain();
  2352. }
  2353. }
  2354. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2355. }, {}], 8: [function (require, module, exports) {
  2356. if (typeof Object.create === 'function') {
  2357. // implementation from standard node.js 'util' module
  2358. module.exports = function inherits(ctor, superCtor) {
  2359. if (superCtor) {
  2360. ctor.super_ = superCtor
  2361. ctor.prototype = Object.create(superCtor.prototype, {
  2362. constructor: {
  2363. value: ctor,
  2364. enumerable: false,
  2365. writable: true,
  2366. configurable: true
  2367. }
  2368. })
  2369. }
  2370. };
  2371. } else {
  2372. // old school shim for old browsers
  2373. module.exports = function inherits(ctor, superCtor) {
  2374. if (superCtor) {
  2375. ctor.super_ = superCtor
  2376. var TempCtor = function () { }
  2377. TempCtor.prototype = superCtor.prototype
  2378. ctor.prototype = new TempCtor()
  2379. ctor.prototype.constructor = ctor
  2380. }
  2381. }
  2382. }
  2383. }, {}], 9: [function (require, module, exports) {
  2384. /*!
  2385. * Determine if an object is a Buffer
  2386. *
  2387. * @author Feross Aboukhadijeh <https://feross.org>
  2388. * @license MIT
  2389. */
  2390. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2391. // Object.prototype.constructor. Remove this eventually
  2392. module.exports = function (obj) {
  2393. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2394. }
  2395. function isBuffer(obj) {
  2396. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2397. }
  2398. // For Node v0.10 support. Remove this eventually.
  2399. function isSlowBuffer(obj) {
  2400. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2401. }
  2402. }, {}], 10: [function (require, module, exports) {
  2403. var toString = {}.toString;
  2404. module.exports = Array.isArray || function (arr) {
  2405. return toString.call(arr) == '[object Array]';
  2406. };
  2407. }, {}], 11: [function (require, module, exports) {
  2408. 'use strict';
  2409. var utils = require('./utils');
  2410. var support = require('./support');
  2411. // private property
  2412. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2413. // public method for encoding
  2414. exports.encode = function (input) {
  2415. var output = [];
  2416. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  2417. var i = 0, len = input.length, remainingBytes = len;
  2418. var isArray = utils.getTypeOf(input) !== "string";
  2419. while (i < input.length) {
  2420. remainingBytes = len - i;
  2421. if (!isArray) {
  2422. chr1 = input.charCodeAt(i++);
  2423. chr2 = i < len ? input.charCodeAt(i++) : 0;
  2424. chr3 = i < len ? input.charCodeAt(i++) : 0;
  2425. } else {
  2426. chr1 = input[i++];
  2427. chr2 = i < len ? input[i++] : 0;
  2428. chr3 = i < len ? input[i++] : 0;
  2429. }
  2430. enc1 = chr1 >> 2;
  2431. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2432. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  2433. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  2434. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  2435. }
  2436. return output.join("");
  2437. };
  2438. // public method for decoding
  2439. exports.decode = function (input) {
  2440. var chr1, chr2, chr3;
  2441. var enc1, enc2, enc3, enc4;
  2442. var i = 0, resultIndex = 0;
  2443. var dataUrlPrefix = "data:";
  2444. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  2445. // This is a common error: people give a data url
  2446. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  2447. // wonders why things don't work.
  2448. // We can detect that the string input looks like a data url but we
  2449. // *can't* be sure it is one: removing everything up to the comma would
  2450. // be too dangerous.
  2451. throw new Error("Invalid base64 input, it looks like a data url.");
  2452. }
  2453. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  2454. var totalLength = input.length * 3 / 4;
  2455. if (input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  2456. totalLength--;
  2457. }
  2458. if (input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  2459. totalLength--;
  2460. }
  2461. if (totalLength % 1 !== 0) {
  2462. // totalLength is not an integer, the length does not match a valid
  2463. // base64 content. That can happen if:
  2464. // - the input is not a base64 content
  2465. // - the input is *almost* a base64 content, with a extra chars at the
  2466. // beginning or at the end
  2467. // - the input uses a base64 variant (base64url for example)
  2468. throw new Error("Invalid base64 input, bad content length.");
  2469. }
  2470. var output;
  2471. if (support.uint8array) {
  2472. output = new Uint8Array(totalLength | 0);
  2473. } else {
  2474. output = new Array(totalLength | 0);
  2475. }
  2476. while (i < input.length) {
  2477. enc1 = _keyStr.indexOf(input.charAt(i++));
  2478. enc2 = _keyStr.indexOf(input.charAt(i++));
  2479. enc3 = _keyStr.indexOf(input.charAt(i++));
  2480. enc4 = _keyStr.indexOf(input.charAt(i++));
  2481. chr1 = (enc1 << 2) | (enc2 >> 4);
  2482. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  2483. chr3 = ((enc3 & 3) << 6) | enc4;
  2484. output[resultIndex++] = chr1;
  2485. if (enc3 !== 64) {
  2486. output[resultIndex++] = chr2;
  2487. }
  2488. if (enc4 !== 64) {
  2489. output[resultIndex++] = chr3;
  2490. }
  2491. }
  2492. return output;
  2493. };
  2494. }, { "./support": 40, "./utils": 42 }], 12: [function (require, module, exports) {
  2495. 'use strict';
  2496. var external = require("./external");
  2497. var DataWorker = require('./stream/DataWorker');
  2498. var DataLengthProbe = require('./stream/DataLengthProbe');
  2499. var Crc32Probe = require('./stream/Crc32Probe');
  2500. var DataLengthProbe = require('./stream/DataLengthProbe');
  2501. /**
  2502. * Represent a compressed object, with everything needed to decompress it.
  2503. * @constructor
  2504. * @param {number} compressedSize the size of the data compressed.
  2505. * @param {number} uncompressedSize the size of the data after decompression.
  2506. * @param {number} crc32 the crc32 of the decompressed file.
  2507. * @param {object} compression the type of compression, see lib/compressions.js.
  2508. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  2509. */
  2510. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  2511. this.compressedSize = compressedSize;
  2512. this.uncompressedSize = uncompressedSize;
  2513. this.crc32 = crc32;
  2514. this.compression = compression;
  2515. this.compressedContent = data;
  2516. }
  2517. CompressedObject.prototype = {
  2518. /**
  2519. * Create a worker to get the uncompressed content.
  2520. * @return {GenericWorker} the worker.
  2521. */
  2522. getContentWorker: function () {
  2523. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  2524. .pipe(this.compression.uncompressWorker())
  2525. .pipe(new DataLengthProbe("data_length"));
  2526. var that = this;
  2527. worker.on("end", function () {
  2528. if (this.streamInfo['data_length'] !== that.uncompressedSize) {
  2529. throw new Error("Bug : uncompressed data size mismatch");
  2530. }
  2531. });
  2532. return worker;
  2533. },
  2534. /**
  2535. * Create a worker to get the compressed content.
  2536. * @return {GenericWorker} the worker.
  2537. */
  2538. getCompressedWorker: function () {
  2539. return new DataWorker(external.Promise.resolve(this.compressedContent))
  2540. .withStreamInfo("compressedSize", this.compressedSize)
  2541. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  2542. .withStreamInfo("crc32", this.crc32)
  2543. .withStreamInfo("compression", this.compression)
  2544. ;
  2545. }
  2546. };
  2547. /**
  2548. * Chain the given worker with other workers to compress the content with the
  2549. * given compression.
  2550. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  2551. * @param {Object} compression the compression object.
  2552. * @param {Object} compressionOptions the options to use when compressing.
  2553. * @return {GenericWorker} the new worker compressing the content.
  2554. */
  2555. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  2556. return uncompressedWorker
  2557. .pipe(new Crc32Probe())
  2558. .pipe(new DataLengthProbe("uncompressedSize"))
  2559. .pipe(compression.compressWorker(compressionOptions))
  2560. .pipe(new DataLengthProbe("compressedSize"))
  2561. .withStreamInfo("compression", compression);
  2562. };
  2563. module.exports = CompressedObject;
  2564. }, { "./external": 16, "./stream/Crc32Probe": 35, "./stream/DataLengthProbe": 36, "./stream/DataWorker": 37 }], 13: [function (require, module, exports) {
  2565. 'use strict';
  2566. var GenericWorker = require("./stream/GenericWorker");
  2567. exports.STORE = {
  2568. magic: "\x00\x00",
  2569. compressWorker: function (compressionOptions) {
  2570. return new GenericWorker("STORE compression");
  2571. },
  2572. uncompressWorker: function () {
  2573. return new GenericWorker("STORE decompression");
  2574. }
  2575. };
  2576. exports.DEFLATE = require('./flate');
  2577. }, { "./flate": 17, "./stream/GenericWorker": 38 }], 14: [function (require, module, exports) {
  2578. 'use strict';
  2579. var utils = require('./utils');
  2580. /**
  2581. * The following functions come from pako, from pako/lib/zlib/crc32.js
  2582. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2583. */
  2584. // Use ordinary array, since untyped makes no boost here
  2585. function makeTable() {
  2586. var c, table = [];
  2587. for (var n = 0; n < 256; n++) {
  2588. c = n;
  2589. for (var k = 0; k < 8; k++) {
  2590. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  2591. }
  2592. table[n] = c;
  2593. }
  2594. return table;
  2595. }
  2596. // Create table on load. Just 255 signed longs. Not a problem.
  2597. var crcTable = makeTable();
  2598. function crc32(crc, buf, len, pos) {
  2599. var t = crcTable, end = pos + len;
  2600. crc = crc ^ (-1);
  2601. for (var i = pos; i < end; i++) {
  2602. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  2603. }
  2604. return (crc ^ (-1)); // >>> 0;
  2605. }
  2606. // That's all for the pako functions.
  2607. /**
  2608. * Compute the crc32 of a string.
  2609. * This is almost the same as the function crc32, but for strings. Using the
  2610. * same function for the two use cases leads to horrible performances.
  2611. * @param {Number} crc the starting value of the crc.
  2612. * @param {String} str the string to use.
  2613. * @param {Number} len the length of the string.
  2614. * @param {Number} pos the starting position for the crc32 computation.
  2615. * @return {Number} the computed crc32.
  2616. */
  2617. function crc32str(crc, str, len, pos) {
  2618. var t = crcTable, end = pos + len;
  2619. crc = crc ^ (-1);
  2620. for (var i = pos; i < end; i++) {
  2621. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  2622. }
  2623. return (crc ^ (-1)); // >>> 0;
  2624. }
  2625. module.exports = function crc32wrapper(input, crc) {
  2626. if (typeof input === "undefined" || !input.length) {
  2627. return 0;
  2628. }
  2629. var isArray = utils.getTypeOf(input) !== "string";
  2630. if (isArray) {
  2631. return crc32(crc | 0, input, input.length, 0);
  2632. } else {
  2633. return crc32str(crc | 0, input, input.length, 0);
  2634. }
  2635. };
  2636. }, { "./utils": 42 }], 15: [function (require, module, exports) {
  2637. 'use strict';
  2638. exports.base64 = false;
  2639. exports.binary = false;
  2640. exports.dir = false;
  2641. exports.createFolders = true;
  2642. exports.date = null;
  2643. exports.compression = null;
  2644. exports.compressionOptions = null;
  2645. exports.comment = null;
  2646. exports.unixPermissions = null;
  2647. exports.dosPermissions = null;
  2648. }, {}], 16: [function (require, module, exports) {
  2649. /* global Promise */
  2650. 'use strict';
  2651. // load the global object first:
  2652. // - it should be better integrated in the system (unhandledRejection in node)
  2653. // - the environment may have a custom Promise implementation (see zone.js)
  2654. var ES6Promise = null;
  2655. if (typeof Promise !== "undefined") {
  2656. ES6Promise = Promise;
  2657. } else {
  2658. ES6Promise = require("lie");
  2659. }
  2660. /**
  2661. * Let the user use/change some implementations.
  2662. */
  2663. module.exports = {
  2664. Promise: ES6Promise
  2665. };
  2666. }, { "lie": 46 }], 17: [function (require, module, exports) {
  2667. 'use strict';
  2668. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  2669. var pako = require("pako");
  2670. var utils = require("./utils");
  2671. var GenericWorker = require("./stream/GenericWorker");
  2672. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  2673. exports.magic = "\x08\x00";
  2674. /**
  2675. * Create a worker that uses pako to inflate/deflate.
  2676. * @constructor
  2677. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  2678. * @param {Object} options the options to use when (de)compressing.
  2679. */
  2680. function FlateWorker(action, options) {
  2681. GenericWorker.call(this, "FlateWorker/" + action);
  2682. this._pako = null;
  2683. this._pakoAction = action;
  2684. this._pakoOptions = options;
  2685. // the `meta` object from the last chunk received
  2686. // this allow this worker to pass around metadata
  2687. this.meta = {};
  2688. }
  2689. utils.inherits(FlateWorker, GenericWorker);
  2690. /**
  2691. * @see GenericWorker.processChunk
  2692. */
  2693. FlateWorker.prototype.processChunk = function (chunk) {
  2694. this.meta = chunk.meta;
  2695. if (this._pako === null) {
  2696. this._createPako();
  2697. }
  2698. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  2699. };
  2700. /**
  2701. * @see GenericWorker.flush
  2702. */
  2703. FlateWorker.prototype.flush = function () {
  2704. GenericWorker.prototype.flush.call(this);
  2705. if (this._pako === null) {
  2706. this._createPako();
  2707. }
  2708. this._pako.push([], true);
  2709. };
  2710. /**
  2711. * @see GenericWorker.cleanUp
  2712. */
  2713. FlateWorker.prototype.cleanUp = function () {
  2714. GenericWorker.prototype.cleanUp.call(this);
  2715. this._pako = null;
  2716. };
  2717. /**
  2718. * Create the _pako object.
  2719. * TODO: lazy-loading this object isn't the best solution but it's the
  2720. * quickest. The best solution is to lazy-load the worker list. See also the
  2721. * issue #446.
  2722. */
  2723. FlateWorker.prototype._createPako = function () {
  2724. this._pako = new pako[this._pakoAction]({
  2725. raw: true,
  2726. level: this._pakoOptions.level || -1 // default compression
  2727. });
  2728. var self = this;
  2729. this._pako.onData = function (data) {
  2730. self.push({
  2731. data: data,
  2732. meta: self.meta
  2733. });
  2734. };
  2735. };
  2736. exports.compressWorker = function (compressionOptions) {
  2737. return new FlateWorker("Deflate", compressionOptions);
  2738. };
  2739. exports.uncompressWorker = function () {
  2740. return new FlateWorker("Inflate", {});
  2741. };
  2742. }, { "./stream/GenericWorker": 38, "./utils": 42, "pako": 47 }], 18: [function (require, module, exports) {
  2743. 'use strict';
  2744. var utils = require('../utils');
  2745. var GenericWorker = require('../stream/GenericWorker');
  2746. var utf8 = require('../utf8');
  2747. var crc32 = require('../crc32');
  2748. var signature = require('../signature');
  2749. /**
  2750. * Transform an integer into a string in hexadecimal.
  2751. * @private
  2752. * @param {number} dec the number to convert.
  2753. * @param {number} bytes the number of bytes to generate.
  2754. * @returns {string} the result.
  2755. */
  2756. var decToHex = function (dec, bytes) {
  2757. var hex = "", i;
  2758. for (i = 0; i < bytes; i++) {
  2759. hex += String.fromCharCode(dec & 0xff);
  2760. dec = dec >>> 8;
  2761. }
  2762. return hex;
  2763. };
  2764. /**
  2765. * Generate the UNIX part of the external file attributes.
  2766. * @param {Object} unixPermissions the unix permissions or null.
  2767. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  2768. * @return {Number} a 32 bit integer.
  2769. *
  2770. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  2771. *
  2772. * TTTTsstrwxrwxrwx0000000000ADVSHR
  2773. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  2774. * ^^^_________________________ setuid, setgid, sticky
  2775. * ^^^^^^^^^________________ permissions
  2776. * ^^^^^^^^^^______ not used ?
  2777. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  2778. */
  2779. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  2780. var result = unixPermissions;
  2781. if (!unixPermissions) {
  2782. // I can't use octal values in strict mode, hence the hexa.
  2783. // 040775 => 0x41fd
  2784. // 0100664 => 0x81b4
  2785. result = isDir ? 0x41fd : 0x81b4;
  2786. }
  2787. return (result & 0xFFFF) << 16;
  2788. };
  2789. /**
  2790. * Generate the DOS part of the external file attributes.
  2791. * @param {Object} dosPermissions the dos permissions or null.
  2792. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  2793. * @return {Number} a 32 bit integer.
  2794. *
  2795. * Bit 0 Read-Only
  2796. * Bit 1 Hidden
  2797. * Bit 2 System
  2798. * Bit 3 Volume Label
  2799. * Bit 4 Directory
  2800. * Bit 5 Archive
  2801. */
  2802. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  2803. // the dir flag is already set for compatibility
  2804. return (dosPermissions || 0) & 0x3F;
  2805. };
  2806. /**
  2807. * Generate the various parts used in the construction of the final zip file.
  2808. * @param {Object} streamInfo the hash with information about the compressed file.
  2809. * @param {Boolean} streamedContent is the content streamed ?
  2810. * @param {Boolean} streamingEnded is the stream finished ?
  2811. * @param {number} offset the current offset from the start of the zip file.
  2812. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  2813. * @param {Function} encodeFileName the function to encode the file name / comment.
  2814. * @return {Object} the zip parts.
  2815. */
  2816. var generateZipParts = function (streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  2817. var file = streamInfo['file'],
  2818. compression = streamInfo['compression'],
  2819. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  2820. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  2821. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  2822. comment = file.comment,
  2823. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  2824. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  2825. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  2826. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  2827. dosTime,
  2828. dosDate,
  2829. extraFields = "",
  2830. unicodePathExtraField = "",
  2831. unicodeCommentExtraField = "",
  2832. dir = file.dir,
  2833. date = file.date;
  2834. var dataInfo = {
  2835. crc32: 0,
  2836. compressedSize: 0,
  2837. uncompressedSize: 0
  2838. };
  2839. // if the content is streamed, the sizes/crc32 are only available AFTER
  2840. // the end of the stream.
  2841. if (!streamedContent || streamingEnded) {
  2842. dataInfo.crc32 = streamInfo['crc32'];
  2843. dataInfo.compressedSize = streamInfo['compressedSize'];
  2844. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  2845. }
  2846. var bitflag = 0;
  2847. if (streamedContent) {
  2848. // Bit 3: the sizes/crc32 are set to zero in the local header.
  2849. // The correct values are put in the data descriptor immediately
  2850. // following the compressed data.
  2851. bitflag |= 0x0008;
  2852. }
  2853. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  2854. // Bit 11: Language encoding flag (EFS).
  2855. bitflag |= 0x0800;
  2856. }
  2857. var extFileAttr = 0;
  2858. var versionMadeBy = 0;
  2859. if (dir) {
  2860. // dos or unix, we set the dos dir flag
  2861. extFileAttr |= 0x00010;
  2862. }
  2863. if (platform === "UNIX") {
  2864. versionMadeBy = 0x031E; // UNIX, version 3.0
  2865. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  2866. } else { // DOS or other, fallback to DOS
  2867. versionMadeBy = 0x0014; // DOS, version 2.0
  2868. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  2869. }
  2870. // date
  2871. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  2872. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  2873. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  2874. dosTime = date.getUTCHours();
  2875. dosTime = dosTime << 6;
  2876. dosTime = dosTime | date.getUTCMinutes();
  2877. dosTime = dosTime << 5;
  2878. dosTime = dosTime | date.getUTCSeconds() / 2;
  2879. dosDate = date.getUTCFullYear() - 1980;
  2880. dosDate = dosDate << 4;
  2881. dosDate = dosDate | (date.getUTCMonth() + 1);
  2882. dosDate = dosDate << 5;
  2883. dosDate = dosDate | date.getUTCDate();
  2884. if (useUTF8ForFileName) {
  2885. // set the unicode path extra field. unzip needs at least one extra
  2886. // field to correctly handle unicode path, so using the path is as good
  2887. // as any other information. This could improve the situation with
  2888. // other archive managers too.
  2889. // This field is usually used without the utf8 flag, with a non
  2890. // unicode path in the header (winrar, winzip). This helps (a bit)
  2891. // with the messy Windows' default compressed folders feature but
  2892. // breaks on p7zip which doesn't seek the unicode path extra field.
  2893. // So for now, UTF-8 everywhere !
  2894. unicodePathExtraField =
  2895. // Version
  2896. decToHex(1, 1) +
  2897. // NameCRC32
  2898. decToHex(crc32(encodedFileName), 4) +
  2899. // UnicodeName
  2900. utfEncodedFileName;
  2901. extraFields +=
  2902. // Info-ZIP Unicode Path Extra Field
  2903. "\x75\x70" +
  2904. // size
  2905. decToHex(unicodePathExtraField.length, 2) +
  2906. // content
  2907. unicodePathExtraField;
  2908. }
  2909. if (useUTF8ForComment) {
  2910. unicodeCommentExtraField =
  2911. // Version
  2912. decToHex(1, 1) +
  2913. // CommentCRC32
  2914. decToHex(crc32(encodedComment), 4) +
  2915. // UnicodeName
  2916. utfEncodedComment;
  2917. extraFields +=
  2918. // Info-ZIP Unicode Path Extra Field
  2919. "\x75\x63" +
  2920. // size
  2921. decToHex(unicodeCommentExtraField.length, 2) +
  2922. // content
  2923. unicodeCommentExtraField;
  2924. }
  2925. var header = "";
  2926. // version needed to extract
  2927. header += "\x0A\x00";
  2928. // general purpose bit flag
  2929. header += decToHex(bitflag, 2);
  2930. // compression method
  2931. header += compression.magic;
  2932. // last mod file time
  2933. header += decToHex(dosTime, 2);
  2934. // last mod file date
  2935. header += decToHex(dosDate, 2);
  2936. // crc-32
  2937. header += decToHex(dataInfo.crc32, 4);
  2938. // compressed size
  2939. header += decToHex(dataInfo.compressedSize, 4);
  2940. // uncompressed size
  2941. header += decToHex(dataInfo.uncompressedSize, 4);
  2942. // file name length
  2943. header += decToHex(encodedFileName.length, 2);
  2944. // extra field length
  2945. header += decToHex(extraFields.length, 2);
  2946. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  2947. var dirRecord = signature.CENTRAL_FILE_HEADER +
  2948. // version made by (00: DOS)
  2949. decToHex(versionMadeBy, 2) +
  2950. // file header (common to file and central directory)
  2951. header +
  2952. // file comment length
  2953. decToHex(encodedComment.length, 2) +
  2954. // disk number start
  2955. "\x00\x00" +
  2956. // internal file attributes TODO
  2957. "\x00\x00" +
  2958. // external file attributes
  2959. decToHex(extFileAttr, 4) +
  2960. // relative offset of local header
  2961. decToHex(offset, 4) +
  2962. // file name
  2963. encodedFileName +
  2964. // extra field
  2965. extraFields +
  2966. // file comment
  2967. encodedComment;
  2968. return {
  2969. fileRecord: fileRecord,
  2970. dirRecord: dirRecord
  2971. };
  2972. };
  2973. /**
  2974. * Generate the EOCD record.
  2975. * @param {Number} entriesCount the number of entries in the zip file.
  2976. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  2977. * @param {Number} localDirLength the length (in bytes) of the local dir.
  2978. * @param {String} comment the zip file comment as a binary string.
  2979. * @param {Function} encodeFileName the function to encode the comment.
  2980. * @return {String} the EOCD record.
  2981. */
  2982. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  2983. var dirEnd = "";
  2984. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  2985. // end of central dir signature
  2986. dirEnd = signature.CENTRAL_DIRECTORY_END +
  2987. // number of this disk
  2988. "\x00\x00" +
  2989. // number of the disk with the start of the central directory
  2990. "\x00\x00" +
  2991. // total number of entries in the central directory on this disk
  2992. decToHex(entriesCount, 2) +
  2993. // total number of entries in the central directory
  2994. decToHex(entriesCount, 2) +
  2995. // size of the central directory 4 bytes
  2996. decToHex(centralDirLength, 4) +
  2997. // offset of start of central directory with respect to the starting disk number
  2998. decToHex(localDirLength, 4) +
  2999. // .ZIP file comment length
  3000. decToHex(encodedComment.length, 2) +
  3001. // .ZIP file comment
  3002. encodedComment;
  3003. return dirEnd;
  3004. };
  3005. /**
  3006. * Generate data descriptors for a file entry.
  3007. * @param {Object} streamInfo the hash generated by a worker, containing information
  3008. * on the file entry.
  3009. * @return {String} the data descriptors.
  3010. */
  3011. var generateDataDescriptors = function (streamInfo) {
  3012. var descriptor = "";
  3013. descriptor = signature.DATA_DESCRIPTOR +
  3014. // crc-32 4 bytes
  3015. decToHex(streamInfo['crc32'], 4) +
  3016. // compressed size 4 bytes
  3017. decToHex(streamInfo['compressedSize'], 4) +
  3018. // uncompressed size 4 bytes
  3019. decToHex(streamInfo['uncompressedSize'], 4);
  3020. return descriptor;
  3021. };
  3022. /**
  3023. * A worker to concatenate other workers to create a zip file.
  3024. * @param {Boolean} streamFiles `true` to stream the content of the files,
  3025. * `false` to accumulate it.
  3026. * @param {String} comment the comment to use.
  3027. * @param {String} platform the platform to use, "UNIX" or "DOS".
  3028. * @param {Function} encodeFileName the function to encode file names and comments.
  3029. */
  3030. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  3031. GenericWorker.call(this, "ZipFileWorker");
  3032. // The number of bytes written so far. This doesn't count accumulated chunks.
  3033. this.bytesWritten = 0;
  3034. // The comment of the zip file
  3035. this.zipComment = comment;
  3036. // The platform "generating" the zip file.
  3037. this.zipPlatform = platform;
  3038. // the function to encode file names and comments.
  3039. this.encodeFileName = encodeFileName;
  3040. // Should we stream the content of the files ?
  3041. this.streamFiles = streamFiles;
  3042. // If `streamFiles` is false, we will need to accumulate the content of the
  3043. // files to calculate sizes / crc32 (and write them *before* the content).
  3044. // This boolean indicates if we are accumulating chunks (it will change a lot
  3045. // during the lifetime of this worker).
  3046. this.accumulate = false;
  3047. // The buffer receiving chunks when accumulating content.
  3048. this.contentBuffer = [];
  3049. // The list of generated directory records.
  3050. this.dirRecords = [];
  3051. // The offset (in bytes) from the beginning of the zip file for the current source.
  3052. this.currentSourceOffset = 0;
  3053. // The total number of entries in this zip file.
  3054. this.entriesCount = 0;
  3055. // the name of the file currently being added, null when handling the end of the zip file.
  3056. // Used for the emitted metadata.
  3057. this.currentFile = null;
  3058. this._sources = [];
  3059. }
  3060. utils.inherits(ZipFileWorker, GenericWorker);
  3061. /**
  3062. * @see GenericWorker.push
  3063. */
  3064. ZipFileWorker.prototype.push = function (chunk) {
  3065. var currentFilePercent = chunk.meta.percent || 0;
  3066. var entriesCount = this.entriesCount;
  3067. var remainingFiles = this._sources.length;
  3068. if (this.accumulate) {
  3069. this.contentBuffer.push(chunk);
  3070. } else {
  3071. this.bytesWritten += chunk.data.length;
  3072. GenericWorker.prototype.push.call(this, {
  3073. data: chunk.data,
  3074. meta: {
  3075. currentFile: this.currentFile,
  3076. percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  3077. }
  3078. });
  3079. }
  3080. };
  3081. /**
  3082. * The worker started a new source (an other worker).
  3083. * @param {Object} streamInfo the streamInfo object from the new source.
  3084. */
  3085. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  3086. this.currentSourceOffset = this.bytesWritten;
  3087. this.currentFile = streamInfo['file'].name;
  3088. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  3089. // don't stream folders (because they don't have any content)
  3090. if (streamedContent) {
  3091. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  3092. this.push({
  3093. data: record.fileRecord,
  3094. meta: { percent: 0 }
  3095. });
  3096. } else {
  3097. // we need to wait for the whole file before pushing anything
  3098. this.accumulate = true;
  3099. }
  3100. };
  3101. /**
  3102. * The worker finished a source (an other worker).
  3103. * @param {Object} streamInfo the streamInfo object from the finished source.
  3104. */
  3105. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  3106. this.accumulate = false;
  3107. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  3108. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  3109. this.dirRecords.push(record.dirRecord);
  3110. if (streamedContent) {
  3111. // after the streamed file, we put data descriptors
  3112. this.push({
  3113. data: generateDataDescriptors(streamInfo),
  3114. meta: { percent: 100 }
  3115. });
  3116. } else {
  3117. // the content wasn't streamed, we need to push everything now
  3118. // first the file record, then the content
  3119. this.push({
  3120. data: record.fileRecord,
  3121. meta: { percent: 0 }
  3122. });
  3123. while (this.contentBuffer.length) {
  3124. this.push(this.contentBuffer.shift());
  3125. }
  3126. }
  3127. this.currentFile = null;
  3128. };
  3129. /**
  3130. * @see GenericWorker.flush
  3131. */
  3132. ZipFileWorker.prototype.flush = function () {
  3133. var localDirLength = this.bytesWritten;
  3134. for (var i = 0; i < this.dirRecords.length; i++) {
  3135. this.push({
  3136. data: this.dirRecords[i],
  3137. meta: { percent: 100 }
  3138. });
  3139. }
  3140. var centralDirLength = this.bytesWritten - localDirLength;
  3141. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  3142. this.push({
  3143. data: dirEnd,
  3144. meta: { percent: 100 }
  3145. });
  3146. };
  3147. /**
  3148. * Prepare the next source to be read.
  3149. */
  3150. ZipFileWorker.prototype.prepareNextSource = function () {
  3151. this.previous = this._sources.shift();
  3152. this.openedSource(this.previous.streamInfo);
  3153. if (this.isPaused) {
  3154. this.previous.pause();
  3155. } else {
  3156. this.previous.resume();
  3157. }
  3158. };
  3159. /**
  3160. * @see GenericWorker.registerPrevious
  3161. */
  3162. ZipFileWorker.prototype.registerPrevious = function (previous) {
  3163. this._sources.push(previous);
  3164. var self = this;
  3165. previous.on('data', function (chunk) {
  3166. self.processChunk(chunk);
  3167. });
  3168. previous.on('end', function () {
  3169. self.closedSource(self.previous.streamInfo);
  3170. if (self._sources.length) {
  3171. self.prepareNextSource();
  3172. } else {
  3173. self.end();
  3174. }
  3175. });
  3176. previous.on('error', function (e) {
  3177. self.error(e);
  3178. });
  3179. return this;
  3180. };
  3181. /**
  3182. * @see GenericWorker.resume
  3183. */
  3184. ZipFileWorker.prototype.resume = function () {
  3185. if (!GenericWorker.prototype.resume.call(this)) {
  3186. return false;
  3187. }
  3188. if (!this.previous && this._sources.length) {
  3189. this.prepareNextSource();
  3190. return true;
  3191. }
  3192. if (!this.previous && !this._sources.length && !this.generatedError) {
  3193. this.end();
  3194. return true;
  3195. }
  3196. };
  3197. /**
  3198. * @see GenericWorker.error
  3199. */
  3200. ZipFileWorker.prototype.error = function (e) {
  3201. var sources = this._sources;
  3202. if (!GenericWorker.prototype.error.call(this, e)) {
  3203. return false;
  3204. }
  3205. for (var i = 0; i < sources.length; i++) {
  3206. try {
  3207. sources[i].error(e);
  3208. } catch (e) {
  3209. // the `error` exploded, nothing to do
  3210. }
  3211. }
  3212. return true;
  3213. };
  3214. /**
  3215. * @see GenericWorker.lock
  3216. */
  3217. ZipFileWorker.prototype.lock = function () {
  3218. GenericWorker.prototype.lock.call(this);
  3219. var sources = this._sources;
  3220. for (var i = 0; i < sources.length; i++) {
  3221. sources[i].lock();
  3222. }
  3223. };
  3224. module.exports = ZipFileWorker;
  3225. }, { "../crc32": 14, "../signature": 33, "../stream/GenericWorker": 38, "../utf8": 41, "../utils": 42 }], 19: [function (require, module, exports) {
  3226. 'use strict';
  3227. var compressions = require('../compressions');
  3228. var ZipFileWorker = require('./ZipFileWorker');
  3229. /**
  3230. * Find the compression to use.
  3231. * @param {String} fileCompression the compression defined at the file level, if any.
  3232. * @param {String} zipCompression the compression defined at the load() level.
  3233. * @return {Object} the compression object to use.
  3234. */
  3235. var getCompression = function (fileCompression, zipCompression) {
  3236. var compressionName = fileCompression || zipCompression;
  3237. var compression = compressions[compressionName];
  3238. if (!compression) {
  3239. throw new Error(compressionName + " is not a valid compression method !");
  3240. }
  3241. return compression;
  3242. };
  3243. /**
  3244. * Create a worker to generate a zip file.
  3245. * @param {JSZip} zip the JSZip instance at the right root level.
  3246. * @param {Object} options to generate the zip file.
  3247. * @param {String} comment the comment to use.
  3248. */
  3249. exports.generateWorker = function (zip, options, comment) {
  3250. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  3251. var entriesCount = 0;
  3252. try {
  3253. zip.forEach(function (relativePath, file) {
  3254. entriesCount++;
  3255. var compression = getCompression(file.options.compression, options.compression);
  3256. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  3257. var dir = file.dir, date = file.date;
  3258. file._compressWorker(compression, compressionOptions)
  3259. .withStreamInfo("file", {
  3260. name: relativePath,
  3261. dir: dir,
  3262. date: date,
  3263. comment: file.comment || "",
  3264. unixPermissions: file.unixPermissions,
  3265. dosPermissions: file.dosPermissions
  3266. })
  3267. .pipe(zipFileWorker);
  3268. });
  3269. zipFileWorker.entriesCount = entriesCount;
  3270. } catch (e) {
  3271. zipFileWorker.error(e);
  3272. }
  3273. return zipFileWorker;
  3274. };
  3275. }, { "../compressions": 13, "./ZipFileWorker": 18 }], 20: [function (require, module, exports) {
  3276. 'use strict';
  3277. /**
  3278. * Representation a of zip file in js
  3279. * @constructor
  3280. */
  3281. function JSZip() {
  3282. // if this constructor is used without `new`, it adds `new` before itself:
  3283. if (!(this instanceof JSZip)) {
  3284. return new JSZip();
  3285. }
  3286. if (arguments.length) {
  3287. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  3288. }
  3289. // object containing the files :
  3290. // {
  3291. // "folder/" : {...},
  3292. // "folder/data.txt" : {...}
  3293. // }
  3294. this.files = {};
  3295. this.comment = null;
  3296. // Where we are in the hierarchy
  3297. this.root = "";
  3298. this.clone = function () {
  3299. var newObj = new JSZip();
  3300. for (var i in this) {
  3301. if (typeof this[i] !== "function") {
  3302. newObj[i] = this[i];
  3303. }
  3304. }
  3305. return newObj;
  3306. };
  3307. }
  3308. JSZip.prototype = require('./object');
  3309. JSZip.prototype.loadAsync = require('./load');
  3310. JSZip.support = require('./support');
  3311. JSZip.defaults = require('./defaults');
  3312. // TODO find a better way to handle this version,
  3313. // a require('package.json').version doesn't work with webpack, see #327
  3314. JSZip.version = "3.5.0";
  3315. JSZip.loadAsync = function (content, options) {
  3316. return new JSZip().loadAsync(content, options);
  3317. };
  3318. JSZip.external = require("./external");
  3319. module.exports = JSZip;
  3320. }, { "./defaults": 15, "./external": 16, "./load": 21, "./object": 25, "./support": 40 }], 21: [function (require, module, exports) {
  3321. 'use strict';
  3322. var utils = require('./utils');
  3323. var external = require("./external");
  3324. var utf8 = require('./utf8');
  3325. var utils = require('./utils');
  3326. var ZipEntries = require('./zipEntries');
  3327. var Crc32Probe = require('./stream/Crc32Probe');
  3328. var nodejsUtils = require("./nodejsUtils");
  3329. /**
  3330. * Check the CRC32 of an entry.
  3331. * @param {ZipEntry} zipEntry the zip entry to check.
  3332. * @return {Promise} the result.
  3333. */
  3334. function checkEntryCRC32(zipEntry) {
  3335. return new external.Promise(function (resolve, reject) {
  3336. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  3337. worker.on("error", function (e) {
  3338. reject(e);
  3339. })
  3340. .on("end", function () {
  3341. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  3342. reject(new Error("Corrupted zip : CRC32 mismatch"));
  3343. } else {
  3344. resolve();
  3345. }
  3346. })
  3347. .resume();
  3348. });
  3349. }
  3350. module.exports = function (data, options) {
  3351. var zip = this;
  3352. options = utils.extend(options || {}, {
  3353. base64: false,
  3354. checkCRC32: false,
  3355. optimizedBinaryString: false,
  3356. createFolders: false,
  3357. decodeFileName: utf8.utf8decode
  3358. });
  3359. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  3360. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  3361. }
  3362. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  3363. .then(function (data) {
  3364. var zipEntries = new ZipEntries(options);
  3365. zipEntries.load(data);
  3366. return zipEntries;
  3367. }).then(function checkCRC32(zipEntries) {
  3368. var promises = [external.Promise.resolve(zipEntries)];
  3369. var files = zipEntries.files;
  3370. if (options.checkCRC32) {
  3371. for (var i = 0; i < files.length; i++) {
  3372. promises.push(checkEntryCRC32(files[i]));
  3373. }
  3374. }
  3375. return external.Promise.all(promises);
  3376. }).then(function addFiles(results) {
  3377. var zipEntries = results.shift();
  3378. var files = zipEntries.files;
  3379. for (var i = 0; i < files.length; i++) {
  3380. var input = files[i];
  3381. zip.file(input.fileNameStr, input.decompressed, {
  3382. binary: true,
  3383. optimizedBinaryString: true,
  3384. date: input.date,
  3385. dir: input.dir,
  3386. comment: input.fileCommentStr.length ? input.fileCommentStr : null,
  3387. unixPermissions: input.unixPermissions,
  3388. dosPermissions: input.dosPermissions,
  3389. createFolders: options.createFolders
  3390. });
  3391. }
  3392. if (zipEntries.zipComment.length) {
  3393. zip.comment = zipEntries.zipComment;
  3394. }
  3395. return zip;
  3396. });
  3397. };
  3398. }, { "./external": 16, "./nodejsUtils": 22, "./stream/Crc32Probe": 35, "./utf8": 41, "./utils": 42, "./zipEntries": 43 }], 22: [function (require, module, exports) {
  3399. (function (Buffer) {
  3400. 'use strict';
  3401. module.exports = {
  3402. /**
  3403. * True if this is running in Nodejs, will be undefined in a browser.
  3404. * In a browser, browserify won't include this file and the whole module
  3405. * will be resolved an empty object.
  3406. */
  3407. isNode: typeof Buffer !== "undefined",
  3408. /**
  3409. * Create a new nodejs Buffer from an existing content.
  3410. * @param {Object} data the data to pass to the constructor.
  3411. * @param {String} encoding the encoding to use.
  3412. * @return {Buffer} a new Buffer.
  3413. */
  3414. newBufferFrom: function (data, encoding) {
  3415. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  3416. return Buffer.from(data, encoding);
  3417. } else {
  3418. if (typeof data === "number") {
  3419. // Safeguard for old Node.js versions. On newer versions,
  3420. // Buffer.from(number) / Buffer(number, encoding) already throw.
  3421. throw new Error("The \"data\" argument must not be a number");
  3422. }
  3423. return new Buffer(data, encoding);
  3424. }
  3425. },
  3426. /**
  3427. * Create a new nodejs Buffer with the specified size.
  3428. * @param {Integer} size the size of the buffer.
  3429. * @return {Buffer} a new Buffer.
  3430. */
  3431. allocBuffer: function (size) {
  3432. if (Buffer.alloc) {
  3433. return Buffer.alloc(size);
  3434. } else {
  3435. var buf = new Buffer(size);
  3436. buf.fill(0);
  3437. return buf;
  3438. }
  3439. },
  3440. /**
  3441. * Find out if an object is a Buffer.
  3442. * @param {Object} b the object to test.
  3443. * @return {Boolean} true if the object is a Buffer, false otherwise.
  3444. */
  3445. isBuffer: function (b) {
  3446. return Buffer.isBuffer(b);
  3447. },
  3448. isStream: function (obj) {
  3449. return obj &&
  3450. typeof obj.on === "function" &&
  3451. typeof obj.pause === "function" &&
  3452. typeof obj.resume === "function";
  3453. }
  3454. };
  3455. }).call(this, require("buffer").Buffer)
  3456. }, { "buffer": 3 }], 23: [function (require, module, exports) {
  3457. "use strict";
  3458. var utils = require('../utils');
  3459. var GenericWorker = require('../stream/GenericWorker');
  3460. /**
  3461. * A worker that use a nodejs stream as source.
  3462. * @constructor
  3463. * @param {String} filename the name of the file entry for this stream.
  3464. * @param {Readable} stream the nodejs stream.
  3465. */
  3466. function NodejsStreamInputAdapter(filename, stream) {
  3467. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  3468. this._upstreamEnded = false;
  3469. this._bindStream(stream);
  3470. }
  3471. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  3472. /**
  3473. * Prepare the stream and bind the callbacks on it.
  3474. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  3475. * @param {Stream} stream the nodejs stream to use.
  3476. */
  3477. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  3478. var self = this;
  3479. this._stream = stream;
  3480. stream.pause();
  3481. stream
  3482. .on("data", function (chunk) {
  3483. self.push({
  3484. data: chunk,
  3485. meta: {
  3486. percent: 0
  3487. }
  3488. });
  3489. })
  3490. .on("error", function (e) {
  3491. if (self.isPaused) {
  3492. this.generatedError = e;
  3493. } else {
  3494. self.error(e);
  3495. }
  3496. })
  3497. .on("end", function () {
  3498. if (self.isPaused) {
  3499. self._upstreamEnded = true;
  3500. } else {
  3501. self.end();
  3502. }
  3503. });
  3504. };
  3505. NodejsStreamInputAdapter.prototype.pause = function () {
  3506. if (!GenericWorker.prototype.pause.call(this)) {
  3507. return false;
  3508. }
  3509. this._stream.pause();
  3510. return true;
  3511. };
  3512. NodejsStreamInputAdapter.prototype.resume = function () {
  3513. if (!GenericWorker.prototype.resume.call(this)) {
  3514. return false;
  3515. }
  3516. if (this._upstreamEnded) {
  3517. this.end();
  3518. } else {
  3519. this._stream.resume();
  3520. }
  3521. return true;
  3522. };
  3523. module.exports = NodejsStreamInputAdapter;
  3524. }, { "../stream/GenericWorker": 38, "../utils": 42 }], 24: [function (require, module, exports) {
  3525. 'use strict';
  3526. var Readable = require('readable-stream').Readable;
  3527. var utils = require('../utils');
  3528. utils.inherits(NodejsStreamOutputAdapter, Readable);
  3529. /**
  3530. * A nodejs stream using a worker as source.
  3531. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  3532. * @constructor
  3533. * @param {StreamHelper} helper the helper wrapping the worker
  3534. * @param {Object} options the nodejs stream options
  3535. * @param {Function} updateCb the update callback.
  3536. */
  3537. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  3538. Readable.call(this, options);
  3539. this._helper = helper;
  3540. var self = this;
  3541. helper.on("data", function (data, meta) {
  3542. if (!self.push(data)) {
  3543. self._helper.pause();
  3544. }
  3545. if (updateCb) {
  3546. updateCb(meta);
  3547. }
  3548. })
  3549. .on("error", function (e) {
  3550. self.emit('error', e);
  3551. })
  3552. .on("end", function () {
  3553. self.push(null);
  3554. });
  3555. }
  3556. NodejsStreamOutputAdapter.prototype._read = function () {
  3557. this._helper.resume();
  3558. };
  3559. module.exports = NodejsStreamOutputAdapter;
  3560. }, { "../utils": 42, "readable-stream": 26 }], 25: [function (require, module, exports) {
  3561. 'use strict';
  3562. var utf8 = require('./utf8');
  3563. var utils = require('./utils');
  3564. var GenericWorker = require('./stream/GenericWorker');
  3565. var StreamHelper = require('./stream/StreamHelper');
  3566. var defaults = require('./defaults');
  3567. var CompressedObject = require('./compressedObject');
  3568. var ZipObject = require('./zipObject');
  3569. var generate = require("./generate");
  3570. var nodejsUtils = require("./nodejsUtils");
  3571. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  3572. /**
  3573. * Add a file in the current folder.
  3574. * @private
  3575. * @param {string} name the name of the file
  3576. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  3577. * @param {Object} originalOptions the options of the file
  3578. * @return {Object} the new file.
  3579. */
  3580. var fileAdd = function (name, data, originalOptions) {
  3581. // be sure sub folders exist
  3582. var dataType = utils.getTypeOf(data),
  3583. parent;
  3584. /*
  3585. * Correct options.
  3586. */
  3587. var o = utils.extend(originalOptions || {}, defaults);
  3588. o.date = o.date || new Date();
  3589. if (o.compression !== null) {
  3590. o.compression = o.compression.toUpperCase();
  3591. }
  3592. if (typeof o.unixPermissions === "string") {
  3593. o.unixPermissions = parseInt(o.unixPermissions, 8);
  3594. }
  3595. // UNX_IFDIR 0040000 see zipinfo.c
  3596. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  3597. o.dir = true;
  3598. }
  3599. // Bit 4 Directory
  3600. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  3601. o.dir = true;
  3602. }
  3603. if (o.dir) {
  3604. name = forceTrailingSlash(name);
  3605. }
  3606. if (o.createFolders && (parent = parentFolder(name))) {
  3607. folderAdd.call(this, parent, true);
  3608. }
  3609. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  3610. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  3611. o.binary = !isUnicodeString;
  3612. }
  3613. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  3614. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  3615. o.base64 = false;
  3616. o.binary = true;
  3617. data = "";
  3618. o.compression = "STORE";
  3619. dataType = "string";
  3620. }
  3621. /*
  3622. * Convert content to fit.
  3623. */
  3624. var zipObjectContent = null;
  3625. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  3626. zipObjectContent = data;
  3627. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  3628. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  3629. } else {
  3630. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  3631. }
  3632. var object = new ZipObject(name, zipObjectContent, o);
  3633. this.files[name] = object;
  3634. /*
  3635. TODO: we can't throw an exception because we have async promises
  3636. (we can have a promise of a Date() for example) but returning a
  3637. promise is useless because file(name, data) returns the JSZip
  3638. object for chaining. Should we break that to allow the user
  3639. to catch the error ?
  3640. return external.Promise.resolve(zipObjectContent)
  3641. .then(function () {
  3642. return object;
  3643. });
  3644. */
  3645. };
  3646. /**
  3647. * Find the parent folder of the path.
  3648. * @private
  3649. * @param {string} path the path to use
  3650. * @return {string} the parent folder, or ""
  3651. */
  3652. var parentFolder = function (path) {
  3653. if (path.slice(-1) === '/') {
  3654. path = path.substring(0, path.length - 1);
  3655. }
  3656. var lastSlash = path.lastIndexOf('/');
  3657. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  3658. };
  3659. /**
  3660. * Returns the path with a slash at the end.
  3661. * @private
  3662. * @param {String} path the path to check.
  3663. * @return {String} the path with a trailing slash.
  3664. */
  3665. var forceTrailingSlash = function (path) {
  3666. // Check the name ends with a /
  3667. if (path.slice(-1) !== "/") {
  3668. path += "/"; // IE doesn't like substr(-1)
  3669. }
  3670. return path;
  3671. };
  3672. /**
  3673. * Add a (sub) folder in the current folder.
  3674. * @private
  3675. * @param {string} name the folder's name
  3676. * @param {boolean=} [createFolders] If true, automatically create sub
  3677. * folders. Defaults to false.
  3678. * @return {Object} the new folder.
  3679. */
  3680. var folderAdd = function (name, createFolders) {
  3681. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  3682. name = forceTrailingSlash(name);
  3683. // Does this folder already exist?
  3684. if (!this.files[name]) {
  3685. fileAdd.call(this, name, null, {
  3686. dir: true,
  3687. createFolders: createFolders
  3688. });
  3689. }
  3690. return this.files[name];
  3691. };
  3692. /**
  3693. * Cross-window, cross-Node-context regular expression detection
  3694. * @param {Object} object Anything
  3695. * @return {Boolean} true if the object is a regular expression,
  3696. * false otherwise
  3697. */
  3698. function isRegExp(object) {
  3699. return Object.prototype.toString.call(object) === "[object RegExp]";
  3700. }
  3701. // return the actual prototype of JSZip
  3702. var out = {
  3703. /**
  3704. * @see loadAsync
  3705. */
  3706. load: function () {
  3707. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3708. },
  3709. /**
  3710. * Call a callback function for each entry at this folder level.
  3711. * @param {Function} cb the callback function:
  3712. * function (relativePath, file) {...}
  3713. * It takes 2 arguments : the relative path and the file.
  3714. */
  3715. forEach: function (cb) {
  3716. var filename, relativePath, file;
  3717. for (filename in this.files) {
  3718. if (!this.files.hasOwnProperty(filename)) {
  3719. continue;
  3720. }
  3721. file = this.files[filename];
  3722. relativePath = filename.slice(this.root.length, filename.length);
  3723. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  3724. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  3725. }
  3726. }
  3727. },
  3728. /**
  3729. * Filter nested files/folders with the specified function.
  3730. * @param {Function} search the predicate to use :
  3731. * function (relativePath, file) {...}
  3732. * It takes 2 arguments : the relative path and the file.
  3733. * @return {Array} An array of matching elements.
  3734. */
  3735. filter: function (search) {
  3736. var result = [];
  3737. this.forEach(function (relativePath, entry) {
  3738. if (search(relativePath, entry)) { // the file matches the function
  3739. result.push(entry);
  3740. }
  3741. });
  3742. return result;
  3743. },
  3744. /**
  3745. * Add a file to the zip file, or search a file.
  3746. * @param {string|RegExp} name The name of the file to add (if data is defined),
  3747. * the name of the file to find (if no data) or a regex to match files.
  3748. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  3749. * @param {Object} o File options
  3750. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  3751. * a file (when searching by string) or an array of files (when searching by regex).
  3752. */
  3753. file: function (name, data, o) {
  3754. if (arguments.length === 1) {
  3755. if (isRegExp(name)) {
  3756. var regexp = name;
  3757. return this.filter(function (relativePath, file) {
  3758. return !file.dir && regexp.test(relativePath);
  3759. });
  3760. }
  3761. else { // text
  3762. var obj = this.files[this.root + name];
  3763. if (obj && !obj.dir) {
  3764. return obj;
  3765. } else {
  3766. return null;
  3767. }
  3768. }
  3769. }
  3770. else { // more than one argument : we have data !
  3771. name = this.root + name;
  3772. fileAdd.call(this, name, data, o);
  3773. }
  3774. return this;
  3775. },
  3776. /**
  3777. * Add a directory to the zip file, or search.
  3778. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  3779. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  3780. */
  3781. folder: function (arg) {
  3782. if (!arg) {
  3783. return this;
  3784. }
  3785. if (isRegExp(arg)) {
  3786. return this.filter(function (relativePath, file) {
  3787. return file.dir && arg.test(relativePath);
  3788. });
  3789. }
  3790. // else, name is a new folder
  3791. var name = this.root + arg;
  3792. var newFolder = folderAdd.call(this, name);
  3793. // Allow chaining by returning a new object with this folder as the root
  3794. var ret = this.clone();
  3795. ret.root = newFolder.name;
  3796. return ret;
  3797. },
  3798. /**
  3799. * Delete a file, or a directory and all sub-files, from the zip
  3800. * @param {string} name the name of the file to delete
  3801. * @return {JSZip} this JSZip object
  3802. */
  3803. remove: function (name) {
  3804. name = this.root + name;
  3805. var file = this.files[name];
  3806. if (!file) {
  3807. // Look for any folders
  3808. if (name.slice(-1) !== "/") {
  3809. name += "/";
  3810. }
  3811. file = this.files[name];
  3812. }
  3813. if (file && !file.dir) {
  3814. // file
  3815. delete this.files[name];
  3816. } else {
  3817. // maybe a folder, delete recursively
  3818. var kids = this.filter(function (relativePath, file) {
  3819. return file.name.slice(0, name.length) === name;
  3820. });
  3821. for (var i = 0; i < kids.length; i++) {
  3822. delete this.files[kids[i].name];
  3823. }
  3824. }
  3825. return this;
  3826. },
  3827. /**
  3828. * Generate the complete zip file
  3829. * @param {Object} options the options to generate the zip file :
  3830. * - compression, "STORE" by default.
  3831. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  3832. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  3833. */
  3834. generate: function (options) {
  3835. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3836. },
  3837. /**
  3838. * Generate the complete zip file as an internal stream.
  3839. * @param {Object} options the options to generate the zip file :
  3840. * - compression, "STORE" by default.
  3841. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  3842. * @return {StreamHelper} the streamed zip file.
  3843. */
  3844. generateInternalStream: function (options) {
  3845. var worker, opts = {};
  3846. try {
  3847. opts = utils.extend(options || {}, {
  3848. streamFiles: false,
  3849. compression: "STORE",
  3850. compressionOptions: null,
  3851. type: "",
  3852. platform: "DOS",
  3853. comment: null,
  3854. mimeType: 'application/zip',
  3855. encodeFileName: utf8.utf8encode
  3856. });
  3857. opts.type = opts.type.toLowerCase();
  3858. opts.compression = opts.compression.toUpperCase();
  3859. // "binarystring" is preferred but the internals use "string".
  3860. if (opts.type === "binarystring") {
  3861. opts.type = "string";
  3862. }
  3863. if (!opts.type) {
  3864. throw new Error("No output type specified.");
  3865. }
  3866. utils.checkSupport(opts.type);
  3867. // accept nodejs `process.platform`
  3868. if (
  3869. opts.platform === 'darwin' ||
  3870. opts.platform === 'freebsd' ||
  3871. opts.platform === 'linux' ||
  3872. opts.platform === 'sunos'
  3873. ) {
  3874. opts.platform = "UNIX";
  3875. }
  3876. if (opts.platform === 'win32') {
  3877. opts.platform = "DOS";
  3878. }
  3879. var comment = opts.comment || this.comment || "";
  3880. worker = generate.generateWorker(this, opts, comment);
  3881. } catch (e) {
  3882. worker = new GenericWorker("error");
  3883. worker.error(e);
  3884. }
  3885. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  3886. },
  3887. /**
  3888. * Generate the complete zip file asynchronously.
  3889. * @see generateInternalStream
  3890. */
  3891. generateAsync: function (options, onUpdate) {
  3892. return this.generateInternalStream(options).accumulate(onUpdate);
  3893. },
  3894. /**
  3895. * Generate the complete zip file asynchronously.
  3896. * @see generateInternalStream
  3897. */
  3898. generateNodeStream: function (options, onUpdate) {
  3899. options = options || {};
  3900. if (!options.type) {
  3901. options.type = "nodebuffer";
  3902. }
  3903. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  3904. }
  3905. };
  3906. module.exports = out;
  3907. }, { "./compressedObject": 12, "./defaults": 15, "./generate": 19, "./nodejs/NodejsStreamInputAdapter": 23, "./nodejsUtils": 22, "./stream/GenericWorker": 38, "./stream/StreamHelper": 39, "./utf8": 41, "./utils": 42, "./zipObject": 45 }], 26: [function (require, module, exports) {
  3908. /*
  3909. * This file is used by module bundlers (browserify/webpack/etc) when
  3910. * including a stream implementation. We use "readable-stream" to get a
  3911. * consistent behavior between nodejs versions but bundlers often have a shim
  3912. * for "stream". Using this shim greatly improve the compatibility and greatly
  3913. * reduce the final size of the bundle (only one stream implementation, not
  3914. * two).
  3915. */
  3916. module.exports = require("stream");
  3917. }, { "stream": 80 }], 27: [function (require, module, exports) {
  3918. 'use strict';
  3919. var DataReader = require('./DataReader');
  3920. var utils = require('../utils');
  3921. function ArrayReader(data) {
  3922. DataReader.call(this, data);
  3923. for (var i = 0; i < this.data.length; i++) {
  3924. data[i] = data[i] & 0xFF;
  3925. }
  3926. }
  3927. utils.inherits(ArrayReader, DataReader);
  3928. /**
  3929. * @see DataReader.byteAt
  3930. */
  3931. ArrayReader.prototype.byteAt = function (i) {
  3932. return this.data[this.zero + i];
  3933. };
  3934. /**
  3935. * @see DataReader.lastIndexOfSignature
  3936. */
  3937. ArrayReader.prototype.lastIndexOfSignature = function (sig) {
  3938. var sig0 = sig.charCodeAt(0),
  3939. sig1 = sig.charCodeAt(1),
  3940. sig2 = sig.charCodeAt(2),
  3941. sig3 = sig.charCodeAt(3);
  3942. for (var i = this.length - 4; i >= 0; --i) {
  3943. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  3944. return i - this.zero;
  3945. }
  3946. }
  3947. return -1;
  3948. };
  3949. /**
  3950. * @see DataReader.readAndCheckSignature
  3951. */
  3952. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  3953. var sig0 = sig.charCodeAt(0),
  3954. sig1 = sig.charCodeAt(1),
  3955. sig2 = sig.charCodeAt(2),
  3956. sig3 = sig.charCodeAt(3),
  3957. data = this.readData(4);
  3958. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  3959. };
  3960. /**
  3961. * @see DataReader.readData
  3962. */
  3963. ArrayReader.prototype.readData = function (size) {
  3964. this.checkOffset(size);
  3965. if (size === 0) {
  3966. return [];
  3967. }
  3968. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3969. this.index += size;
  3970. return result;
  3971. };
  3972. module.exports = ArrayReader;
  3973. }, { "../utils": 42, "./DataReader": 28 }], 28: [function (require, module, exports) {
  3974. 'use strict';
  3975. var utils = require('../utils');
  3976. function DataReader(data) {
  3977. this.data = data; // type : see implementation
  3978. this.length = data.length;
  3979. this.index = 0;
  3980. this.zero = 0;
  3981. }
  3982. DataReader.prototype = {
  3983. /**
  3984. * Check that the offset will not go too far.
  3985. * @param {string} offset the additional offset to check.
  3986. * @throws {Error} an Error if the offset is out of bounds.
  3987. */
  3988. checkOffset: function (offset) {
  3989. this.checkIndex(this.index + offset);
  3990. },
  3991. /**
  3992. * Check that the specified index will not be too far.
  3993. * @param {string} newIndex the index to check.
  3994. * @throws {Error} an Error if the index is out of bounds.
  3995. */
  3996. checkIndex: function (newIndex) {
  3997. if (this.length < this.zero + newIndex || newIndex < 0) {
  3998. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  3999. }
  4000. },
  4001. /**
  4002. * Change the index.
  4003. * @param {number} newIndex The new index.
  4004. * @throws {Error} if the new index is out of the data.
  4005. */
  4006. setIndex: function (newIndex) {
  4007. this.checkIndex(newIndex);
  4008. this.index = newIndex;
  4009. },
  4010. /**
  4011. * Skip the next n bytes.
  4012. * @param {number} n the number of bytes to skip.
  4013. * @throws {Error} if the new index is out of the data.
  4014. */
  4015. skip: function (n) {
  4016. this.setIndex(this.index + n);
  4017. },
  4018. /**
  4019. * Get the byte at the specified index.
  4020. * @param {number} i the index to use.
  4021. * @return {number} a byte.
  4022. */
  4023. byteAt: function (i) {
  4024. // see implementations
  4025. },
  4026. /**
  4027. * Get the next number with a given byte size.
  4028. * @param {number} size the number of bytes to read.
  4029. * @return {number} the corresponding number.
  4030. */
  4031. readInt: function (size) {
  4032. var result = 0,
  4033. i;
  4034. this.checkOffset(size);
  4035. for (i = this.index + size - 1; i >= this.index; i--) {
  4036. result = (result << 8) + this.byteAt(i);
  4037. }
  4038. this.index += size;
  4039. return result;
  4040. },
  4041. /**
  4042. * Get the next string with a given byte size.
  4043. * @param {number} size the number of bytes to read.
  4044. * @return {string} the corresponding string.
  4045. */
  4046. readString: function (size) {
  4047. return utils.transformTo("string", this.readData(size));
  4048. },
  4049. /**
  4050. * Get raw data without conversion, <size> bytes.
  4051. * @param {number} size the number of bytes to read.
  4052. * @return {Object} the raw data, implementation specific.
  4053. */
  4054. readData: function (size) {
  4055. // see implementations
  4056. },
  4057. /**
  4058. * Find the last occurrence of a zip signature (4 bytes).
  4059. * @param {string} sig the signature to find.
  4060. * @return {number} the index of the last occurrence, -1 if not found.
  4061. */
  4062. lastIndexOfSignature: function (sig) {
  4063. // see implementations
  4064. },
  4065. /**
  4066. * Read the signature (4 bytes) at the current position and compare it with sig.
  4067. * @param {string} sig the expected signature
  4068. * @return {boolean} true if the signature matches, false otherwise.
  4069. */
  4070. readAndCheckSignature: function (sig) {
  4071. // see implementations
  4072. },
  4073. /**
  4074. * Get the next date.
  4075. * @return {Date} the date.
  4076. */
  4077. readDate: function () {
  4078. var dostime = this.readInt(4);
  4079. return new Date(Date.UTC(
  4080. ((dostime >> 25) & 0x7f) + 1980, // year
  4081. ((dostime >> 21) & 0x0f) - 1, // month
  4082. (dostime >> 16) & 0x1f, // day
  4083. (dostime >> 11) & 0x1f, // hour
  4084. (dostime >> 5) & 0x3f, // minute
  4085. (dostime & 0x1f) << 1)); // second
  4086. }
  4087. };
  4088. module.exports = DataReader;
  4089. }, { "../utils": 42 }], 29: [function (require, module, exports) {
  4090. 'use strict';
  4091. var Uint8ArrayReader = require('./Uint8ArrayReader');
  4092. var utils = require('../utils');
  4093. function NodeBufferReader(data) {
  4094. Uint8ArrayReader.call(this, data);
  4095. }
  4096. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  4097. /**
  4098. * @see DataReader.readData
  4099. */
  4100. NodeBufferReader.prototype.readData = function (size) {
  4101. this.checkOffset(size);
  4102. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  4103. this.index += size;
  4104. return result;
  4105. };
  4106. module.exports = NodeBufferReader;
  4107. }, { "../utils": 42, "./Uint8ArrayReader": 31 }], 30: [function (require, module, exports) {
  4108. 'use strict';
  4109. var DataReader = require('./DataReader');
  4110. var utils = require('../utils');
  4111. function StringReader(data) {
  4112. DataReader.call(this, data);
  4113. }
  4114. utils.inherits(StringReader, DataReader);
  4115. /**
  4116. * @see DataReader.byteAt
  4117. */
  4118. StringReader.prototype.byteAt = function (i) {
  4119. return this.data.charCodeAt(this.zero + i);
  4120. };
  4121. /**
  4122. * @see DataReader.lastIndexOfSignature
  4123. */
  4124. StringReader.prototype.lastIndexOfSignature = function (sig) {
  4125. return this.data.lastIndexOf(sig) - this.zero;
  4126. };
  4127. /**
  4128. * @see DataReader.readAndCheckSignature
  4129. */
  4130. StringReader.prototype.readAndCheckSignature = function (sig) {
  4131. var data = this.readData(4);
  4132. return sig === data;
  4133. };
  4134. /**
  4135. * @see DataReader.readData
  4136. */
  4137. StringReader.prototype.readData = function (size) {
  4138. this.checkOffset(size);
  4139. // this will work because the constructor applied the "& 0xff" mask.
  4140. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  4141. this.index += size;
  4142. return result;
  4143. };
  4144. module.exports = StringReader;
  4145. }, { "../utils": 42, "./DataReader": 28 }], 31: [function (require, module, exports) {
  4146. 'use strict';
  4147. var ArrayReader = require('./ArrayReader');
  4148. var utils = require('../utils');
  4149. function Uint8ArrayReader(data) {
  4150. ArrayReader.call(this, data);
  4151. }
  4152. utils.inherits(Uint8ArrayReader, ArrayReader);
  4153. /**
  4154. * @see DataReader.readData
  4155. */
  4156. Uint8ArrayReader.prototype.readData = function (size) {
  4157. this.checkOffset(size);
  4158. if (size === 0) {
  4159. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  4160. return new Uint8Array(0);
  4161. }
  4162. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  4163. this.index += size;
  4164. return result;
  4165. };
  4166. module.exports = Uint8ArrayReader;
  4167. }, { "../utils": 42, "./ArrayReader": 27 }], 32: [function (require, module, exports) {
  4168. 'use strict';
  4169. var utils = require('../utils');
  4170. var support = require('../support');
  4171. var ArrayReader = require('./ArrayReader');
  4172. var StringReader = require('./StringReader');
  4173. var NodeBufferReader = require('./NodeBufferReader');
  4174. var Uint8ArrayReader = require('./Uint8ArrayReader');
  4175. /**
  4176. * Create a reader adapted to the data.
  4177. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  4178. * @return {DataReader} the data reader.
  4179. */
  4180. module.exports = function (data) {
  4181. var type = utils.getTypeOf(data);
  4182. utils.checkSupport(type);
  4183. if (type === "string" && !support.uint8array) {
  4184. return new StringReader(data);
  4185. }
  4186. if (type === "nodebuffer") {
  4187. return new NodeBufferReader(data);
  4188. }
  4189. if (support.uint8array) {
  4190. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  4191. }
  4192. return new ArrayReader(utils.transformTo("array", data));
  4193. };
  4194. }, { "../support": 40, "../utils": 42, "./ArrayReader": 27, "./NodeBufferReader": 29, "./StringReader": 30, "./Uint8ArrayReader": 31 }], 33: [function (require, module, exports) {
  4195. 'use strict';
  4196. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  4197. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  4198. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  4199. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  4200. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  4201. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  4202. }, {}], 34: [function (require, module, exports) {
  4203. 'use strict';
  4204. var GenericWorker = require('./GenericWorker');
  4205. var utils = require('../utils');
  4206. /**
  4207. * A worker which convert chunks to a specified type.
  4208. * @constructor
  4209. * @param {String} destType the destination type.
  4210. */
  4211. function ConvertWorker(destType) {
  4212. GenericWorker.call(this, "ConvertWorker to " + destType);
  4213. this.destType = destType;
  4214. }
  4215. utils.inherits(ConvertWorker, GenericWorker);
  4216. /**
  4217. * @see GenericWorker.processChunk
  4218. */
  4219. ConvertWorker.prototype.processChunk = function (chunk) {
  4220. this.push({
  4221. data: utils.transformTo(this.destType, chunk.data),
  4222. meta: chunk.meta
  4223. });
  4224. };
  4225. module.exports = ConvertWorker;
  4226. }, { "../utils": 42, "./GenericWorker": 38 }], 35: [function (require, module, exports) {
  4227. 'use strict';
  4228. var GenericWorker = require('./GenericWorker');
  4229. var crc32 = require('../crc32');
  4230. var utils = require('../utils');
  4231. /**
  4232. * A worker which calculate the crc32 of the data flowing through.
  4233. * @constructor
  4234. */
  4235. function Crc32Probe() {
  4236. GenericWorker.call(this, "Crc32Probe");
  4237. this.withStreamInfo("crc32", 0);
  4238. }
  4239. utils.inherits(Crc32Probe, GenericWorker);
  4240. /**
  4241. * @see GenericWorker.processChunk
  4242. */
  4243. Crc32Probe.prototype.processChunk = function (chunk) {
  4244. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  4245. this.push(chunk);
  4246. };
  4247. module.exports = Crc32Probe;
  4248. }, { "../crc32": 14, "../utils": 42, "./GenericWorker": 38 }], 36: [function (require, module, exports) {
  4249. 'use strict';
  4250. var utils = require('../utils');
  4251. var GenericWorker = require('./GenericWorker');
  4252. /**
  4253. * A worker which calculate the total length of the data flowing through.
  4254. * @constructor
  4255. * @param {String} propName the name used to expose the length
  4256. */
  4257. function DataLengthProbe(propName) {
  4258. GenericWorker.call(this, "DataLengthProbe for " + propName);
  4259. this.propName = propName;
  4260. this.withStreamInfo(propName, 0);
  4261. }
  4262. utils.inherits(DataLengthProbe, GenericWorker);
  4263. /**
  4264. * @see GenericWorker.processChunk
  4265. */
  4266. DataLengthProbe.prototype.processChunk = function (chunk) {
  4267. if (chunk) {
  4268. var length = this.streamInfo[this.propName] || 0;
  4269. this.streamInfo[this.propName] = length + chunk.data.length;
  4270. }
  4271. GenericWorker.prototype.processChunk.call(this, chunk);
  4272. };
  4273. module.exports = DataLengthProbe;
  4274. }, { "../utils": 42, "./GenericWorker": 38 }], 37: [function (require, module, exports) {
  4275. 'use strict';
  4276. var utils = require('../utils');
  4277. var GenericWorker = require('./GenericWorker');
  4278. // the size of the generated chunks
  4279. // TODO expose this as a public variable
  4280. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  4281. /**
  4282. * A worker that reads a content and emits chunks.
  4283. * @constructor
  4284. * @param {Promise} dataP the promise of the data to split
  4285. */
  4286. function DataWorker(dataP) {
  4287. GenericWorker.call(this, "DataWorker");
  4288. var self = this;
  4289. this.dataIsReady = false;
  4290. this.index = 0;
  4291. this.max = 0;
  4292. this.data = null;
  4293. this.type = "";
  4294. this._tickScheduled = false;
  4295. dataP.then(function (data) {
  4296. self.dataIsReady = true;
  4297. self.data = data;
  4298. self.max = data && data.length || 0;
  4299. self.type = utils.getTypeOf(data);
  4300. if (!self.isPaused) {
  4301. self._tickAndRepeat();
  4302. }
  4303. }, function (e) {
  4304. self.error(e);
  4305. });
  4306. }
  4307. utils.inherits(DataWorker, GenericWorker);
  4308. /**
  4309. * @see GenericWorker.cleanUp
  4310. */
  4311. DataWorker.prototype.cleanUp = function () {
  4312. GenericWorker.prototype.cleanUp.call(this);
  4313. this.data = null;
  4314. };
  4315. /**
  4316. * @see GenericWorker.resume
  4317. */
  4318. DataWorker.prototype.resume = function () {
  4319. if (!GenericWorker.prototype.resume.call(this)) {
  4320. return false;
  4321. }
  4322. if (!this._tickScheduled && this.dataIsReady) {
  4323. this._tickScheduled = true;
  4324. utils.delay(this._tickAndRepeat, [], this);
  4325. }
  4326. return true;
  4327. };
  4328. /**
  4329. * Trigger a tick a schedule an other call to this function.
  4330. */
  4331. DataWorker.prototype._tickAndRepeat = function () {
  4332. this._tickScheduled = false;
  4333. if (this.isPaused || this.isFinished) {
  4334. return;
  4335. }
  4336. this._tick();
  4337. if (!this.isFinished) {
  4338. utils.delay(this._tickAndRepeat, [], this);
  4339. this._tickScheduled = true;
  4340. }
  4341. };
  4342. /**
  4343. * Read and push a chunk.
  4344. */
  4345. DataWorker.prototype._tick = function () {
  4346. if (this.isPaused || this.isFinished) {
  4347. return false;
  4348. }
  4349. var size = DEFAULT_BLOCK_SIZE;
  4350. var data = null, nextIndex = Math.min(this.max, this.index + size);
  4351. if (this.index >= this.max) {
  4352. // EOF
  4353. return this.end();
  4354. } else {
  4355. switch (this.type) {
  4356. case "string":
  4357. data = this.data.substring(this.index, nextIndex);
  4358. break;
  4359. case "uint8array":
  4360. data = this.data.subarray(this.index, nextIndex);
  4361. break;
  4362. case "array":
  4363. case "nodebuffer":
  4364. data = this.data.slice(this.index, nextIndex);
  4365. break;
  4366. }
  4367. this.index = nextIndex;
  4368. return this.push({
  4369. data: data,
  4370. meta: {
  4371. percent: this.max ? this.index / this.max * 100 : 0
  4372. }
  4373. });
  4374. }
  4375. };
  4376. module.exports = DataWorker;
  4377. }, { "../utils": 42, "./GenericWorker": 38 }], 38: [function (require, module, exports) {
  4378. 'use strict';
  4379. /**
  4380. * A worker that does nothing but passing chunks to the next one. This is like
  4381. * a nodejs stream but with some differences. On the good side :
  4382. * - it works on IE 6-9 without any issue / polyfill
  4383. * - it weights less than the full dependencies bundled with browserify
  4384. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  4385. *
  4386. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  4387. * object containing anything (`percent` for example), see each worker for more
  4388. * details. The latter is the real data (String, Uint8Array, etc).
  4389. *
  4390. * @constructor
  4391. * @param {String} name the name of the stream (mainly used for debugging purposes)
  4392. */
  4393. function GenericWorker(name) {
  4394. // the name of the worker
  4395. this.name = name || "default";
  4396. // an object containing metadata about the workers chain
  4397. this.streamInfo = {};
  4398. // an error which happened when the worker was paused
  4399. this.generatedError = null;
  4400. // an object containing metadata to be merged by this worker into the general metadata
  4401. this.extraStreamInfo = {};
  4402. // true if the stream is paused (and should not do anything), false otherwise
  4403. this.isPaused = true;
  4404. // true if the stream is finished (and should not do anything), false otherwise
  4405. this.isFinished = false;
  4406. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  4407. this.isLocked = false;
  4408. // the event listeners
  4409. this._listeners = {
  4410. 'data': [],
  4411. 'end': [],
  4412. 'error': []
  4413. };
  4414. // the previous worker, if any
  4415. this.previous = null;
  4416. }
  4417. GenericWorker.prototype = {
  4418. /**
  4419. * Push a chunk to the next workers.
  4420. * @param {Object} chunk the chunk to push
  4421. */
  4422. push: function (chunk) {
  4423. this.emit("data", chunk);
  4424. },
  4425. /**
  4426. * End the stream.
  4427. * @return {Boolean} true if this call ended the worker, false otherwise.
  4428. */
  4429. end: function () {
  4430. if (this.isFinished) {
  4431. return false;
  4432. }
  4433. this.flush();
  4434. try {
  4435. this.emit("end");
  4436. this.cleanUp();
  4437. this.isFinished = true;
  4438. } catch (e) {
  4439. this.emit("error", e);
  4440. }
  4441. return true;
  4442. },
  4443. /**
  4444. * End the stream with an error.
  4445. * @param {Error} e the error which caused the premature end.
  4446. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  4447. */
  4448. error: function (e) {
  4449. if (this.isFinished) {
  4450. return false;
  4451. }
  4452. if (this.isPaused) {
  4453. this.generatedError = e;
  4454. } else {
  4455. this.isFinished = true;
  4456. this.emit("error", e);
  4457. // in the workers chain exploded in the middle of the chain,
  4458. // the error event will go downward but we also need to notify
  4459. // workers upward that there has been an error.
  4460. if (this.previous) {
  4461. this.previous.error(e);
  4462. }
  4463. this.cleanUp();
  4464. }
  4465. return true;
  4466. },
  4467. /**
  4468. * Add a callback on an event.
  4469. * @param {String} name the name of the event (data, end, error)
  4470. * @param {Function} listener the function to call when the event is triggered
  4471. * @return {GenericWorker} the current object for chainability
  4472. */
  4473. on: function (name, listener) {
  4474. this._listeners[name].push(listener);
  4475. return this;
  4476. },
  4477. /**
  4478. * Clean any references when a worker is ending.
  4479. */
  4480. cleanUp: function () {
  4481. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  4482. this._listeners = [];
  4483. },
  4484. /**
  4485. * Trigger an event. This will call registered callback with the provided arg.
  4486. * @param {String} name the name of the event (data, end, error)
  4487. * @param {Object} arg the argument to call the callback with.
  4488. */
  4489. emit: function (name, arg) {
  4490. if (this._listeners[name]) {
  4491. for (var i = 0; i < this._listeners[name].length; i++) {
  4492. this._listeners[name][i].call(this, arg);
  4493. }
  4494. }
  4495. },
  4496. /**
  4497. * Chain a worker with an other.
  4498. * @param {Worker} next the worker receiving events from the current one.
  4499. * @return {worker} the next worker for chainability
  4500. */
  4501. pipe: function (next) {
  4502. return next.registerPrevious(this);
  4503. },
  4504. /**
  4505. * Same as `pipe` in the other direction.
  4506. * Using an API with `pipe(next)` is very easy.
  4507. * Implementing the API with the point of view of the next one registering
  4508. * a source is easier, see the ZipFileWorker.
  4509. * @param {Worker} previous the previous worker, sending events to this one
  4510. * @return {Worker} the current worker for chainability
  4511. */
  4512. registerPrevious: function (previous) {
  4513. if (this.isLocked) {
  4514. throw new Error("The stream '" + this + "' has already been used.");
  4515. }
  4516. // sharing the streamInfo...
  4517. this.streamInfo = previous.streamInfo;
  4518. // ... and adding our own bits
  4519. this.mergeStreamInfo();
  4520. this.previous = previous;
  4521. var self = this;
  4522. previous.on('data', function (chunk) {
  4523. self.processChunk(chunk);
  4524. });
  4525. previous.on('end', function () {
  4526. self.end();
  4527. });
  4528. previous.on('error', function (e) {
  4529. self.error(e);
  4530. });
  4531. return this;
  4532. },
  4533. /**
  4534. * Pause the stream so it doesn't send events anymore.
  4535. * @return {Boolean} true if this call paused the worker, false otherwise.
  4536. */
  4537. pause: function () {
  4538. if (this.isPaused || this.isFinished) {
  4539. return false;
  4540. }
  4541. this.isPaused = true;
  4542. if (this.previous) {
  4543. this.previous.pause();
  4544. }
  4545. return true;
  4546. },
  4547. /**
  4548. * Resume a paused stream.
  4549. * @return {Boolean} true if this call resumed the worker, false otherwise.
  4550. */
  4551. resume: function () {
  4552. if (!this.isPaused || this.isFinished) {
  4553. return false;
  4554. }
  4555. this.isPaused = false;
  4556. // if true, the worker tried to resume but failed
  4557. var withError = false;
  4558. if (this.generatedError) {
  4559. this.error(this.generatedError);
  4560. withError = true;
  4561. }
  4562. if (this.previous) {
  4563. this.previous.resume();
  4564. }
  4565. return !withError;
  4566. },
  4567. /**
  4568. * Flush any remaining bytes as the stream is ending.
  4569. */
  4570. flush: function () { },
  4571. /**
  4572. * Process a chunk. This is usually the method overridden.
  4573. * @param {Object} chunk the chunk to process.
  4574. */
  4575. processChunk: function (chunk) {
  4576. this.push(chunk);
  4577. },
  4578. /**
  4579. * Add a key/value to be added in the workers chain streamInfo once activated.
  4580. * @param {String} key the key to use
  4581. * @param {Object} value the associated value
  4582. * @return {Worker} the current worker for chainability
  4583. */
  4584. withStreamInfo: function (key, value) {
  4585. this.extraStreamInfo[key] = value;
  4586. this.mergeStreamInfo();
  4587. return this;
  4588. },
  4589. /**
  4590. * Merge this worker's streamInfo into the chain's streamInfo.
  4591. */
  4592. mergeStreamInfo: function () {
  4593. for (var key in this.extraStreamInfo) {
  4594. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  4595. continue;
  4596. }
  4597. this.streamInfo[key] = this.extraStreamInfo[key];
  4598. }
  4599. },
  4600. /**
  4601. * Lock the stream to prevent further updates on the workers chain.
  4602. * After calling this method, all calls to pipe will fail.
  4603. */
  4604. lock: function () {
  4605. if (this.isLocked) {
  4606. throw new Error("The stream '" + this + "' has already been used.");
  4607. }
  4608. this.isLocked = true;
  4609. if (this.previous) {
  4610. this.previous.lock();
  4611. }
  4612. },
  4613. /**
  4614. *
  4615. * Pretty print the workers chain.
  4616. */
  4617. toString: function () {
  4618. var me = "Worker " + this.name;
  4619. if (this.previous) {
  4620. return this.previous + " -> " + me;
  4621. } else {
  4622. return me;
  4623. }
  4624. }
  4625. };
  4626. module.exports = GenericWorker;
  4627. }, {}], 39: [function (require, module, exports) {
  4628. (function (Buffer) {
  4629. 'use strict';
  4630. var utils = require('../utils');
  4631. var ConvertWorker = require('./ConvertWorker');
  4632. var GenericWorker = require('./GenericWorker');
  4633. var base64 = require('../base64');
  4634. var support = require("../support");
  4635. var external = require("../external");
  4636. var NodejsStreamOutputAdapter = null;
  4637. if (support.nodestream) {
  4638. try {
  4639. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  4640. } catch (e) { }
  4641. }
  4642. /**
  4643. * Apply the final transformation of the data. If the user wants a Blob for
  4644. * example, it's easier to work with an U8intArray and finally do the
  4645. * ArrayBuffer/Blob conversion.
  4646. * @param {String} type the name of the final type
  4647. * @param {String|Uint8Array|Buffer} content the content to transform
  4648. * @param {String} mimeType the mime type of the content, if applicable.
  4649. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  4650. */
  4651. function transformZipOutput(type, content, mimeType) {
  4652. switch (type) {
  4653. case "blob":
  4654. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  4655. case "base64":
  4656. return base64.encode(content);
  4657. default:
  4658. return utils.transformTo(type, content);
  4659. }
  4660. }
  4661. /**
  4662. * Concatenate an array of data of the given type.
  4663. * @param {String} type the type of the data in the given array.
  4664. * @param {Array} dataArray the array containing the data chunks to concatenate
  4665. * @return {String|Uint8Array|Buffer} the concatenated data
  4666. * @throws Error if the asked type is unsupported
  4667. */
  4668. function concat(type, dataArray) {
  4669. var i, index = 0, res = null, totalLength = 0;
  4670. for (i = 0; i < dataArray.length; i++) {
  4671. totalLength += dataArray[i].length;
  4672. }
  4673. switch (type) {
  4674. case "string":
  4675. return dataArray.join("");
  4676. case "array":
  4677. return Array.prototype.concat.apply([], dataArray);
  4678. case "uint8array":
  4679. res = new Uint8Array(totalLength);
  4680. for (i = 0; i < dataArray.length; i++) {
  4681. res.set(dataArray[i], index);
  4682. index += dataArray[i].length;
  4683. }
  4684. return res;
  4685. case "nodebuffer":
  4686. return Buffer.concat(dataArray);
  4687. default:
  4688. throw new Error("concat : unsupported type '" + type + "'");
  4689. }
  4690. }
  4691. /**
  4692. * Listen a StreamHelper, accumulate its content and concatenate it into a
  4693. * complete block.
  4694. * @param {StreamHelper} helper the helper to use.
  4695. * @param {Function} updateCallback a callback called on each update. Called
  4696. * with one arg :
  4697. * - the metadata linked to the update received.
  4698. * @return Promise the promise for the accumulation.
  4699. */
  4700. function accumulate(helper, updateCallback) {
  4701. return new external.Promise(function (resolve, reject) {
  4702. var dataArray = [];
  4703. var chunkType = helper._internalType,
  4704. resultType = helper._outputType,
  4705. mimeType = helper._mimeType;
  4706. helper
  4707. .on('data', function (data, meta) {
  4708. dataArray.push(data);
  4709. if (updateCallback) {
  4710. updateCallback(meta);
  4711. }
  4712. })
  4713. .on('error', function (err) {
  4714. dataArray = [];
  4715. reject(err);
  4716. })
  4717. .on('end', function () {
  4718. try {
  4719. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  4720. resolve(result);
  4721. } catch (e) {
  4722. reject(e);
  4723. }
  4724. dataArray = [];
  4725. })
  4726. .resume();
  4727. });
  4728. }
  4729. /**
  4730. * An helper to easily use workers outside of JSZip.
  4731. * @constructor
  4732. * @param {Worker} worker the worker to wrap
  4733. * @param {String} outputType the type of data expected by the use
  4734. * @param {String} mimeType the mime type of the content, if applicable.
  4735. */
  4736. function StreamHelper(worker, outputType, mimeType) {
  4737. var internalType = outputType;
  4738. switch (outputType) {
  4739. case "blob":
  4740. case "arraybuffer":
  4741. internalType = "uint8array";
  4742. break;
  4743. case "base64":
  4744. internalType = "string";
  4745. break;
  4746. }
  4747. try {
  4748. // the type used internally
  4749. this._internalType = internalType;
  4750. // the type used to output results
  4751. this._outputType = outputType;
  4752. // the mime type
  4753. this._mimeType = mimeType;
  4754. utils.checkSupport(internalType);
  4755. this._worker = worker.pipe(new ConvertWorker(internalType));
  4756. // the last workers can be rewired without issues but we need to
  4757. // prevent any updates on previous workers.
  4758. worker.lock();
  4759. } catch (e) {
  4760. this._worker = new GenericWorker("error");
  4761. this._worker.error(e);
  4762. }
  4763. }
  4764. StreamHelper.prototype = {
  4765. /**
  4766. * Listen a StreamHelper, accumulate its content and concatenate it into a
  4767. * complete block.
  4768. * @param {Function} updateCb the update callback.
  4769. * @return Promise the promise for the accumulation.
  4770. */
  4771. accumulate: function (updateCb) {
  4772. return accumulate(this, updateCb);
  4773. },
  4774. /**
  4775. * Add a listener on an event triggered on a stream.
  4776. * @param {String} evt the name of the event
  4777. * @param {Function} fn the listener
  4778. * @return {StreamHelper} the current helper.
  4779. */
  4780. on: function (evt, fn) {
  4781. var self = this;
  4782. if (evt === "data") {
  4783. this._worker.on(evt, function (chunk) {
  4784. fn.call(self, chunk.data, chunk.meta);
  4785. });
  4786. } else {
  4787. this._worker.on(evt, function () {
  4788. utils.delay(fn, arguments, self);
  4789. });
  4790. }
  4791. return this;
  4792. },
  4793. /**
  4794. * Resume the flow of chunks.
  4795. * @return {StreamHelper} the current helper.
  4796. */
  4797. resume: function () {
  4798. utils.delay(this._worker.resume, [], this._worker);
  4799. return this;
  4800. },
  4801. /**
  4802. * Pause the flow of chunks.
  4803. * @return {StreamHelper} the current helper.
  4804. */
  4805. pause: function () {
  4806. this._worker.pause();
  4807. return this;
  4808. },
  4809. /**
  4810. * Return a nodejs stream for this helper.
  4811. * @param {Function} updateCb the update callback.
  4812. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  4813. */
  4814. toNodejsStream: function (updateCb) {
  4815. utils.checkSupport("nodestream");
  4816. if (this._outputType !== "nodebuffer") {
  4817. // an object stream containing blob/arraybuffer/uint8array/string
  4818. // is strange and I don't know if it would be useful.
  4819. // I you find this comment and have a good usecase, please open a
  4820. // bug report !
  4821. throw new Error(this._outputType + " is not supported by this method");
  4822. }
  4823. return new NodejsStreamOutputAdapter(this, {
  4824. objectMode: this._outputType !== "nodebuffer"
  4825. }, updateCb);
  4826. }
  4827. };
  4828. module.exports = StreamHelper;
  4829. }).call(this, require("buffer").Buffer)
  4830. }, { "../base64": 11, "../external": 16, "../nodejs/NodejsStreamOutputAdapter": 24, "../support": 40, "../utils": 42, "./ConvertWorker": 34, "./GenericWorker": 38, "buffer": 3 }], 40: [function (require, module, exports) {
  4831. (function (Buffer) {
  4832. 'use strict';
  4833. exports.base64 = true;
  4834. exports.array = true;
  4835. exports.string = true;
  4836. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  4837. exports.nodebuffer = typeof Buffer !== "undefined";
  4838. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  4839. exports.uint8array = typeof Uint8Array !== "undefined";
  4840. if (typeof ArrayBuffer === "undefined") {
  4841. exports.blob = false;
  4842. }
  4843. else {
  4844. var buffer = new ArrayBuffer(0);
  4845. try {
  4846. exports.blob = new Blob([buffer], {
  4847. type: "application/zip"
  4848. }).size === 0;
  4849. }
  4850. catch (e) {
  4851. try {
  4852. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  4853. var builder = new Builder();
  4854. builder.append(buffer);
  4855. exports.blob = builder.getBlob('application/zip').size === 0;
  4856. }
  4857. catch (e) {
  4858. exports.blob = false;
  4859. }
  4860. }
  4861. }
  4862. try {
  4863. exports.nodestream = !!require('readable-stream').Readable;
  4864. } catch (e) {
  4865. exports.nodestream = false;
  4866. }
  4867. }).call(this, require("buffer").Buffer)
  4868. }, { "buffer": 3, "readable-stream": 26 }], 41: [function (require, module, exports) {
  4869. 'use strict';
  4870. var utils = require('./utils');
  4871. var support = require('./support');
  4872. var nodejsUtils = require('./nodejsUtils');
  4873. var GenericWorker = require('./stream/GenericWorker');
  4874. /**
  4875. * The following functions come from pako, from pako/lib/utils/strings
  4876. * released under the MIT license, see pako https://github.com/nodeca/pako/
  4877. */
  4878. // Table with utf8 lengths (calculated by first byte of sequence)
  4879. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4880. // because max possible codepoint is 0x10ffff
  4881. var _utf8len = new Array(256);
  4882. for (var i = 0; i < 256; i++) {
  4883. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  4884. }
  4885. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  4886. // convert string to array (typed, when possible)
  4887. var string2buf = function (str) {
  4888. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4889. // count binary size
  4890. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4891. c = str.charCodeAt(m_pos);
  4892. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4893. c2 = str.charCodeAt(m_pos + 1);
  4894. if ((c2 & 0xfc00) === 0xdc00) {
  4895. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4896. m_pos++;
  4897. }
  4898. }
  4899. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4900. }
  4901. // allocate buffer
  4902. if (support.uint8array) {
  4903. buf = new Uint8Array(buf_len);
  4904. } else {
  4905. buf = new Array(buf_len);
  4906. }
  4907. // convert
  4908. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  4909. c = str.charCodeAt(m_pos);
  4910. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4911. c2 = str.charCodeAt(m_pos + 1);
  4912. if ((c2 & 0xfc00) === 0xdc00) {
  4913. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4914. m_pos++;
  4915. }
  4916. }
  4917. if (c < 0x80) {
  4918. /* one byte */
  4919. buf[i++] = c;
  4920. } else if (c < 0x800) {
  4921. /* two bytes */
  4922. buf[i++] = 0xC0 | (c >>> 6);
  4923. buf[i++] = 0x80 | (c & 0x3f);
  4924. } else if (c < 0x10000) {
  4925. /* three bytes */
  4926. buf[i++] = 0xE0 | (c >>> 12);
  4927. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4928. buf[i++] = 0x80 | (c & 0x3f);
  4929. } else {
  4930. /* four bytes */
  4931. buf[i++] = 0xf0 | (c >>> 18);
  4932. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  4933. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4934. buf[i++] = 0x80 | (c & 0x3f);
  4935. }
  4936. }
  4937. return buf;
  4938. };
  4939. // Calculate max possible position in utf8 buffer,
  4940. // that will not break sequence. If that's not possible
  4941. // - (very small limits) return max size as is.
  4942. //
  4943. // buf[] - utf8 bytes array
  4944. // max - length limit (mandatory);
  4945. var utf8border = function (buf, max) {
  4946. var pos;
  4947. max = max || buf.length;
  4948. if (max > buf.length) { max = buf.length; }
  4949. // go back from last position, until start of sequence found
  4950. pos = max - 1;
  4951. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  4952. // Fuckup - very small and broken sequence,
  4953. // return max, because we should return something anyway.
  4954. if (pos < 0) { return max; }
  4955. // If we came to start of buffer - that means vuffer is too small,
  4956. // return max too.
  4957. if (pos === 0) { return max; }
  4958. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  4959. };
  4960. // convert array to string
  4961. var buf2string = function (buf) {
  4962. var str, i, out, c, c_len;
  4963. var len = buf.length;
  4964. // Reserve max possible length (2 words per char)
  4965. // NB: by unknown reasons, Array is significantly faster for
  4966. // String.fromCharCode.apply than Uint16Array.
  4967. var utf16buf = new Array(len * 2);
  4968. for (out = 0, i = 0; i < len;) {
  4969. c = buf[i++];
  4970. // quick process ascii
  4971. if (c < 0x80) { utf16buf[out++] = c; continue; }
  4972. c_len = _utf8len[c];
  4973. // skip 5 & 6 byte codes
  4974. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  4975. // apply mask on first byte
  4976. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  4977. // join the rest
  4978. while (c_len > 1 && i < len) {
  4979. c = (c << 6) | (buf[i++] & 0x3f);
  4980. c_len--;
  4981. }
  4982. // terminated by end of string?
  4983. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  4984. if (c < 0x10000) {
  4985. utf16buf[out++] = c;
  4986. } else {
  4987. c -= 0x10000;
  4988. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  4989. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  4990. }
  4991. }
  4992. // shrinkBuf(utf16buf, out)
  4993. if (utf16buf.length !== out) {
  4994. if (utf16buf.subarray) {
  4995. utf16buf = utf16buf.subarray(0, out);
  4996. } else {
  4997. utf16buf.length = out;
  4998. }
  4999. }
  5000. // return String.fromCharCode.apply(null, utf16buf);
  5001. return utils.applyFromCharCode(utf16buf);
  5002. };
  5003. // That's all for the pako functions.
  5004. /**
  5005. * Transform a javascript string into an array (typed if possible) of bytes,
  5006. * UTF-8 encoded.
  5007. * @param {String} str the string to encode
  5008. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  5009. */
  5010. exports.utf8encode = function utf8encode(str) {
  5011. if (support.nodebuffer) {
  5012. return nodejsUtils.newBufferFrom(str, "utf-8");
  5013. }
  5014. return string2buf(str);
  5015. };
  5016. /**
  5017. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  5018. * string into a javascript string.
  5019. * @param {Array|Uint8Array|Buffer} buf the data de decode
  5020. * @return {String} the decoded string.
  5021. */
  5022. exports.utf8decode = function utf8decode(buf) {
  5023. if (support.nodebuffer) {
  5024. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  5025. }
  5026. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  5027. return buf2string(buf);
  5028. };
  5029. /**
  5030. * A worker to decode utf8 encoded binary chunks into string chunks.
  5031. * @constructor
  5032. */
  5033. function Utf8DecodeWorker() {
  5034. GenericWorker.call(this, "utf-8 decode");
  5035. // the last bytes if a chunk didn't end with a complete codepoint.
  5036. this.leftOver = null;
  5037. }
  5038. utils.inherits(Utf8DecodeWorker, GenericWorker);
  5039. /**
  5040. * @see GenericWorker.processChunk
  5041. */
  5042. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  5043. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  5044. // 1st step, re-use what's left of the previous chunk
  5045. if (this.leftOver && this.leftOver.length) {
  5046. if (support.uint8array) {
  5047. var previousData = data;
  5048. data = new Uint8Array(previousData.length + this.leftOver.length);
  5049. data.set(this.leftOver, 0);
  5050. data.set(previousData, this.leftOver.length);
  5051. } else {
  5052. data = this.leftOver.concat(data);
  5053. }
  5054. this.leftOver = null;
  5055. }
  5056. var nextBoundary = utf8border(data);
  5057. var usableData = data;
  5058. if (nextBoundary !== data.length) {
  5059. if (support.uint8array) {
  5060. usableData = data.subarray(0, nextBoundary);
  5061. this.leftOver = data.subarray(nextBoundary, data.length);
  5062. } else {
  5063. usableData = data.slice(0, nextBoundary);
  5064. this.leftOver = data.slice(nextBoundary, data.length);
  5065. }
  5066. }
  5067. this.push({
  5068. data: exports.utf8decode(usableData),
  5069. meta: chunk.meta
  5070. });
  5071. };
  5072. /**
  5073. * @see GenericWorker.flush
  5074. */
  5075. Utf8DecodeWorker.prototype.flush = function () {
  5076. if (this.leftOver && this.leftOver.length) {
  5077. this.push({
  5078. data: exports.utf8decode(this.leftOver),
  5079. meta: {}
  5080. });
  5081. this.leftOver = null;
  5082. }
  5083. };
  5084. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  5085. /**
  5086. * A worker to endcode string chunks into utf8 encoded binary chunks.
  5087. * @constructor
  5088. */
  5089. function Utf8EncodeWorker() {
  5090. GenericWorker.call(this, "utf-8 encode");
  5091. }
  5092. utils.inherits(Utf8EncodeWorker, GenericWorker);
  5093. /**
  5094. * @see GenericWorker.processChunk
  5095. */
  5096. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  5097. this.push({
  5098. data: exports.utf8encode(chunk.data),
  5099. meta: chunk.meta
  5100. });
  5101. };
  5102. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  5103. }, { "./nodejsUtils": 22, "./stream/GenericWorker": 38, "./support": 40, "./utils": 42 }], 42: [function (require, module, exports) {
  5104. 'use strict';
  5105. var support = require('./support');
  5106. var base64 = require('./base64');
  5107. var nodejsUtils = require('./nodejsUtils');
  5108. var setImmediate = require('set-immediate-shim');
  5109. var external = require("./external");
  5110. /**
  5111. * Convert a string that pass as a "binary string": it should represent a byte
  5112. * array but may have > 255 char codes. Be sure to take only the first byte
  5113. * and returns the byte array.
  5114. * @param {String} str the string to transform.
  5115. * @return {Array|Uint8Array} the string in a binary format.
  5116. */
  5117. function string2binary(str) {
  5118. var result = null;
  5119. if (support.uint8array) {
  5120. result = new Uint8Array(str.length);
  5121. } else {
  5122. result = new Array(str.length);
  5123. }
  5124. return stringToArrayLike(str, result);
  5125. }
  5126. /**
  5127. * Create a new blob with the given content and the given type.
  5128. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  5129. * an Uint8Array because the stock browser of android 4 won't accept it (it
  5130. * will be silently converted to a string, "[object Uint8Array]").
  5131. *
  5132. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  5133. * when a large amount of Array is used to create the Blob, the amount of
  5134. * memory consumed is nearly 100 times the original data amount.
  5135. *
  5136. * @param {String} type the mime type of the blob.
  5137. * @return {Blob} the created blob.
  5138. */
  5139. exports.newBlob = function (part, type) {
  5140. exports.checkSupport("blob");
  5141. try {
  5142. // Blob constructor
  5143. return new Blob([part], {
  5144. type: type
  5145. });
  5146. }
  5147. catch (e) {
  5148. try {
  5149. // deprecated, browser only, old way
  5150. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  5151. var builder = new Builder();
  5152. builder.append(part);
  5153. return builder.getBlob(type);
  5154. }
  5155. catch (e) {
  5156. // well, fuck ?!
  5157. throw new Error("Bug : can't construct the Blob.");
  5158. }
  5159. }
  5160. };
  5161. /**
  5162. * The identity function.
  5163. * @param {Object} input the input.
  5164. * @return {Object} the same input.
  5165. */
  5166. function identity(input) {
  5167. return input;
  5168. }
  5169. /**
  5170. * Fill in an array with a string.
  5171. * @param {String} str the string to use.
  5172. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  5173. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  5174. */
  5175. function stringToArrayLike(str, array) {
  5176. for (var i = 0; i < str.length; ++i) {
  5177. array[i] = str.charCodeAt(i) & 0xFF;
  5178. }
  5179. return array;
  5180. }
  5181. /**
  5182. * An helper for the function arrayLikeToString.
  5183. * This contains static information and functions that
  5184. * can be optimized by the browser JIT compiler.
  5185. */
  5186. var arrayToStringHelper = {
  5187. /**
  5188. * Transform an array of int into a string, chunk by chunk.
  5189. * See the performances notes on arrayLikeToString.
  5190. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  5191. * @param {String} type the type of the array.
  5192. * @param {Integer} chunk the chunk size.
  5193. * @return {String} the resulting string.
  5194. * @throws Error if the chunk is too big for the stack.
  5195. */
  5196. stringifyByChunk: function (array, type, chunk) {
  5197. var result = [], k = 0, len = array.length;
  5198. // shortcut
  5199. if (len <= chunk) {
  5200. return String.fromCharCode.apply(null, array);
  5201. }
  5202. while (k < len) {
  5203. if (type === "array" || type === "nodebuffer") {
  5204. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  5205. }
  5206. else {
  5207. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  5208. }
  5209. k += chunk;
  5210. }
  5211. return result.join("");
  5212. },
  5213. /**
  5214. * Call String.fromCharCode on every item in the array.
  5215. * This is the naive implementation, which generate A LOT of intermediate string.
  5216. * This should be used when everything else fail.
  5217. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  5218. * @return {String} the result.
  5219. */
  5220. stringifyByChar: function (array) {
  5221. var resultStr = "";
  5222. for (var i = 0; i < array.length; i++) {
  5223. resultStr += String.fromCharCode(array[i]);
  5224. }
  5225. return resultStr;
  5226. },
  5227. applyCanBeUsed: {
  5228. /**
  5229. * true if the browser accepts to use String.fromCharCode on Uint8Array
  5230. */
  5231. uint8array: (function () {
  5232. try {
  5233. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  5234. } catch (e) {
  5235. return false;
  5236. }
  5237. })(),
  5238. /**
  5239. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  5240. */
  5241. nodebuffer: (function () {
  5242. try {
  5243. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  5244. } catch (e) {
  5245. return false;
  5246. }
  5247. })()
  5248. }
  5249. };
  5250. /**
  5251. * Transform an array-like object to a string.
  5252. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  5253. * @return {String} the result.
  5254. */
  5255. function arrayLikeToString(array) {
  5256. // Performances notes :
  5257. // --------------------
  5258. // String.fromCharCode.apply(null, array) is the fastest, see
  5259. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  5260. // but the stack is limited (and we can get huge arrays !).
  5261. //
  5262. // result += String.fromCharCode(array[i]); generate too many strings !
  5263. //
  5264. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  5265. // TODO : we now have workers that split the work. Do we still need that ?
  5266. var chunk = 65536,
  5267. type = exports.getTypeOf(array),
  5268. canUseApply = true;
  5269. if (type === "uint8array") {
  5270. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  5271. } else if (type === "nodebuffer") {
  5272. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  5273. }
  5274. if (canUseApply) {
  5275. while (chunk > 1) {
  5276. try {
  5277. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  5278. } catch (e) {
  5279. chunk = Math.floor(chunk / 2);
  5280. }
  5281. }
  5282. }
  5283. // no apply or chunk error : slow and painful algorithm
  5284. // default browser on android 4.*
  5285. return arrayToStringHelper.stringifyByChar(array);
  5286. }
  5287. exports.applyFromCharCode = arrayLikeToString;
  5288. /**
  5289. * Copy the data from an array-like to an other array-like.
  5290. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  5291. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  5292. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  5293. */
  5294. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  5295. for (var i = 0; i < arrayFrom.length; i++) {
  5296. arrayTo[i] = arrayFrom[i];
  5297. }
  5298. return arrayTo;
  5299. }
  5300. // a matrix containing functions to transform everything into everything.
  5301. var transform = {};
  5302. // string to ?
  5303. transform["string"] = {
  5304. "string": identity,
  5305. "array": function (input) {
  5306. return stringToArrayLike(input, new Array(input.length));
  5307. },
  5308. "arraybuffer": function (input) {
  5309. return transform["string"]["uint8array"](input).buffer;
  5310. },
  5311. "uint8array": function (input) {
  5312. return stringToArrayLike(input, new Uint8Array(input.length));
  5313. },
  5314. "nodebuffer": function (input) {
  5315. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  5316. }
  5317. };
  5318. // array to ?
  5319. transform["array"] = {
  5320. "string": arrayLikeToString,
  5321. "array": identity,
  5322. "arraybuffer": function (input) {
  5323. return (new Uint8Array(input)).buffer;
  5324. },
  5325. "uint8array": function (input) {
  5326. return new Uint8Array(input);
  5327. },
  5328. "nodebuffer": function (input) {
  5329. return nodejsUtils.newBufferFrom(input);
  5330. }
  5331. };
  5332. // arraybuffer to ?
  5333. transform["arraybuffer"] = {
  5334. "string": function (input) {
  5335. return arrayLikeToString(new Uint8Array(input));
  5336. },
  5337. "array": function (input) {
  5338. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  5339. },
  5340. "arraybuffer": identity,
  5341. "uint8array": function (input) {
  5342. return new Uint8Array(input);
  5343. },
  5344. "nodebuffer": function (input) {
  5345. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  5346. }
  5347. };
  5348. // uint8array to ?
  5349. transform["uint8array"] = {
  5350. "string": arrayLikeToString,
  5351. "array": function (input) {
  5352. return arrayLikeToArrayLike(input, new Array(input.length));
  5353. },
  5354. "arraybuffer": function (input) {
  5355. return input.buffer;
  5356. },
  5357. "uint8array": identity,
  5358. "nodebuffer": function (input) {
  5359. return nodejsUtils.newBufferFrom(input);
  5360. }
  5361. };
  5362. // nodebuffer to ?
  5363. transform["nodebuffer"] = {
  5364. "string": arrayLikeToString,
  5365. "array": function (input) {
  5366. return arrayLikeToArrayLike(input, new Array(input.length));
  5367. },
  5368. "arraybuffer": function (input) {
  5369. return transform["nodebuffer"]["uint8array"](input).buffer;
  5370. },
  5371. "uint8array": function (input) {
  5372. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  5373. },
  5374. "nodebuffer": identity
  5375. };
  5376. /**
  5377. * Transform an input into any type.
  5378. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  5379. * If no output type is specified, the unmodified input will be returned.
  5380. * @param {String} outputType the output type.
  5381. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  5382. * @throws {Error} an Error if the browser doesn't support the requested output type.
  5383. */
  5384. exports.transformTo = function (outputType, input) {
  5385. if (!input) {
  5386. // undefined, null, etc
  5387. // an empty string won't harm.
  5388. input = "";
  5389. }
  5390. if (!outputType) {
  5391. return input;
  5392. }
  5393. exports.checkSupport(outputType);
  5394. var inputType = exports.getTypeOf(input);
  5395. var result = transform[inputType][outputType](input);
  5396. return result;
  5397. };
  5398. /**
  5399. * Return the type of the input.
  5400. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  5401. * @param {Object} input the input to identify.
  5402. * @return {String} the (lowercase) type of the input.
  5403. */
  5404. exports.getTypeOf = function (input) {
  5405. if (typeof input === "string") {
  5406. return "string";
  5407. }
  5408. if (Object.prototype.toString.call(input) === "[object Array]") {
  5409. return "array";
  5410. }
  5411. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  5412. return "nodebuffer";
  5413. }
  5414. if (support.uint8array && input instanceof Uint8Array) {
  5415. return "uint8array";
  5416. }
  5417. if (support.arraybuffer && input instanceof ArrayBuffer) {
  5418. return "arraybuffer";
  5419. }
  5420. };
  5421. /**
  5422. * Throw an exception if the type is not supported.
  5423. * @param {String} type the type to check.
  5424. * @throws {Error} an Error if the browser doesn't support the requested type.
  5425. */
  5426. exports.checkSupport = function (type) {
  5427. var supported = support[type.toLowerCase()];
  5428. if (!supported) {
  5429. throw new Error(type + " is not supported by this platform");
  5430. }
  5431. };
  5432. exports.MAX_VALUE_16BITS = 65535;
  5433. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  5434. /**
  5435. * Prettify a string read as binary.
  5436. * @param {string} str the string to prettify.
  5437. * @return {string} a pretty string.
  5438. */
  5439. exports.pretty = function (str) {
  5440. var res = '',
  5441. code, i;
  5442. for (i = 0; i < (str || "").length; i++) {
  5443. code = str.charCodeAt(i);
  5444. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  5445. }
  5446. return res;
  5447. };
  5448. /**
  5449. * Defer the call of a function.
  5450. * @param {Function} callback the function to call asynchronously.
  5451. * @param {Array} args the arguments to give to the callback.
  5452. */
  5453. exports.delay = function (callback, args, self) {
  5454. setImmediate(function () {
  5455. callback.apply(self || null, args || []);
  5456. });
  5457. };
  5458. /**
  5459. * Extends a prototype with an other, without calling a constructor with
  5460. * side effects. Inspired by nodejs' `utils.inherits`
  5461. * @param {Function} ctor the constructor to augment
  5462. * @param {Function} superCtor the parent constructor to use
  5463. */
  5464. exports.inherits = function (ctor, superCtor) {
  5465. var Obj = function () { };
  5466. Obj.prototype = superCtor.prototype;
  5467. ctor.prototype = new Obj();
  5468. };
  5469. /**
  5470. * Merge the objects passed as parameters into a new one.
  5471. * @private
  5472. * @param {...Object} var_args All objects to merge.
  5473. * @return {Object} a new object with the data of the others.
  5474. */
  5475. exports.extend = function () {
  5476. var result = {}, i, attr;
  5477. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  5478. for (attr in arguments[i]) {
  5479. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  5480. result[attr] = arguments[i][attr];
  5481. }
  5482. }
  5483. }
  5484. return result;
  5485. };
  5486. /**
  5487. * Transform arbitrary content into a Promise.
  5488. * @param {String} name a name for the content being processed.
  5489. * @param {Object} inputData the content to process.
  5490. * @param {Boolean} isBinary true if the content is not an unicode string
  5491. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  5492. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  5493. * @return {Promise} a promise in a format usable by JSZip.
  5494. */
  5495. exports.prepareContent = function (name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  5496. // if inputData is already a promise, this flatten it.
  5497. var promise = external.Promise.resolve(inputData).then(function (data) {
  5498. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  5499. if (isBlob && typeof FileReader !== "undefined") {
  5500. return new external.Promise(function (resolve, reject) {
  5501. var reader = new FileReader();
  5502. reader.onload = function (e) {
  5503. resolve(e.target.result);
  5504. };
  5505. reader.onerror = function (e) {
  5506. reject(e.target.error);
  5507. };
  5508. reader.readAsArrayBuffer(data);
  5509. });
  5510. } else {
  5511. return data;
  5512. }
  5513. });
  5514. return promise.then(function (data) {
  5515. var dataType = exports.getTypeOf(data);
  5516. if (!dataType) {
  5517. return external.Promise.reject(
  5518. new Error("Can't read the data of '" + name + "'. Is it " +
  5519. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  5520. );
  5521. }
  5522. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  5523. if (dataType === "arraybuffer") {
  5524. data = exports.transformTo("uint8array", data);
  5525. } else if (dataType === "string") {
  5526. if (isBase64) {
  5527. data = base64.decode(data);
  5528. }
  5529. else if (isBinary) {
  5530. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  5531. if (isOptimizedBinaryString !== true) {
  5532. // this is a string, not in a base64 format.
  5533. // Be sure that this is a correct "binary string"
  5534. data = string2binary(data);
  5535. }
  5536. }
  5537. }
  5538. return data;
  5539. });
  5540. };
  5541. }, { "./base64": 11, "./external": 16, "./nodejsUtils": 22, "./support": 40, "set-immediate-shim": 79 }], 43: [function (require, module, exports) {
  5542. 'use strict';
  5543. var readerFor = require('./reader/readerFor');
  5544. var utils = require('./utils');
  5545. var sig = require('./signature');
  5546. var ZipEntry = require('./zipEntry');
  5547. var utf8 = require('./utf8');
  5548. var support = require('./support');
  5549. // class ZipEntries {{{
  5550. /**
  5551. * All the entries in the zip file.
  5552. * @constructor
  5553. * @param {Object} loadOptions Options for loading the stream.
  5554. */
  5555. function ZipEntries(loadOptions) {
  5556. this.files = [];
  5557. this.loadOptions = loadOptions;
  5558. }
  5559. ZipEntries.prototype = {
  5560. /**
  5561. * Check that the reader is on the specified signature.
  5562. * @param {string} expectedSignature the expected signature.
  5563. * @throws {Error} if it is an other signature.
  5564. */
  5565. checkSignature: function (expectedSignature) {
  5566. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  5567. this.reader.index -= 4;
  5568. var signature = this.reader.readString(4);
  5569. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  5570. }
  5571. },
  5572. /**
  5573. * Check if the given signature is at the given index.
  5574. * @param {number} askedIndex the index to check.
  5575. * @param {string} expectedSignature the signature to expect.
  5576. * @return {boolean} true if the signature is here, false otherwise.
  5577. */
  5578. isSignature: function (askedIndex, expectedSignature) {
  5579. var currentIndex = this.reader.index;
  5580. this.reader.setIndex(askedIndex);
  5581. var signature = this.reader.readString(4);
  5582. var result = signature === expectedSignature;
  5583. this.reader.setIndex(currentIndex);
  5584. return result;
  5585. },
  5586. /**
  5587. * Read the end of the central directory.
  5588. */
  5589. readBlockEndOfCentral: function () {
  5590. this.diskNumber = this.reader.readInt(2);
  5591. this.diskWithCentralDirStart = this.reader.readInt(2);
  5592. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  5593. this.centralDirRecords = this.reader.readInt(2);
  5594. this.centralDirSize = this.reader.readInt(4);
  5595. this.centralDirOffset = this.reader.readInt(4);
  5596. this.zipCommentLength = this.reader.readInt(2);
  5597. // warning : the encoding depends of the system locale
  5598. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  5599. // On a windows machine, this field is encoded with the localized windows code page.
  5600. var zipComment = this.reader.readData(this.zipCommentLength);
  5601. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5602. // To get consistent behavior with the generation part, we will assume that
  5603. // this is utf8 encoded unless specified otherwise.
  5604. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  5605. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  5606. },
  5607. /**
  5608. * Read the end of the Zip 64 central directory.
  5609. * Not merged with the method readEndOfCentral :
  5610. * The end of central can coexist with its Zip64 brother,
  5611. * I don't want to read the wrong number of bytes !
  5612. */
  5613. readBlockZip64EndOfCentral: function () {
  5614. this.zip64EndOfCentralSize = this.reader.readInt(8);
  5615. this.reader.skip(4);
  5616. // this.versionMadeBy = this.reader.readString(2);
  5617. // this.versionNeeded = this.reader.readInt(2);
  5618. this.diskNumber = this.reader.readInt(4);
  5619. this.diskWithCentralDirStart = this.reader.readInt(4);
  5620. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  5621. this.centralDirRecords = this.reader.readInt(8);
  5622. this.centralDirSize = this.reader.readInt(8);
  5623. this.centralDirOffset = this.reader.readInt(8);
  5624. this.zip64ExtensibleData = {};
  5625. var extraDataSize = this.zip64EndOfCentralSize - 44,
  5626. index = 0,
  5627. extraFieldId,
  5628. extraFieldLength,
  5629. extraFieldValue;
  5630. while (index < extraDataSize) {
  5631. extraFieldId = this.reader.readInt(2);
  5632. extraFieldLength = this.reader.readInt(4);
  5633. extraFieldValue = this.reader.readData(extraFieldLength);
  5634. this.zip64ExtensibleData[extraFieldId] = {
  5635. id: extraFieldId,
  5636. length: extraFieldLength,
  5637. value: extraFieldValue
  5638. };
  5639. }
  5640. },
  5641. /**
  5642. * Read the end of the Zip 64 central directory locator.
  5643. */
  5644. readBlockZip64EndOfCentralLocator: function () {
  5645. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  5646. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  5647. this.disksCount = this.reader.readInt(4);
  5648. if (this.disksCount > 1) {
  5649. throw new Error("Multi-volumes zip are not supported");
  5650. }
  5651. },
  5652. /**
  5653. * Read the local files, based on the offset read in the central part.
  5654. */
  5655. readLocalFiles: function () {
  5656. var i, file;
  5657. for (i = 0; i < this.files.length; i++) {
  5658. file = this.files[i];
  5659. this.reader.setIndex(file.localHeaderOffset);
  5660. this.checkSignature(sig.LOCAL_FILE_HEADER);
  5661. file.readLocalPart(this.reader);
  5662. file.handleUTF8();
  5663. file.processAttributes();
  5664. }
  5665. },
  5666. /**
  5667. * Read the central directory.
  5668. */
  5669. readCentralDir: function () {
  5670. var file;
  5671. this.reader.setIndex(this.centralDirOffset);
  5672. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  5673. file = new ZipEntry({
  5674. zip64: this.zip64
  5675. }, this.loadOptions);
  5676. file.readCentralPart(this.reader);
  5677. this.files.push(file);
  5678. }
  5679. if (this.centralDirRecords !== this.files.length) {
  5680. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  5681. // We expected some records but couldn't find ANY.
  5682. // This is really suspicious, as if something went wrong.
  5683. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  5684. } else {
  5685. // We found some records but not all.
  5686. // Something is wrong but we got something for the user: no error here.
  5687. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  5688. }
  5689. }
  5690. },
  5691. /**
  5692. * Read the end of central directory.
  5693. */
  5694. readEndOfCentral: function () {
  5695. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  5696. if (offset < 0) {
  5697. // Check if the content is a truncated zip or complete garbage.
  5698. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  5699. // extractible zip for example) but it can give a good hint.
  5700. // If an ajax request was used without responseType, we will also
  5701. // get unreadable data.
  5702. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  5703. if (isGarbage) {
  5704. throw new Error("Can't find end of central directory : is this a zip file ? " +
  5705. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  5706. } else {
  5707. throw new Error("Corrupted zip: can't find end of central directory");
  5708. }
  5709. }
  5710. this.reader.setIndex(offset);
  5711. var endOfCentralDirOffset = offset;
  5712. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  5713. this.readBlockEndOfCentral();
  5714. /* extract from the zip spec :
  5715. 4) If one of the fields in the end of central directory
  5716. record is too small to hold required data, the field
  5717. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  5718. ZIP64 format record should be created.
  5719. 5) The end of central directory record and the
  5720. Zip64 end of central directory locator record must
  5721. reside on the same disk when splitting or spanning
  5722. an archive.
  5723. */
  5724. 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) {
  5725. this.zip64 = true;
  5726. /*
  5727. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  5728. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  5729. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  5730. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  5731. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  5732. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  5733. */
  5734. // should look for a zip64 EOCD locator
  5735. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5736. if (offset < 0) {
  5737. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  5738. }
  5739. this.reader.setIndex(offset);
  5740. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5741. this.readBlockZip64EndOfCentralLocator();
  5742. // now the zip64 EOCD record
  5743. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  5744. // console.warn("ZIP64 end of central directory not where expected.");
  5745. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5746. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  5747. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  5748. }
  5749. }
  5750. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  5751. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5752. this.readBlockZip64EndOfCentral();
  5753. }
  5754. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  5755. if (this.zip64) {
  5756. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  5757. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  5758. }
  5759. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  5760. if (extraBytes > 0) {
  5761. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  5762. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  5763. // The offsets seem wrong, but we have something at the specified offset.
  5764. // So… we keep it.
  5765. } else {
  5766. // the offset is wrong, update the "zero" of the reader
  5767. // this happens if data has been prepended (crx files for example)
  5768. this.reader.zero = extraBytes;
  5769. }
  5770. } else if (extraBytes < 0) {
  5771. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  5772. }
  5773. },
  5774. prepareReader: function (data) {
  5775. this.reader = readerFor(data);
  5776. },
  5777. /**
  5778. * Read a zip file and create ZipEntries.
  5779. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  5780. */
  5781. load: function (data) {
  5782. this.prepareReader(data);
  5783. this.readEndOfCentral();
  5784. this.readCentralDir();
  5785. this.readLocalFiles();
  5786. }
  5787. };
  5788. // }}} end of ZipEntries
  5789. module.exports = ZipEntries;
  5790. }, { "./reader/readerFor": 32, "./signature": 33, "./support": 40, "./utf8": 41, "./utils": 42, "./zipEntry": 44 }], 44: [function (require, module, exports) {
  5791. 'use strict';
  5792. var readerFor = require('./reader/readerFor');
  5793. var utils = require('./utils');
  5794. var CompressedObject = require('./compressedObject');
  5795. var crc32fn = require('./crc32');
  5796. var utf8 = require('./utf8');
  5797. var compressions = require('./compressions');
  5798. var support = require('./support');
  5799. var MADE_BY_DOS = 0x00;
  5800. var MADE_BY_UNIX = 0x03;
  5801. /**
  5802. * Find a compression registered in JSZip.
  5803. * @param {string} compressionMethod the method magic to find.
  5804. * @return {Object|null} the JSZip compression object, null if none found.
  5805. */
  5806. var findCompression = function (compressionMethod) {
  5807. for (var method in compressions) {
  5808. if (!compressions.hasOwnProperty(method)) {
  5809. continue;
  5810. }
  5811. if (compressions[method].magic === compressionMethod) {
  5812. return compressions[method];
  5813. }
  5814. }
  5815. return null;
  5816. };
  5817. // class ZipEntry {{{
  5818. /**
  5819. * An entry in the zip file.
  5820. * @constructor
  5821. * @param {Object} options Options of the current file.
  5822. * @param {Object} loadOptions Options for loading the stream.
  5823. */
  5824. function ZipEntry(options, loadOptions) {
  5825. this.options = options;
  5826. this.loadOptions = loadOptions;
  5827. }
  5828. ZipEntry.prototype = {
  5829. /**
  5830. * say if the file is encrypted.
  5831. * @return {boolean} true if the file is encrypted, false otherwise.
  5832. */
  5833. isEncrypted: function () {
  5834. // bit 1 is set
  5835. return (this.bitFlag & 0x0001) === 0x0001;
  5836. },
  5837. /**
  5838. * say if the file has utf-8 filename/comment.
  5839. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  5840. */
  5841. useUTF8: function () {
  5842. // bit 11 is set
  5843. return (this.bitFlag & 0x0800) === 0x0800;
  5844. },
  5845. /**
  5846. * Read the local part of a zip file and add the info in this object.
  5847. * @param {DataReader} reader the reader to use.
  5848. */
  5849. readLocalPart: function (reader) {
  5850. var compression, localExtraFieldsLength;
  5851. // we already know everything from the central dir !
  5852. // If the central dir data are false, we are doomed.
  5853. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  5854. // The less data we get here, the more reliable this should be.
  5855. // Let's skip the whole header and dash to the data !
  5856. reader.skip(22);
  5857. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  5858. // Strangely, the filename here is OK.
  5859. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  5860. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  5861. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  5862. // the internet.
  5863. //
  5864. // I think I see the logic here : the central directory is used to display
  5865. // content and the local directory is used to extract the files. Mixing / and \
  5866. // may be used to display \ to windows users and use / when extracting the files.
  5867. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  5868. this.fileNameLength = reader.readInt(2);
  5869. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  5870. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  5871. this.fileName = reader.readData(this.fileNameLength);
  5872. reader.skip(localExtraFieldsLength);
  5873. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  5874. throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  5875. }
  5876. compression = findCompression(this.compressionMethod);
  5877. if (compression === null) { // no compression found
  5878. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  5879. }
  5880. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  5881. },
  5882. /**
  5883. * Read the central part of a zip file and add the info in this object.
  5884. * @param {DataReader} reader the reader to use.
  5885. */
  5886. readCentralPart: function (reader) {
  5887. this.versionMadeBy = reader.readInt(2);
  5888. reader.skip(2);
  5889. // this.versionNeeded = reader.readInt(2);
  5890. this.bitFlag = reader.readInt(2);
  5891. this.compressionMethod = reader.readString(2);
  5892. this.date = reader.readDate();
  5893. this.crc32 = reader.readInt(4);
  5894. this.compressedSize = reader.readInt(4);
  5895. this.uncompressedSize = reader.readInt(4);
  5896. var fileNameLength = reader.readInt(2);
  5897. this.extraFieldsLength = reader.readInt(2);
  5898. this.fileCommentLength = reader.readInt(2);
  5899. this.diskNumberStart = reader.readInt(2);
  5900. this.internalFileAttributes = reader.readInt(2);
  5901. this.externalFileAttributes = reader.readInt(4);
  5902. this.localHeaderOffset = reader.readInt(4);
  5903. if (this.isEncrypted()) {
  5904. throw new Error("Encrypted zip are not supported");
  5905. }
  5906. // will be read in the local part, see the comments there
  5907. reader.skip(fileNameLength);
  5908. this.readExtraFields(reader);
  5909. this.parseZIP64ExtraField(reader);
  5910. this.fileComment = reader.readData(this.fileCommentLength);
  5911. },
  5912. /**
  5913. * Parse the external file attributes and get the unix/dos permissions.
  5914. */
  5915. processAttributes: function () {
  5916. this.unixPermissions = null;
  5917. this.dosPermissions = null;
  5918. var madeBy = this.versionMadeBy >> 8;
  5919. // Check if we have the DOS directory flag set.
  5920. // We look for it in the DOS and UNIX permissions
  5921. // but some unknown platform could set it as a compatibility flag.
  5922. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  5923. if (madeBy === MADE_BY_DOS) {
  5924. // first 6 bits (0 to 5)
  5925. this.dosPermissions = this.externalFileAttributes & 0x3F;
  5926. }
  5927. if (madeBy === MADE_BY_UNIX) {
  5928. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  5929. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  5930. }
  5931. // fail safe : if the name ends with a / it probably means a folder
  5932. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  5933. this.dir = true;
  5934. }
  5935. },
  5936. /**
  5937. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  5938. * @param {DataReader} reader the reader to use.
  5939. */
  5940. parseZIP64ExtraField: function (reader) {
  5941. if (!this.extraFields[0x0001]) {
  5942. return;
  5943. }
  5944. // should be something, preparing the extra reader
  5945. var extraReader = readerFor(this.extraFields[0x0001].value);
  5946. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  5947. // won't let us have more.
  5948. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  5949. this.uncompressedSize = extraReader.readInt(8);
  5950. }
  5951. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  5952. this.compressedSize = extraReader.readInt(8);
  5953. }
  5954. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  5955. this.localHeaderOffset = extraReader.readInt(8);
  5956. }
  5957. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  5958. this.diskNumberStart = extraReader.readInt(4);
  5959. }
  5960. },
  5961. /**
  5962. * Read the central part of a zip file and add the info in this object.
  5963. * @param {DataReader} reader the reader to use.
  5964. */
  5965. readExtraFields: function (reader) {
  5966. var end = reader.index + this.extraFieldsLength,
  5967. extraFieldId,
  5968. extraFieldLength,
  5969. extraFieldValue;
  5970. if (!this.extraFields) {
  5971. this.extraFields = {};
  5972. }
  5973. while (reader.index + 4 < end) {
  5974. extraFieldId = reader.readInt(2);
  5975. extraFieldLength = reader.readInt(2);
  5976. extraFieldValue = reader.readData(extraFieldLength);
  5977. this.extraFields[extraFieldId] = {
  5978. id: extraFieldId,
  5979. length: extraFieldLength,
  5980. value: extraFieldValue
  5981. };
  5982. }
  5983. reader.setIndex(end);
  5984. },
  5985. /**
  5986. * Apply an UTF8 transformation if needed.
  5987. */
  5988. handleUTF8: function () {
  5989. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5990. if (this.useUTF8()) {
  5991. this.fileNameStr = utf8.utf8decode(this.fileName);
  5992. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  5993. } else {
  5994. var upath = this.findExtraFieldUnicodePath();
  5995. if (upath !== null) {
  5996. this.fileNameStr = upath;
  5997. } else {
  5998. // ASCII text or unsupported code page
  5999. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  6000. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  6001. }
  6002. var ucomment = this.findExtraFieldUnicodeComment();
  6003. if (ucomment !== null) {
  6004. this.fileCommentStr = ucomment;
  6005. } else {
  6006. // ASCII text or unsupported code page
  6007. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  6008. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  6009. }
  6010. }
  6011. },
  6012. /**
  6013. * Find the unicode path declared in the extra field, if any.
  6014. * @return {String} the unicode path, null otherwise.
  6015. */
  6016. findExtraFieldUnicodePath: function () {
  6017. var upathField = this.extraFields[0x7075];
  6018. if (upathField) {
  6019. var extraReader = readerFor(upathField.value);
  6020. // wrong version
  6021. if (extraReader.readInt(1) !== 1) {
  6022. return null;
  6023. }
  6024. // the crc of the filename changed, this field is out of date.
  6025. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  6026. return null;
  6027. }
  6028. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  6029. }
  6030. return null;
  6031. },
  6032. /**
  6033. * Find the unicode comment declared in the extra field, if any.
  6034. * @return {String} the unicode comment, null otherwise.
  6035. */
  6036. findExtraFieldUnicodeComment: function () {
  6037. var ucommentField = this.extraFields[0x6375];
  6038. if (ucommentField) {
  6039. var extraReader = readerFor(ucommentField.value);
  6040. // wrong version
  6041. if (extraReader.readInt(1) !== 1) {
  6042. return null;
  6043. }
  6044. // the crc of the comment changed, this field is out of date.
  6045. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  6046. return null;
  6047. }
  6048. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  6049. }
  6050. return null;
  6051. }
  6052. };
  6053. module.exports = ZipEntry;
  6054. }, { "./compressedObject": 12, "./compressions": 13, "./crc32": 14, "./reader/readerFor": 32, "./support": 40, "./utf8": 41, "./utils": 42 }], 45: [function (require, module, exports) {
  6055. 'use strict';
  6056. var StreamHelper = require('./stream/StreamHelper');
  6057. var DataWorker = require('./stream/DataWorker');
  6058. var utf8 = require('./utf8');
  6059. var CompressedObject = require('./compressedObject');
  6060. var GenericWorker = require('./stream/GenericWorker');
  6061. /**
  6062. * A simple object representing a file in the zip file.
  6063. * @constructor
  6064. * @param {string} name the name of the file
  6065. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  6066. * @param {Object} options the options of the file
  6067. */
  6068. var ZipObject = function (name, data, options) {
  6069. this.name = name;
  6070. this.dir = options.dir;
  6071. this.date = options.date;
  6072. this.comment = options.comment;
  6073. this.unixPermissions = options.unixPermissions;
  6074. this.dosPermissions = options.dosPermissions;
  6075. this._data = data;
  6076. this._dataBinary = options.binary;
  6077. // keep only the compression
  6078. this.options = {
  6079. compression: options.compression,
  6080. compressionOptions: options.compressionOptions
  6081. };
  6082. };
  6083. ZipObject.prototype = {
  6084. /**
  6085. * Create an internal stream for the content of this object.
  6086. * @param {String} type the type of each chunk.
  6087. * @return StreamHelper the stream.
  6088. */
  6089. internalStream: function (type) {
  6090. var result = null, outputType = "string";
  6091. try {
  6092. if (!type) {
  6093. throw new Error("No output type specified.");
  6094. }
  6095. outputType = type.toLowerCase();
  6096. var askUnicodeString = outputType === "string" || outputType === "text";
  6097. if (outputType === "binarystring" || outputType === "text") {
  6098. outputType = "string";
  6099. }
  6100. result = this._decompressWorker();
  6101. var isUnicodeString = !this._dataBinary;
  6102. if (isUnicodeString && !askUnicodeString) {
  6103. result = result.pipe(new utf8.Utf8EncodeWorker());
  6104. }
  6105. if (!isUnicodeString && askUnicodeString) {
  6106. result = result.pipe(new utf8.Utf8DecodeWorker());
  6107. }
  6108. } catch (e) {
  6109. result = new GenericWorker("error");
  6110. result.error(e);
  6111. }
  6112. return new StreamHelper(result, outputType, "");
  6113. },
  6114. /**
  6115. * Prepare the content in the asked type.
  6116. * @param {String} type the type of the result.
  6117. * @param {Function} onUpdate a function to call on each internal update.
  6118. * @return Promise the promise of the result.
  6119. */
  6120. async: function (type, onUpdate) {
  6121. return this.internalStream(type).accumulate(onUpdate);
  6122. },
  6123. /**
  6124. * Prepare the content as a nodejs stream.
  6125. * @param {String} type the type of each chunk.
  6126. * @param {Function} onUpdate a function to call on each internal update.
  6127. * @return Stream the stream.
  6128. */
  6129. nodeStream: function (type, onUpdate) {
  6130. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  6131. },
  6132. /**
  6133. * Return a worker for the compressed content.
  6134. * @private
  6135. * @param {Object} compression the compression object to use.
  6136. * @param {Object} compressionOptions the options to use when compressing.
  6137. * @return Worker the worker.
  6138. */
  6139. _compressWorker: function (compression, compressionOptions) {
  6140. if (
  6141. this._data instanceof CompressedObject &&
  6142. this._data.compression.magic === compression.magic
  6143. ) {
  6144. return this._data.getCompressedWorker();
  6145. } else {
  6146. var result = this._decompressWorker();
  6147. if (!this._dataBinary) {
  6148. result = result.pipe(new utf8.Utf8EncodeWorker());
  6149. }
  6150. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  6151. }
  6152. },
  6153. /**
  6154. * Return a worker for the decompressed content.
  6155. * @private
  6156. * @return Worker the worker.
  6157. */
  6158. _decompressWorker: function () {
  6159. if (this._data instanceof CompressedObject) {
  6160. return this._data.getContentWorker();
  6161. } else if (this._data instanceof GenericWorker) {
  6162. return this._data;
  6163. } else {
  6164. return new DataWorker(this._data);
  6165. }
  6166. }
  6167. };
  6168. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  6169. var removedFn = function () {
  6170. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  6171. };
  6172. for (var i = 0; i < removedMethods.length; i++) {
  6173. ZipObject.prototype[removedMethods[i]] = removedFn;
  6174. }
  6175. module.exports = ZipObject;
  6176. }, { "./compressedObject": 12, "./stream/DataWorker": 37, "./stream/GenericWorker": 38, "./stream/StreamHelper": 39, "./utf8": 41 }], 46: [function (require, module, exports) {
  6177. 'use strict';
  6178. var immediate = require('immediate');
  6179. /* istanbul ignore next */
  6180. function INTERNAL() { }
  6181. var handlers = {};
  6182. var REJECTED = ['REJECTED'];
  6183. var FULFILLED = ['FULFILLED'];
  6184. var PENDING = ['PENDING'];
  6185. module.exports = Promise;
  6186. function Promise(resolver) {
  6187. if (typeof resolver !== 'function') {
  6188. throw new TypeError('resolver must be a function');
  6189. }
  6190. this.state = PENDING;
  6191. this.queue = [];
  6192. this.outcome = void 0;
  6193. if (resolver !== INTERNAL) {
  6194. safelyResolveThenable(this, resolver);
  6195. }
  6196. }
  6197. Promise.prototype["finally"] = function (callback) {
  6198. if (typeof callback !== 'function') {
  6199. return this;
  6200. }
  6201. var p = this.constructor;
  6202. return this.then(resolve, reject);
  6203. function resolve(value) {
  6204. function yes() {
  6205. return value;
  6206. }
  6207. return p.resolve(callback()).then(yes);
  6208. }
  6209. function reject(reason) {
  6210. function no() {
  6211. throw reason;
  6212. }
  6213. return p.resolve(callback()).then(no);
  6214. }
  6215. };
  6216. Promise.prototype["catch"] = function (onRejected) {
  6217. return this.then(null, onRejected);
  6218. };
  6219. Promise.prototype.then = function (onFulfilled, onRejected) {
  6220. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  6221. typeof onRejected !== 'function' && this.state === REJECTED) {
  6222. return this;
  6223. }
  6224. var promise = new this.constructor(INTERNAL);
  6225. if (this.state !== PENDING) {
  6226. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  6227. unwrap(promise, resolver, this.outcome);
  6228. } else {
  6229. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  6230. }
  6231. return promise;
  6232. };
  6233. function QueueItem(promise, onFulfilled, onRejected) {
  6234. this.promise = promise;
  6235. if (typeof onFulfilled === 'function') {
  6236. this.onFulfilled = onFulfilled;
  6237. this.callFulfilled = this.otherCallFulfilled;
  6238. }
  6239. if (typeof onRejected === 'function') {
  6240. this.onRejected = onRejected;
  6241. this.callRejected = this.otherCallRejected;
  6242. }
  6243. }
  6244. QueueItem.prototype.callFulfilled = function (value) {
  6245. handlers.resolve(this.promise, value);
  6246. };
  6247. QueueItem.prototype.otherCallFulfilled = function (value) {
  6248. unwrap(this.promise, this.onFulfilled, value);
  6249. };
  6250. QueueItem.prototype.callRejected = function (value) {
  6251. handlers.reject(this.promise, value);
  6252. };
  6253. QueueItem.prototype.otherCallRejected = function (value) {
  6254. unwrap(this.promise, this.onRejected, value);
  6255. };
  6256. function unwrap(promise, func, value) {
  6257. immediate(function () {
  6258. var returnValue;
  6259. try {
  6260. returnValue = func(value);
  6261. } catch (e) {
  6262. return handlers.reject(promise, e);
  6263. }
  6264. if (returnValue === promise) {
  6265. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  6266. } else {
  6267. handlers.resolve(promise, returnValue);
  6268. }
  6269. });
  6270. }
  6271. handlers.resolve = function (self, value) {
  6272. var result = tryCatch(getThen, value);
  6273. if (result.status === 'error') {
  6274. return handlers.reject(self, result.value);
  6275. }
  6276. var thenable = result.value;
  6277. if (thenable) {
  6278. safelyResolveThenable(self, thenable);
  6279. } else {
  6280. self.state = FULFILLED;
  6281. self.outcome = value;
  6282. var i = -1;
  6283. var len = self.queue.length;
  6284. while (++i < len) {
  6285. self.queue[i].callFulfilled(value);
  6286. }
  6287. }
  6288. return self;
  6289. };
  6290. handlers.reject = function (self, error) {
  6291. self.state = REJECTED;
  6292. self.outcome = error;
  6293. var i = -1;
  6294. var len = self.queue.length;
  6295. while (++i < len) {
  6296. self.queue[i].callRejected(error);
  6297. }
  6298. return self;
  6299. };
  6300. function getThen(obj) {
  6301. // Make sure we only access the accessor once as required by the spec
  6302. var then = obj && obj.then;
  6303. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  6304. return function appyThen() {
  6305. then.apply(obj, arguments);
  6306. };
  6307. }
  6308. }
  6309. function safelyResolveThenable(self, thenable) {
  6310. // Either fulfill, reject or reject with error
  6311. var called = false;
  6312. function onError(value) {
  6313. if (called) {
  6314. return;
  6315. }
  6316. called = true;
  6317. handlers.reject(self, value);
  6318. }
  6319. function onSuccess(value) {
  6320. if (called) {
  6321. return;
  6322. }
  6323. called = true;
  6324. handlers.resolve(self, value);
  6325. }
  6326. function tryToUnwrap() {
  6327. thenable(onSuccess, onError);
  6328. }
  6329. var result = tryCatch(tryToUnwrap);
  6330. if (result.status === 'error') {
  6331. onError(result.value);
  6332. }
  6333. }
  6334. function tryCatch(func, value) {
  6335. var out = {};
  6336. try {
  6337. out.value = func(value);
  6338. out.status = 'success';
  6339. } catch (e) {
  6340. out.status = 'error';
  6341. out.value = e;
  6342. }
  6343. return out;
  6344. }
  6345. Promise.resolve = resolve;
  6346. function resolve(value) {
  6347. if (value instanceof this) {
  6348. return value;
  6349. }
  6350. return handlers.resolve(new this(INTERNAL), value);
  6351. }
  6352. Promise.reject = reject;
  6353. function reject(reason) {
  6354. var promise = new this(INTERNAL);
  6355. return handlers.reject(promise, reason);
  6356. }
  6357. Promise.all = all;
  6358. function all(iterable) {
  6359. var self = this;
  6360. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  6361. return this.reject(new TypeError('must be an array'));
  6362. }
  6363. var len = iterable.length;
  6364. var called = false;
  6365. if (!len) {
  6366. return this.resolve([]);
  6367. }
  6368. var values = new Array(len);
  6369. var resolved = 0;
  6370. var i = -1;
  6371. var promise = new this(INTERNAL);
  6372. while (++i < len) {
  6373. allResolver(iterable[i], i);
  6374. }
  6375. return promise;
  6376. function allResolver(value, i) {
  6377. self.resolve(value).then(resolveFromAll, function (error) {
  6378. if (!called) {
  6379. called = true;
  6380. handlers.reject(promise, error);
  6381. }
  6382. });
  6383. function resolveFromAll(outValue) {
  6384. values[i] = outValue;
  6385. if (++resolved === len && !called) {
  6386. called = true;
  6387. handlers.resolve(promise, values);
  6388. }
  6389. }
  6390. }
  6391. }
  6392. Promise.race = race;
  6393. function race(iterable) {
  6394. var self = this;
  6395. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  6396. return this.reject(new TypeError('must be an array'));
  6397. }
  6398. var len = iterable.length;
  6399. var called = false;
  6400. if (!len) {
  6401. return this.resolve([]);
  6402. }
  6403. var i = -1;
  6404. var promise = new this(INTERNAL);
  6405. while (++i < len) {
  6406. resolver(iterable[i]);
  6407. }
  6408. return promise;
  6409. function resolver(value) {
  6410. self.resolve(value).then(function (response) {
  6411. if (!called) {
  6412. called = true;
  6413. handlers.resolve(promise, response);
  6414. }
  6415. }, function (error) {
  6416. if (!called) {
  6417. called = true;
  6418. handlers.reject(promise, error);
  6419. }
  6420. });
  6421. }
  6422. }
  6423. }, { "immediate": 7 }], 47: [function (require, module, exports) {
  6424. // Top level file is just a mixin of submodules & constants
  6425. 'use strict';
  6426. var assign = require('./lib/utils/common').assign;
  6427. var deflate = require('./lib/deflate');
  6428. var inflate = require('./lib/inflate');
  6429. var constants = require('./lib/zlib/constants');
  6430. var pako = {};
  6431. assign(pako, deflate, inflate, constants);
  6432. module.exports = pako;
  6433. }, { "./lib/deflate": 48, "./lib/inflate": 49, "./lib/utils/common": 50, "./lib/zlib/constants": 53 }], 48: [function (require, module, exports) {
  6434. 'use strict';
  6435. var zlib_deflate = require('./zlib/deflate');
  6436. var utils = require('./utils/common');
  6437. var strings = require('./utils/strings');
  6438. var msg = require('./zlib/messages');
  6439. var ZStream = require('./zlib/zstream');
  6440. var toString = Object.prototype.toString;
  6441. /* Public constants ==========================================================*/
  6442. /* ===========================================================================*/
  6443. var Z_NO_FLUSH = 0;
  6444. var Z_FINISH = 4;
  6445. var Z_OK = 0;
  6446. var Z_STREAM_END = 1;
  6447. var Z_SYNC_FLUSH = 2;
  6448. var Z_DEFAULT_COMPRESSION = -1;
  6449. var Z_DEFAULT_STRATEGY = 0;
  6450. var Z_DEFLATED = 8;
  6451. /* ===========================================================================*/
  6452. /**
  6453. * class Deflate
  6454. *
  6455. * Generic JS-style wrapper for zlib calls. If you don't need
  6456. * streaming behaviour - use more simple functions: [[deflate]],
  6457. * [[deflateRaw]] and [[gzip]].
  6458. **/
  6459. /* internal
  6460. * Deflate.chunks -> Array
  6461. *
  6462. * Chunks of output data, if [[Deflate#onData]] not overridden.
  6463. **/
  6464. /**
  6465. * Deflate.result -> Uint8Array|Array
  6466. *
  6467. * Compressed result, generated by default [[Deflate#onData]]
  6468. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  6469. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  6470. * push a chunk with explicit flush (call [[Deflate#push]] with
  6471. * `Z_SYNC_FLUSH` param).
  6472. **/
  6473. /**
  6474. * Deflate.err -> Number
  6475. *
  6476. * Error code after deflate finished. 0 (Z_OK) on success.
  6477. * You will not need it in real life, because deflate errors
  6478. * are possible only on wrong options or bad `onData` / `onEnd`
  6479. * custom handlers.
  6480. **/
  6481. /**
  6482. * Deflate.msg -> String
  6483. *
  6484. * Error message, if [[Deflate.err]] != 0
  6485. **/
  6486. /**
  6487. * new Deflate(options)
  6488. * - options (Object): zlib deflate options.
  6489. *
  6490. * Creates new deflator instance with specified params. Throws exception
  6491. * on bad params. Supported options:
  6492. *
  6493. * - `level`
  6494. * - `windowBits`
  6495. * - `memLevel`
  6496. * - `strategy`
  6497. * - `dictionary`
  6498. *
  6499. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6500. * for more information on these.
  6501. *
  6502. * Additional options, for internal needs:
  6503. *
  6504. * - `chunkSize` - size of generated data chunks (16K by default)
  6505. * - `raw` (Boolean) - do raw deflate
  6506. * - `gzip` (Boolean) - create gzip wrapper
  6507. * - `to` (String) - if equal to 'string', then result will be "binary string"
  6508. * (each char code [0..255])
  6509. * - `header` (Object) - custom header for gzip
  6510. * - `text` (Boolean) - true if compressed data believed to be text
  6511. * - `time` (Number) - modification time, unix timestamp
  6512. * - `os` (Number) - operation system code
  6513. * - `extra` (Array) - array of bytes with extra data (max 65536)
  6514. * - `name` (String) - file name (binary string)
  6515. * - `comment` (String) - comment (binary string)
  6516. * - `hcrc` (Boolean) - true if header crc should be added
  6517. *
  6518. * ##### Example:
  6519. *
  6520. * ```javascript
  6521. * var pako = require('pako')
  6522. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  6523. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  6524. *
  6525. * var deflate = new pako.Deflate({ level: 3});
  6526. *
  6527. * deflate.push(chunk1, false);
  6528. * deflate.push(chunk2, true); // true -> last chunk
  6529. *
  6530. * if (deflate.err) { throw new Error(deflate.err); }
  6531. *
  6532. * console.log(deflate.result);
  6533. * ```
  6534. **/
  6535. function Deflate(options) {
  6536. if (!(this instanceof Deflate)) return new Deflate(options);
  6537. this.options = utils.assign({
  6538. level: Z_DEFAULT_COMPRESSION,
  6539. method: Z_DEFLATED,
  6540. chunkSize: 16384,
  6541. windowBits: 15,
  6542. memLevel: 8,
  6543. strategy: Z_DEFAULT_STRATEGY,
  6544. to: ''
  6545. }, options || {});
  6546. var opt = this.options;
  6547. if (opt.raw && (opt.windowBits > 0)) {
  6548. opt.windowBits = -opt.windowBits;
  6549. }
  6550. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  6551. opt.windowBits += 16;
  6552. }
  6553. this.err = 0; // error code, if happens (0 = Z_OK)
  6554. this.msg = ''; // error message
  6555. this.ended = false; // used to avoid multiple onEnd() calls
  6556. this.chunks = []; // chunks of compressed data
  6557. this.strm = new ZStream();
  6558. this.strm.avail_out = 0;
  6559. var status = zlib_deflate.deflateInit2(
  6560. this.strm,
  6561. opt.level,
  6562. opt.method,
  6563. opt.windowBits,
  6564. opt.memLevel,
  6565. opt.strategy
  6566. );
  6567. if (status !== Z_OK) {
  6568. throw new Error(msg[status]);
  6569. }
  6570. if (opt.header) {
  6571. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  6572. }
  6573. if (opt.dictionary) {
  6574. var dict;
  6575. // Convert data if needed
  6576. if (typeof opt.dictionary === 'string') {
  6577. // If we need to compress text, change encoding to utf8.
  6578. dict = strings.string2buf(opt.dictionary);
  6579. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  6580. dict = new Uint8Array(opt.dictionary);
  6581. } else {
  6582. dict = opt.dictionary;
  6583. }
  6584. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  6585. if (status !== Z_OK) {
  6586. throw new Error(msg[status]);
  6587. }
  6588. this._dict_set = true;
  6589. }
  6590. }
  6591. /**
  6592. * Deflate#push(data[, mode]) -> Boolean
  6593. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  6594. * converted to utf8 byte sequence.
  6595. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  6596. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  6597. *
  6598. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  6599. * new compressed chunks. Returns `true` on success. The last data block must have
  6600. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  6601. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  6602. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  6603. *
  6604. * On fail call [[Deflate#onEnd]] with error code and return false.
  6605. *
  6606. * We strongly recommend to use `Uint8Array` on input for best speed (output
  6607. * array format is detected automatically). Also, don't skip last param and always
  6608. * use the same type in your code (boolean or number). That will improve JS speed.
  6609. *
  6610. * For regular `Array`-s make sure all elements are [0..255].
  6611. *
  6612. * ##### Example
  6613. *
  6614. * ```javascript
  6615. * push(chunk, false); // push one of data chunks
  6616. * ...
  6617. * push(chunk, true); // push last chunk
  6618. * ```
  6619. **/
  6620. Deflate.prototype.push = function (data, mode) {
  6621. var strm = this.strm;
  6622. var chunkSize = this.options.chunkSize;
  6623. var status, _mode;
  6624. if (this.ended) { return false; }
  6625. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  6626. // Convert data if needed
  6627. if (typeof data === 'string') {
  6628. // If we need to compress text, change encoding to utf8.
  6629. strm.input = strings.string2buf(data);
  6630. } else if (toString.call(data) === '[object ArrayBuffer]') {
  6631. strm.input = new Uint8Array(data);
  6632. } else {
  6633. strm.input = data;
  6634. }
  6635. strm.next_in = 0;
  6636. strm.avail_in = strm.input.length;
  6637. do {
  6638. if (strm.avail_out === 0) {
  6639. strm.output = new utils.Buf8(chunkSize);
  6640. strm.next_out = 0;
  6641. strm.avail_out = chunkSize;
  6642. }
  6643. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  6644. if (status !== Z_STREAM_END && status !== Z_OK) {
  6645. this.onEnd(status);
  6646. this.ended = true;
  6647. return false;
  6648. }
  6649. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  6650. if (this.options.to === 'string') {
  6651. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  6652. } else {
  6653. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  6654. }
  6655. }
  6656. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  6657. // Finalize on the last chunk.
  6658. if (_mode === Z_FINISH) {
  6659. status = zlib_deflate.deflateEnd(this.strm);
  6660. this.onEnd(status);
  6661. this.ended = true;
  6662. return status === Z_OK;
  6663. }
  6664. // callback interim results if Z_SYNC_FLUSH.
  6665. if (_mode === Z_SYNC_FLUSH) {
  6666. this.onEnd(Z_OK);
  6667. strm.avail_out = 0;
  6668. return true;
  6669. }
  6670. return true;
  6671. };
  6672. /**
  6673. * Deflate#onData(chunk) -> Void
  6674. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  6675. * on js engine support. When string output requested, each chunk
  6676. * will be string.
  6677. *
  6678. * By default, stores data blocks in `chunks[]` property and glue
  6679. * those in `onEnd`. Override this handler, if you need another behaviour.
  6680. **/
  6681. Deflate.prototype.onData = function (chunk) {
  6682. this.chunks.push(chunk);
  6683. };
  6684. /**
  6685. * Deflate#onEnd(status) -> Void
  6686. * - status (Number): deflate status. 0 (Z_OK) on success,
  6687. * other if not.
  6688. *
  6689. * Called once after you tell deflate that the input stream is
  6690. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  6691. * or if an error happened. By default - join collected chunks,
  6692. * free memory and fill `results` / `err` properties.
  6693. **/
  6694. Deflate.prototype.onEnd = function (status) {
  6695. // On success - join
  6696. if (status === Z_OK) {
  6697. if (this.options.to === 'string') {
  6698. this.result = this.chunks.join('');
  6699. } else {
  6700. this.result = utils.flattenChunks(this.chunks);
  6701. }
  6702. }
  6703. this.chunks = [];
  6704. this.err = status;
  6705. this.msg = this.strm.msg;
  6706. };
  6707. /**
  6708. * deflate(data[, options]) -> Uint8Array|Array|String
  6709. * - data (Uint8Array|Array|String): input data to compress.
  6710. * - options (Object): zlib deflate options.
  6711. *
  6712. * Compress `data` with deflate algorithm and `options`.
  6713. *
  6714. * Supported options are:
  6715. *
  6716. * - level
  6717. * - windowBits
  6718. * - memLevel
  6719. * - strategy
  6720. * - dictionary
  6721. *
  6722. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6723. * for more information on these.
  6724. *
  6725. * Sugar (options):
  6726. *
  6727. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  6728. * negative windowBits implicitly.
  6729. * - `to` (String) - if equal to 'string', then result will be "binary string"
  6730. * (each char code [0..255])
  6731. *
  6732. * ##### Example:
  6733. *
  6734. * ```javascript
  6735. * var pako = require('pako')
  6736. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  6737. *
  6738. * console.log(pako.deflate(data));
  6739. * ```
  6740. **/
  6741. function deflate(input, options) {
  6742. var deflator = new Deflate(options);
  6743. deflator.push(input, true);
  6744. // That will never happens, if you don't cheat with options :)
  6745. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  6746. return deflator.result;
  6747. }
  6748. /**
  6749. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  6750. * - data (Uint8Array|Array|String): input data to compress.
  6751. * - options (Object): zlib deflate options.
  6752. *
  6753. * The same as [[deflate]], but creates raw data, without wrapper
  6754. * (header and adler32 crc).
  6755. **/
  6756. function deflateRaw(input, options) {
  6757. options = options || {};
  6758. options.raw = true;
  6759. return deflate(input, options);
  6760. }
  6761. /**
  6762. * gzip(data[, options]) -> Uint8Array|Array|String
  6763. * - data (Uint8Array|Array|String): input data to compress.
  6764. * - options (Object): zlib deflate options.
  6765. *
  6766. * The same as [[deflate]], but create gzip wrapper instead of
  6767. * deflate one.
  6768. **/
  6769. function gzip(input, options) {
  6770. options = options || {};
  6771. options.gzip = true;
  6772. return deflate(input, options);
  6773. }
  6774. exports.Deflate = Deflate;
  6775. exports.deflate = deflate;
  6776. exports.deflateRaw = deflateRaw;
  6777. exports.gzip = gzip;
  6778. }, { "./utils/common": 50, "./utils/strings": 51, "./zlib/deflate": 55, "./zlib/messages": 60, "./zlib/zstream": 62 }], 49: [function (require, module, exports) {
  6779. 'use strict';
  6780. var zlib_inflate = require('./zlib/inflate');
  6781. var utils = require('./utils/common');
  6782. var strings = require('./utils/strings');
  6783. var c = require('./zlib/constants');
  6784. var msg = require('./zlib/messages');
  6785. var ZStream = require('./zlib/zstream');
  6786. var GZheader = require('./zlib/gzheader');
  6787. var toString = Object.prototype.toString;
  6788. /**
  6789. * class Inflate
  6790. *
  6791. * Generic JS-style wrapper for zlib calls. If you don't need
  6792. * streaming behaviour - use more simple functions: [[inflate]]
  6793. * and [[inflateRaw]].
  6794. **/
  6795. /* internal
  6796. * inflate.chunks -> Array
  6797. *
  6798. * Chunks of output data, if [[Inflate#onData]] not overridden.
  6799. **/
  6800. /**
  6801. * Inflate.result -> Uint8Array|Array|String
  6802. *
  6803. * Uncompressed result, generated by default [[Inflate#onData]]
  6804. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  6805. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  6806. * push a chunk with explicit flush (call [[Inflate#push]] with
  6807. * `Z_SYNC_FLUSH` param).
  6808. **/
  6809. /**
  6810. * Inflate.err -> Number
  6811. *
  6812. * Error code after inflate finished. 0 (Z_OK) on success.
  6813. * Should be checked if broken data possible.
  6814. **/
  6815. /**
  6816. * Inflate.msg -> String
  6817. *
  6818. * Error message, if [[Inflate.err]] != 0
  6819. **/
  6820. /**
  6821. * new Inflate(options)
  6822. * - options (Object): zlib inflate options.
  6823. *
  6824. * Creates new inflator instance with specified params. Throws exception
  6825. * on bad params. Supported options:
  6826. *
  6827. * - `windowBits`
  6828. * - `dictionary`
  6829. *
  6830. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6831. * for more information on these.
  6832. *
  6833. * Additional options, for internal needs:
  6834. *
  6835. * - `chunkSize` - size of generated data chunks (16K by default)
  6836. * - `raw` (Boolean) - do raw inflate
  6837. * - `to` (String) - if equal to 'string', then result will be converted
  6838. * from utf8 to utf16 (javascript) string. When string output requested,
  6839. * chunk length can differ from `chunkSize`, depending on content.
  6840. *
  6841. * By default, when no options set, autodetect deflate/gzip data format via
  6842. * wrapper header.
  6843. *
  6844. * ##### Example:
  6845. *
  6846. * ```javascript
  6847. * var pako = require('pako')
  6848. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  6849. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  6850. *
  6851. * var inflate = new pako.Inflate({ level: 3});
  6852. *
  6853. * inflate.push(chunk1, false);
  6854. * inflate.push(chunk2, true); // true -> last chunk
  6855. *
  6856. * if (inflate.err) { throw new Error(inflate.err); }
  6857. *
  6858. * console.log(inflate.result);
  6859. * ```
  6860. **/
  6861. function Inflate(options) {
  6862. if (!(this instanceof Inflate)) return new Inflate(options);
  6863. this.options = utils.assign({
  6864. chunkSize: 16384,
  6865. windowBits: 0,
  6866. to: ''
  6867. }, options || {});
  6868. var opt = this.options;
  6869. // Force window size for `raw` data, if not set directly,
  6870. // because we have no header for autodetect.
  6871. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  6872. opt.windowBits = -opt.windowBits;
  6873. if (opt.windowBits === 0) { opt.windowBits = -15; }
  6874. }
  6875. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  6876. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  6877. !(options && options.windowBits)) {
  6878. opt.windowBits += 32;
  6879. }
  6880. // Gzip header has no info about windows size, we can do autodetect only
  6881. // for deflate. So, if window size not set, force it to max when gzip possible
  6882. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  6883. // bit 3 (16) -> gzipped data
  6884. // bit 4 (32) -> autodetect gzip/deflate
  6885. if ((opt.windowBits & 15) === 0) {
  6886. opt.windowBits |= 15;
  6887. }
  6888. }
  6889. this.err = 0; // error code, if happens (0 = Z_OK)
  6890. this.msg = ''; // error message
  6891. this.ended = false; // used to avoid multiple onEnd() calls
  6892. this.chunks = []; // chunks of compressed data
  6893. this.strm = new ZStream();
  6894. this.strm.avail_out = 0;
  6895. var status = zlib_inflate.inflateInit2(
  6896. this.strm,
  6897. opt.windowBits
  6898. );
  6899. if (status !== c.Z_OK) {
  6900. throw new Error(msg[status]);
  6901. }
  6902. this.header = new GZheader();
  6903. zlib_inflate.inflateGetHeader(this.strm, this.header);
  6904. // Setup dictionary
  6905. if (opt.dictionary) {
  6906. // Convert data if needed
  6907. if (typeof opt.dictionary === 'string') {
  6908. opt.dictionary = strings.string2buf(opt.dictionary);
  6909. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  6910. opt.dictionary = new Uint8Array(opt.dictionary);
  6911. }
  6912. if (opt.raw) { //In raw mode we need to set the dictionary early
  6913. status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
  6914. if (status !== c.Z_OK) {
  6915. throw new Error(msg[status]);
  6916. }
  6917. }
  6918. }
  6919. }
  6920. /**
  6921. * Inflate#push(data[, mode]) -> Boolean
  6922. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  6923. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  6924. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  6925. *
  6926. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  6927. * new output chunks. Returns `true` on success. The last data block must have
  6928. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  6929. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  6930. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  6931. *
  6932. * On fail call [[Inflate#onEnd]] with error code and return false.
  6933. *
  6934. * We strongly recommend to use `Uint8Array` on input for best speed (output
  6935. * format is detected automatically). Also, don't skip last param and always
  6936. * use the same type in your code (boolean or number). That will improve JS speed.
  6937. *
  6938. * For regular `Array`-s make sure all elements are [0..255].
  6939. *
  6940. * ##### Example
  6941. *
  6942. * ```javascript
  6943. * push(chunk, false); // push one of data chunks
  6944. * ...
  6945. * push(chunk, true); // push last chunk
  6946. * ```
  6947. **/
  6948. Inflate.prototype.push = function (data, mode) {
  6949. var strm = this.strm;
  6950. var chunkSize = this.options.chunkSize;
  6951. var dictionary = this.options.dictionary;
  6952. var status, _mode;
  6953. var next_out_utf8, tail, utf8str;
  6954. // Flag to properly process Z_BUF_ERROR on testing inflate call
  6955. // when we check that all output data was flushed.
  6956. var allowBufError = false;
  6957. if (this.ended) { return false; }
  6958. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  6959. // Convert data if needed
  6960. if (typeof data === 'string') {
  6961. // Only binary strings can be decompressed on practice
  6962. strm.input = strings.binstring2buf(data);
  6963. } else if (toString.call(data) === '[object ArrayBuffer]') {
  6964. strm.input = new Uint8Array(data);
  6965. } else {
  6966. strm.input = data;
  6967. }
  6968. strm.next_in = 0;
  6969. strm.avail_in = strm.input.length;
  6970. do {
  6971. if (strm.avail_out === 0) {
  6972. strm.output = new utils.Buf8(chunkSize);
  6973. strm.next_out = 0;
  6974. strm.avail_out = chunkSize;
  6975. }
  6976. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  6977. if (status === c.Z_NEED_DICT && dictionary) {
  6978. status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
  6979. }
  6980. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  6981. status = c.Z_OK;
  6982. allowBufError = false;
  6983. }
  6984. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  6985. this.onEnd(status);
  6986. this.ended = true;
  6987. return false;
  6988. }
  6989. if (strm.next_out) {
  6990. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  6991. if (this.options.to === 'string') {
  6992. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  6993. tail = strm.next_out - next_out_utf8;
  6994. utf8str = strings.buf2string(strm.output, next_out_utf8);
  6995. // move tail
  6996. strm.next_out = tail;
  6997. strm.avail_out = chunkSize - tail;
  6998. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  6999. this.onData(utf8str);
  7000. } else {
  7001. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  7002. }
  7003. }
  7004. }
  7005. // When no more input data, we should check that internal inflate buffers
  7006. // are flushed. The only way to do it when avail_out = 0 - run one more
  7007. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  7008. // Here we set flag to process this error properly.
  7009. //
  7010. // NOTE. Deflate does not return error in this case and does not needs such
  7011. // logic.
  7012. if (strm.avail_in === 0 && strm.avail_out === 0) {
  7013. allowBufError = true;
  7014. }
  7015. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  7016. if (status === c.Z_STREAM_END) {
  7017. _mode = c.Z_FINISH;
  7018. }
  7019. // Finalize on the last chunk.
  7020. if (_mode === c.Z_FINISH) {
  7021. status = zlib_inflate.inflateEnd(this.strm);
  7022. this.onEnd(status);
  7023. this.ended = true;
  7024. return status === c.Z_OK;
  7025. }
  7026. // callback interim results if Z_SYNC_FLUSH.
  7027. if (_mode === c.Z_SYNC_FLUSH) {
  7028. this.onEnd(c.Z_OK);
  7029. strm.avail_out = 0;
  7030. return true;
  7031. }
  7032. return true;
  7033. };
  7034. /**
  7035. * Inflate#onData(chunk) -> Void
  7036. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  7037. * on js engine support. When string output requested, each chunk
  7038. * will be string.
  7039. *
  7040. * By default, stores data blocks in `chunks[]` property and glue
  7041. * those in `onEnd`. Override this handler, if you need another behaviour.
  7042. **/
  7043. Inflate.prototype.onData = function (chunk) {
  7044. this.chunks.push(chunk);
  7045. };
  7046. /**
  7047. * Inflate#onEnd(status) -> Void
  7048. * - status (Number): inflate status. 0 (Z_OK) on success,
  7049. * other if not.
  7050. *
  7051. * Called either after you tell inflate that the input stream is
  7052. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  7053. * or if an error happened. By default - join collected chunks,
  7054. * free memory and fill `results` / `err` properties.
  7055. **/
  7056. Inflate.prototype.onEnd = function (status) {
  7057. // On success - join
  7058. if (status === c.Z_OK) {
  7059. if (this.options.to === 'string') {
  7060. // Glue & convert here, until we teach pako to send
  7061. // utf8 aligned strings to onData
  7062. this.result = this.chunks.join('');
  7063. } else {
  7064. this.result = utils.flattenChunks(this.chunks);
  7065. }
  7066. }
  7067. this.chunks = [];
  7068. this.err = status;
  7069. this.msg = this.strm.msg;
  7070. };
  7071. /**
  7072. * inflate(data[, options]) -> Uint8Array|Array|String
  7073. * - data (Uint8Array|Array|String): input data to decompress.
  7074. * - options (Object): zlib inflate options.
  7075. *
  7076. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  7077. * format via wrapper header by default. That's why we don't provide
  7078. * separate `ungzip` method.
  7079. *
  7080. * Supported options are:
  7081. *
  7082. * - windowBits
  7083. *
  7084. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  7085. * for more information.
  7086. *
  7087. * Sugar (options):
  7088. *
  7089. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  7090. * negative windowBits implicitly.
  7091. * - `to` (String) - if equal to 'string', then result will be converted
  7092. * from utf8 to utf16 (javascript) string. When string output requested,
  7093. * chunk length can differ from `chunkSize`, depending on content.
  7094. *
  7095. *
  7096. * ##### Example:
  7097. *
  7098. * ```javascript
  7099. * var pako = require('pako')
  7100. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  7101. * , output;
  7102. *
  7103. * try {
  7104. * output = pako.inflate(input);
  7105. * } catch (err)
  7106. * console.log(err);
  7107. * }
  7108. * ```
  7109. **/
  7110. function inflate(input, options) {
  7111. var inflator = new Inflate(options);
  7112. inflator.push(input, true);
  7113. // That will never happens, if you don't cheat with options :)
  7114. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  7115. return inflator.result;
  7116. }
  7117. /**
  7118. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  7119. * - data (Uint8Array|Array|String): input data to decompress.
  7120. * - options (Object): zlib inflate options.
  7121. *
  7122. * The same as [[inflate]], but creates raw data, without wrapper
  7123. * (header and adler32 crc).
  7124. **/
  7125. function inflateRaw(input, options) {
  7126. options = options || {};
  7127. options.raw = true;
  7128. return inflate(input, options);
  7129. }
  7130. /**
  7131. * ungzip(data[, options]) -> Uint8Array|Array|String
  7132. * - data (Uint8Array|Array|String): input data to decompress.
  7133. * - options (Object): zlib inflate options.
  7134. *
  7135. * Just shortcut to [[inflate]], because it autodetects format
  7136. * by header.content. Done for convenience.
  7137. **/
  7138. exports.Inflate = Inflate;
  7139. exports.inflate = inflate;
  7140. exports.inflateRaw = inflateRaw;
  7141. exports.ungzip = inflate;
  7142. }, { "./utils/common": 50, "./utils/strings": 51, "./zlib/constants": 53, "./zlib/gzheader": 56, "./zlib/inflate": 58, "./zlib/messages": 60, "./zlib/zstream": 62 }], 50: [function (require, module, exports) {
  7143. 'use strict';
  7144. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  7145. (typeof Uint16Array !== 'undefined') &&
  7146. (typeof Int32Array !== 'undefined');
  7147. function _has(obj, key) {
  7148. return Object.prototype.hasOwnProperty.call(obj, key);
  7149. }
  7150. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  7151. var sources = Array.prototype.slice.call(arguments, 1);
  7152. while (sources.length) {
  7153. var source = sources.shift();
  7154. if (!source) { continue; }
  7155. if (typeof source !== 'object') {
  7156. throw new TypeError(source + 'must be non-object');
  7157. }
  7158. for (var p in source) {
  7159. if (_has(source, p)) {
  7160. obj[p] = source[p];
  7161. }
  7162. }
  7163. }
  7164. return obj;
  7165. };
  7166. // reduce buffer size, avoiding mem copy
  7167. exports.shrinkBuf = function (buf, size) {
  7168. if (buf.length === size) { return buf; }
  7169. if (buf.subarray) { return buf.subarray(0, size); }
  7170. buf.length = size;
  7171. return buf;
  7172. };
  7173. var fnTyped = {
  7174. arraySet: function (dest, src, src_offs, len, dest_offs) {
  7175. if (src.subarray && dest.subarray) {
  7176. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  7177. return;
  7178. }
  7179. // Fallback to ordinary array
  7180. for (var i = 0; i < len; i++) {
  7181. dest[dest_offs + i] = src[src_offs + i];
  7182. }
  7183. },
  7184. // Join array of chunks to single array.
  7185. flattenChunks: function (chunks) {
  7186. var i, l, len, pos, chunk, result;
  7187. // calculate data length
  7188. len = 0;
  7189. for (i = 0, l = chunks.length; i < l; i++) {
  7190. len += chunks[i].length;
  7191. }
  7192. // join chunks
  7193. result = new Uint8Array(len);
  7194. pos = 0;
  7195. for (i = 0, l = chunks.length; i < l; i++) {
  7196. chunk = chunks[i];
  7197. result.set(chunk, pos);
  7198. pos += chunk.length;
  7199. }
  7200. return result;
  7201. }
  7202. };
  7203. var fnUntyped = {
  7204. arraySet: function (dest, src, src_offs, len, dest_offs) {
  7205. for (var i = 0; i < len; i++) {
  7206. dest[dest_offs + i] = src[src_offs + i];
  7207. }
  7208. },
  7209. // Join array of chunks to single array.
  7210. flattenChunks: function (chunks) {
  7211. return [].concat.apply([], chunks);
  7212. }
  7213. };
  7214. // Enable/Disable typed arrays use, for testing
  7215. //
  7216. exports.setTyped = function (on) {
  7217. if (on) {
  7218. exports.Buf8 = Uint8Array;
  7219. exports.Buf16 = Uint16Array;
  7220. exports.Buf32 = Int32Array;
  7221. exports.assign(exports, fnTyped);
  7222. } else {
  7223. exports.Buf8 = Array;
  7224. exports.Buf16 = Array;
  7225. exports.Buf32 = Array;
  7226. exports.assign(exports, fnUntyped);
  7227. }
  7228. };
  7229. exports.setTyped(TYPED_OK);
  7230. }, {}], 51: [function (require, module, exports) {
  7231. // String encode/decode helpers
  7232. 'use strict';
  7233. var utils = require('./common');
  7234. // Quick check if we can use fast array to bin string conversion
  7235. //
  7236. // - apply(Array) can fail on Android 2.2
  7237. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  7238. //
  7239. var STR_APPLY_OK = true;
  7240. var STR_APPLY_UIA_OK = true;
  7241. try { String.fromCharCode.apply(null, [0]); } catch (__) { STR_APPLY_OK = false; }
  7242. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  7243. // Table with utf8 lengths (calculated by first byte of sequence)
  7244. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  7245. // because max possible codepoint is 0x10ffff
  7246. var _utf8len = new utils.Buf8(256);
  7247. for (var q = 0; q < 256; q++) {
  7248. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  7249. }
  7250. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  7251. // convert string to array (typed, when possible)
  7252. exports.string2buf = function (str) {
  7253. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  7254. // count binary size
  7255. for (m_pos = 0; m_pos < str_len; m_pos++) {
  7256. c = str.charCodeAt(m_pos);
  7257. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  7258. c2 = str.charCodeAt(m_pos + 1);
  7259. if ((c2 & 0xfc00) === 0xdc00) {
  7260. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  7261. m_pos++;
  7262. }
  7263. }
  7264. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  7265. }
  7266. // allocate buffer
  7267. buf = new utils.Buf8(buf_len);
  7268. // convert
  7269. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  7270. c = str.charCodeAt(m_pos);
  7271. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  7272. c2 = str.charCodeAt(m_pos + 1);
  7273. if ((c2 & 0xfc00) === 0xdc00) {
  7274. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  7275. m_pos++;
  7276. }
  7277. }
  7278. if (c < 0x80) {
  7279. /* one byte */
  7280. buf[i++] = c;
  7281. } else if (c < 0x800) {
  7282. /* two bytes */
  7283. buf[i++] = 0xC0 | (c >>> 6);
  7284. buf[i++] = 0x80 | (c & 0x3f);
  7285. } else if (c < 0x10000) {
  7286. /* three bytes */
  7287. buf[i++] = 0xE0 | (c >>> 12);
  7288. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  7289. buf[i++] = 0x80 | (c & 0x3f);
  7290. } else {
  7291. /* four bytes */
  7292. buf[i++] = 0xf0 | (c >>> 18);
  7293. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  7294. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  7295. buf[i++] = 0x80 | (c & 0x3f);
  7296. }
  7297. }
  7298. return buf;
  7299. };
  7300. // Helper (used in 2 places)
  7301. function buf2binstring(buf, len) {
  7302. // On Chrome, the arguments in a function call that are allowed is `65534`.
  7303. // If the length of the buffer is smaller than that, we can use this optimization,
  7304. // otherwise we will take a slower path.
  7305. if (len < 65534) {
  7306. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  7307. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  7308. }
  7309. }
  7310. var result = '';
  7311. for (var i = 0; i < len; i++) {
  7312. result += String.fromCharCode(buf[i]);
  7313. }
  7314. return result;
  7315. }
  7316. // Convert byte array to binary string
  7317. exports.buf2binstring = function (buf) {
  7318. return buf2binstring(buf, buf.length);
  7319. };
  7320. // Convert binary string (typed, when possible)
  7321. exports.binstring2buf = function (str) {
  7322. var buf = new utils.Buf8(str.length);
  7323. for (var i = 0, len = buf.length; i < len; i++) {
  7324. buf[i] = str.charCodeAt(i);
  7325. }
  7326. return buf;
  7327. };
  7328. // convert array to string
  7329. exports.buf2string = function (buf, max) {
  7330. var i, out, c, c_len;
  7331. var len = max || buf.length;
  7332. // Reserve max possible length (2 words per char)
  7333. // NB: by unknown reasons, Array is significantly faster for
  7334. // String.fromCharCode.apply than Uint16Array.
  7335. var utf16buf = new Array(len * 2);
  7336. for (out = 0, i = 0; i < len;) {
  7337. c = buf[i++];
  7338. // quick process ascii
  7339. if (c < 0x80) { utf16buf[out++] = c; continue; }
  7340. c_len = _utf8len[c];
  7341. // skip 5 & 6 byte codes
  7342. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  7343. // apply mask on first byte
  7344. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  7345. // join the rest
  7346. while (c_len > 1 && i < len) {
  7347. c = (c << 6) | (buf[i++] & 0x3f);
  7348. c_len--;
  7349. }
  7350. // terminated by end of string?
  7351. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  7352. if (c < 0x10000) {
  7353. utf16buf[out++] = c;
  7354. } else {
  7355. c -= 0x10000;
  7356. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  7357. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  7358. }
  7359. }
  7360. return buf2binstring(utf16buf, out);
  7361. };
  7362. // Calculate max possible position in utf8 buffer,
  7363. // that will not break sequence. If that's not possible
  7364. // - (very small limits) return max size as is.
  7365. //
  7366. // buf[] - utf8 bytes array
  7367. // max - length limit (mandatory);
  7368. exports.utf8border = function (buf, max) {
  7369. var pos;
  7370. max = max || buf.length;
  7371. if (max > buf.length) { max = buf.length; }
  7372. // go back from last position, until start of sequence found
  7373. pos = max - 1;
  7374. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  7375. // Very small and broken sequence,
  7376. // return max, because we should return something anyway.
  7377. if (pos < 0) { return max; }
  7378. // If we came to start of buffer - that means buffer is too small,
  7379. // return max too.
  7380. if (pos === 0) { return max; }
  7381. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  7382. };
  7383. }, { "./common": 50 }], 52: [function (require, module, exports) {
  7384. 'use strict';
  7385. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  7386. // It isn't worth it to make additional optimizations as in original.
  7387. // Small size is preferable.
  7388. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7389. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7390. //
  7391. // This software is provided 'as-is', without any express or implied
  7392. // warranty. In no event will the authors be held liable for any damages
  7393. // arising from the use of this software.
  7394. //
  7395. // Permission is granted to anyone to use this software for any purpose,
  7396. // including commercial applications, and to alter it and redistribute it
  7397. // freely, subject to the following restrictions:
  7398. //
  7399. // 1. The origin of this software must not be misrepresented; you must not
  7400. // claim that you wrote the original software. If you use this software
  7401. // in a product, an acknowledgment in the product documentation would be
  7402. // appreciated but is not required.
  7403. // 2. Altered source versions must be plainly marked as such, and must not be
  7404. // misrepresented as being the original software.
  7405. // 3. This notice may not be removed or altered from any source distribution.
  7406. function adler32(adler, buf, len, pos) {
  7407. var s1 = (adler & 0xffff) | 0,
  7408. s2 = ((adler >>> 16) & 0xffff) | 0,
  7409. n = 0;
  7410. while (len !== 0) {
  7411. // Set limit ~ twice less than 5552, to keep
  7412. // s2 in 31-bits, because we force signed ints.
  7413. // in other case %= will fail.
  7414. n = len > 2000 ? 2000 : len;
  7415. len -= n;
  7416. do {
  7417. s1 = (s1 + buf[pos++]) | 0;
  7418. s2 = (s2 + s1) | 0;
  7419. } while (--n);
  7420. s1 %= 65521;
  7421. s2 %= 65521;
  7422. }
  7423. return (s1 | (s2 << 16)) | 0;
  7424. }
  7425. module.exports = adler32;
  7426. }, {}], 53: [function (require, module, exports) {
  7427. 'use strict';
  7428. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7429. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7430. //
  7431. // This software is provided 'as-is', without any express or implied
  7432. // warranty. In no event will the authors be held liable for any damages
  7433. // arising from the use of this software.
  7434. //
  7435. // Permission is granted to anyone to use this software for any purpose,
  7436. // including commercial applications, and to alter it and redistribute it
  7437. // freely, subject to the following restrictions:
  7438. //
  7439. // 1. The origin of this software must not be misrepresented; you must not
  7440. // claim that you wrote the original software. If you use this software
  7441. // in a product, an acknowledgment in the product documentation would be
  7442. // appreciated but is not required.
  7443. // 2. Altered source versions must be plainly marked as such, and must not be
  7444. // misrepresented as being the original software.
  7445. // 3. This notice may not be removed or altered from any source distribution.
  7446. module.exports = {
  7447. /* Allowed flush values; see deflate() and inflate() below for details */
  7448. Z_NO_FLUSH: 0,
  7449. Z_PARTIAL_FLUSH: 1,
  7450. Z_SYNC_FLUSH: 2,
  7451. Z_FULL_FLUSH: 3,
  7452. Z_FINISH: 4,
  7453. Z_BLOCK: 5,
  7454. Z_TREES: 6,
  7455. /* Return codes for the compression/decompression functions. Negative values
  7456. * are errors, positive values are used for special but normal events.
  7457. */
  7458. Z_OK: 0,
  7459. Z_STREAM_END: 1,
  7460. Z_NEED_DICT: 2,
  7461. Z_ERRNO: -1,
  7462. Z_STREAM_ERROR: -2,
  7463. Z_DATA_ERROR: -3,
  7464. //Z_MEM_ERROR: -4,
  7465. Z_BUF_ERROR: -5,
  7466. //Z_VERSION_ERROR: -6,
  7467. /* compression levels */
  7468. Z_NO_COMPRESSION: 0,
  7469. Z_BEST_SPEED: 1,
  7470. Z_BEST_COMPRESSION: 9,
  7471. Z_DEFAULT_COMPRESSION: -1,
  7472. Z_FILTERED: 1,
  7473. Z_HUFFMAN_ONLY: 2,
  7474. Z_RLE: 3,
  7475. Z_FIXED: 4,
  7476. Z_DEFAULT_STRATEGY: 0,
  7477. /* Possible values of the data_type field (though see inflate()) */
  7478. Z_BINARY: 0,
  7479. Z_TEXT: 1,
  7480. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  7481. Z_UNKNOWN: 2,
  7482. /* The deflate compression method */
  7483. Z_DEFLATED: 8
  7484. //Z_NULL: null // Use -1 or null inline, depending on var type
  7485. };
  7486. }, {}], 54: [function (require, module, exports) {
  7487. 'use strict';
  7488. // Note: we can't get significant speed boost here.
  7489. // So write code to minimize size - no pregenerated tables
  7490. // and array tools dependencies.
  7491. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7492. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7493. //
  7494. // This software is provided 'as-is', without any express or implied
  7495. // warranty. In no event will the authors be held liable for any damages
  7496. // arising from the use of this software.
  7497. //
  7498. // Permission is granted to anyone to use this software for any purpose,
  7499. // including commercial applications, and to alter it and redistribute it
  7500. // freely, subject to the following restrictions:
  7501. //
  7502. // 1. The origin of this software must not be misrepresented; you must not
  7503. // claim that you wrote the original software. If you use this software
  7504. // in a product, an acknowledgment in the product documentation would be
  7505. // appreciated but is not required.
  7506. // 2. Altered source versions must be plainly marked as such, and must not be
  7507. // misrepresented as being the original software.
  7508. // 3. This notice may not be removed or altered from any source distribution.
  7509. // Use ordinary array, since untyped makes no boost here
  7510. function makeTable() {
  7511. var c, table = [];
  7512. for (var n = 0; n < 256; n++) {
  7513. c = n;
  7514. for (var k = 0; k < 8; k++) {
  7515. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  7516. }
  7517. table[n] = c;
  7518. }
  7519. return table;
  7520. }
  7521. // Create table on load. Just 255 signed longs. Not a problem.
  7522. var crcTable = makeTable();
  7523. function crc32(crc, buf, len, pos) {
  7524. var t = crcTable,
  7525. end = pos + len;
  7526. crc ^= -1;
  7527. for (var i = pos; i < end; i++) {
  7528. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  7529. }
  7530. return (crc ^ (-1)); // >>> 0;
  7531. }
  7532. module.exports = crc32;
  7533. }, {}], 55: [function (require, module, exports) {
  7534. 'use strict';
  7535. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7536. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7537. //
  7538. // This software is provided 'as-is', without any express or implied
  7539. // warranty. In no event will the authors be held liable for any damages
  7540. // arising from the use of this software.
  7541. //
  7542. // Permission is granted to anyone to use this software for any purpose,
  7543. // including commercial applications, and to alter it and redistribute it
  7544. // freely, subject to the following restrictions:
  7545. //
  7546. // 1. The origin of this software must not be misrepresented; you must not
  7547. // claim that you wrote the original software. If you use this software
  7548. // in a product, an acknowledgment in the product documentation would be
  7549. // appreciated but is not required.
  7550. // 2. Altered source versions must be plainly marked as such, and must not be
  7551. // misrepresented as being the original software.
  7552. // 3. This notice may not be removed or altered from any source distribution.
  7553. var utils = require('../utils/common');
  7554. var trees = require('./trees');
  7555. var adler32 = require('./adler32');
  7556. var crc32 = require('./crc32');
  7557. var msg = require('./messages');
  7558. /* Public constants ==========================================================*/
  7559. /* ===========================================================================*/
  7560. /* Allowed flush values; see deflate() and inflate() below for details */
  7561. var Z_NO_FLUSH = 0;
  7562. var Z_PARTIAL_FLUSH = 1;
  7563. //var Z_SYNC_FLUSH = 2;
  7564. var Z_FULL_FLUSH = 3;
  7565. var Z_FINISH = 4;
  7566. var Z_BLOCK = 5;
  7567. //var Z_TREES = 6;
  7568. /* Return codes for the compression/decompression functions. Negative values
  7569. * are errors, positive values are used for special but normal events.
  7570. */
  7571. var Z_OK = 0;
  7572. var Z_STREAM_END = 1;
  7573. //var Z_NEED_DICT = 2;
  7574. //var Z_ERRNO = -1;
  7575. var Z_STREAM_ERROR = -2;
  7576. var Z_DATA_ERROR = -3;
  7577. //var Z_MEM_ERROR = -4;
  7578. var Z_BUF_ERROR = -5;
  7579. //var Z_VERSION_ERROR = -6;
  7580. /* compression levels */
  7581. //var Z_NO_COMPRESSION = 0;
  7582. //var Z_BEST_SPEED = 1;
  7583. //var Z_BEST_COMPRESSION = 9;
  7584. var Z_DEFAULT_COMPRESSION = -1;
  7585. var Z_FILTERED = 1;
  7586. var Z_HUFFMAN_ONLY = 2;
  7587. var Z_RLE = 3;
  7588. var Z_FIXED = 4;
  7589. var Z_DEFAULT_STRATEGY = 0;
  7590. /* Possible values of the data_type field (though see inflate()) */
  7591. //var Z_BINARY = 0;
  7592. //var Z_TEXT = 1;
  7593. //var Z_ASCII = 1; // = Z_TEXT
  7594. var Z_UNKNOWN = 2;
  7595. /* The deflate compression method */
  7596. var Z_DEFLATED = 8;
  7597. /*============================================================================*/
  7598. var MAX_MEM_LEVEL = 9;
  7599. /* Maximum value for memLevel in deflateInit2 */
  7600. var MAX_WBITS = 15;
  7601. /* 32K LZ77 window */
  7602. var DEF_MEM_LEVEL = 8;
  7603. var LENGTH_CODES = 29;
  7604. /* number of length codes, not counting the special END_BLOCK code */
  7605. var LITERALS = 256;
  7606. /* number of literal bytes 0..255 */
  7607. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  7608. /* number of Literal or Length codes, including the END_BLOCK code */
  7609. var D_CODES = 30;
  7610. /* number of distance codes */
  7611. var BL_CODES = 19;
  7612. /* number of codes used to transfer the bit lengths */
  7613. var HEAP_SIZE = 2 * L_CODES + 1;
  7614. /* maximum heap size */
  7615. var MAX_BITS = 15;
  7616. /* All codes must not exceed MAX_BITS bits */
  7617. var MIN_MATCH = 3;
  7618. var MAX_MATCH = 258;
  7619. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  7620. var PRESET_DICT = 0x20;
  7621. var INIT_STATE = 42;
  7622. var EXTRA_STATE = 69;
  7623. var NAME_STATE = 73;
  7624. var COMMENT_STATE = 91;
  7625. var HCRC_STATE = 103;
  7626. var BUSY_STATE = 113;
  7627. var FINISH_STATE = 666;
  7628. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  7629. var BS_BLOCK_DONE = 2; /* block flush performed */
  7630. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  7631. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  7632. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  7633. function err(strm, errorCode) {
  7634. strm.msg = msg[errorCode];
  7635. return errorCode;
  7636. }
  7637. function rank(f) {
  7638. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  7639. }
  7640. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  7641. /* =========================================================================
  7642. * Flush as much pending output as possible. All deflate() output goes
  7643. * through this function so some applications may wish to modify it
  7644. * to avoid allocating a large strm->output buffer and copying into it.
  7645. * (See also read_buf()).
  7646. */
  7647. function flush_pending(strm) {
  7648. var s = strm.state;
  7649. //_tr_flush_bits(s);
  7650. var len = s.pending;
  7651. if (len > strm.avail_out) {
  7652. len = strm.avail_out;
  7653. }
  7654. if (len === 0) { return; }
  7655. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  7656. strm.next_out += len;
  7657. s.pending_out += len;
  7658. strm.total_out += len;
  7659. strm.avail_out -= len;
  7660. s.pending -= len;
  7661. if (s.pending === 0) {
  7662. s.pending_out = 0;
  7663. }
  7664. }
  7665. function flush_block_only(s, last) {
  7666. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  7667. s.block_start = s.strstart;
  7668. flush_pending(s.strm);
  7669. }
  7670. function put_byte(s, b) {
  7671. s.pending_buf[s.pending++] = b;
  7672. }
  7673. /* =========================================================================
  7674. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  7675. * IN assertion: the stream state is correct and there is enough room in
  7676. * pending_buf.
  7677. */
  7678. function putShortMSB(s, b) {
  7679. // put_byte(s, (Byte)(b >> 8));
  7680. // put_byte(s, (Byte)(b & 0xff));
  7681. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  7682. s.pending_buf[s.pending++] = b & 0xff;
  7683. }
  7684. /* ===========================================================================
  7685. * Read a new buffer from the current input stream, update the adler32
  7686. * and total number of bytes read. All deflate() input goes through
  7687. * this function so some applications may wish to modify it to avoid
  7688. * allocating a large strm->input buffer and copying from it.
  7689. * (See also flush_pending()).
  7690. */
  7691. function read_buf(strm, buf, start, size) {
  7692. var len = strm.avail_in;
  7693. if (len > size) { len = size; }
  7694. if (len === 0) { return 0; }
  7695. strm.avail_in -= len;
  7696. // zmemcpy(buf, strm->next_in, len);
  7697. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  7698. if (strm.state.wrap === 1) {
  7699. strm.adler = adler32(strm.adler, buf, len, start);
  7700. }
  7701. else if (strm.state.wrap === 2) {
  7702. strm.adler = crc32(strm.adler, buf, len, start);
  7703. }
  7704. strm.next_in += len;
  7705. strm.total_in += len;
  7706. return len;
  7707. }
  7708. /* ===========================================================================
  7709. * Set match_start to the longest match starting at the given string and
  7710. * return its length. Matches shorter or equal to prev_length are discarded,
  7711. * in which case the result is equal to prev_length and match_start is
  7712. * garbage.
  7713. * IN assertions: cur_match is the head of the hash chain for the current
  7714. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  7715. * OUT assertion: the match length is not greater than s->lookahead.
  7716. */
  7717. function longest_match(s, cur_match) {
  7718. var chain_length = s.max_chain_length; /* max hash chain length */
  7719. var scan = s.strstart; /* current string */
  7720. var match; /* matched string */
  7721. var len; /* length of current match */
  7722. var best_len = s.prev_length; /* best match length so far */
  7723. var nice_match = s.nice_match; /* stop if match long enough */
  7724. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  7725. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  7726. var _win = s.window; // shortcut
  7727. var wmask = s.w_mask;
  7728. var prev = s.prev;
  7729. /* Stop when cur_match becomes <= limit. To simplify the code,
  7730. * we prevent matches with the string of window index 0.
  7731. */
  7732. var strend = s.strstart + MAX_MATCH;
  7733. var scan_end1 = _win[scan + best_len - 1];
  7734. var scan_end = _win[scan + best_len];
  7735. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  7736. * It is easy to get rid of this optimization if necessary.
  7737. */
  7738. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  7739. /* Do not waste too much time if we already have a good match: */
  7740. if (s.prev_length >= s.good_match) {
  7741. chain_length >>= 2;
  7742. }
  7743. /* Do not look for matches beyond the end of the input. This is necessary
  7744. * to make deflate deterministic.
  7745. */
  7746. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  7747. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  7748. do {
  7749. // Assert(cur_match < s->strstart, "no future");
  7750. match = cur_match;
  7751. /* Skip to next match if the match length cannot increase
  7752. * or if the match length is less than 2. Note that the checks below
  7753. * for insufficient lookahead only occur occasionally for performance
  7754. * reasons. Therefore uninitialized memory will be accessed, and
  7755. * conditional jumps will be made that depend on those values.
  7756. * However the length of the match is limited to the lookahead, so
  7757. * the output of deflate is not affected by the uninitialized values.
  7758. */
  7759. if (_win[match + best_len] !== scan_end ||
  7760. _win[match + best_len - 1] !== scan_end1 ||
  7761. _win[match] !== _win[scan] ||
  7762. _win[++match] !== _win[scan + 1]) {
  7763. continue;
  7764. }
  7765. /* The check at best_len-1 can be removed because it will be made
  7766. * again later. (This heuristic is not always a win.)
  7767. * It is not necessary to compare scan[2] and match[2] since they
  7768. * are always equal when the other bytes match, given that
  7769. * the hash keys are equal and that HASH_BITS >= 8.
  7770. */
  7771. scan += 2;
  7772. match++;
  7773. // Assert(*scan == *match, "match[2]?");
  7774. /* We check for insufficient lookahead only every 8th comparison;
  7775. * the 256th check will be made at strstart+258.
  7776. */
  7777. do {
  7778. /*jshint noempty:false*/
  7779. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7780. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7781. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7782. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7783. scan < strend);
  7784. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  7785. len = MAX_MATCH - (strend - scan);
  7786. scan = strend - MAX_MATCH;
  7787. if (len > best_len) {
  7788. s.match_start = cur_match;
  7789. best_len = len;
  7790. if (len >= nice_match) {
  7791. break;
  7792. }
  7793. scan_end1 = _win[scan + best_len - 1];
  7794. scan_end = _win[scan + best_len];
  7795. }
  7796. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  7797. if (best_len <= s.lookahead) {
  7798. return best_len;
  7799. }
  7800. return s.lookahead;
  7801. }
  7802. /* ===========================================================================
  7803. * Fill the window when the lookahead becomes insufficient.
  7804. * Updates strstart and lookahead.
  7805. *
  7806. * IN assertion: lookahead < MIN_LOOKAHEAD
  7807. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  7808. * At least one byte has been read, or avail_in == 0; reads are
  7809. * performed for at least two bytes (required for the zip translate_eol
  7810. * option -- not supported here).
  7811. */
  7812. function fill_window(s) {
  7813. var _w_size = s.w_size;
  7814. var p, n, m, more, str;
  7815. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  7816. do {
  7817. more = s.window_size - s.lookahead - s.strstart;
  7818. // JS ints have 32 bit, block below not needed
  7819. /* Deal with !@#$% 64K limit: */
  7820. //if (sizeof(int) <= 2) {
  7821. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  7822. // more = wsize;
  7823. //
  7824. // } else if (more == (unsigned)(-1)) {
  7825. // /* Very unlikely, but possible on 16 bit machine if
  7826. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  7827. // */
  7828. // more--;
  7829. // }
  7830. //}
  7831. /* If the window is almost full and there is insufficient lookahead,
  7832. * move the upper half to the lower one to make room in the upper half.
  7833. */
  7834. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  7835. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  7836. s.match_start -= _w_size;
  7837. s.strstart -= _w_size;
  7838. /* we now have strstart >= MAX_DIST */
  7839. s.block_start -= _w_size;
  7840. /* Slide the hash table (could be avoided with 32 bit values
  7841. at the expense of memory usage). We slide even when level == 0
  7842. to keep the hash table consistent if we switch back to level > 0
  7843. later. (Using level 0 permanently is not an optimal usage of
  7844. zlib, so we don't care about this pathological case.)
  7845. */
  7846. n = s.hash_size;
  7847. p = n;
  7848. do {
  7849. m = s.head[--p];
  7850. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  7851. } while (--n);
  7852. n = _w_size;
  7853. p = n;
  7854. do {
  7855. m = s.prev[--p];
  7856. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  7857. /* If n is not on any hash chain, prev[n] is garbage but
  7858. * its value will never be used.
  7859. */
  7860. } while (--n);
  7861. more += _w_size;
  7862. }
  7863. if (s.strm.avail_in === 0) {
  7864. break;
  7865. }
  7866. /* If there was no sliding:
  7867. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  7868. * more == window_size - lookahead - strstart
  7869. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  7870. * => more >= window_size - 2*WSIZE + 2
  7871. * In the BIG_MEM or MMAP case (not yet supported),
  7872. * window_size == input_size + MIN_LOOKAHEAD &&
  7873. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  7874. * Otherwise, window_size == 2*WSIZE so more >= 2.
  7875. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  7876. */
  7877. //Assert(more >= 2, "more < 2");
  7878. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  7879. s.lookahead += n;
  7880. /* Initialize the hash value now that we have some input: */
  7881. if (s.lookahead + s.insert >= MIN_MATCH) {
  7882. str = s.strstart - s.insert;
  7883. s.ins_h = s.window[str];
  7884. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  7885. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  7886. //#if MIN_MATCH != 3
  7887. // Call update_hash() MIN_MATCH-3 more times
  7888. //#endif
  7889. while (s.insert) {
  7890. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7891. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7892. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7893. s.head[s.ins_h] = str;
  7894. str++;
  7895. s.insert--;
  7896. if (s.lookahead + s.insert < MIN_MATCH) {
  7897. break;
  7898. }
  7899. }
  7900. }
  7901. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  7902. * but this is not important since only literal bytes will be emitted.
  7903. */
  7904. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  7905. /* If the WIN_INIT bytes after the end of the current data have never been
  7906. * written, then zero those bytes in order to avoid memory check reports of
  7907. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  7908. * the longest match routines. Update the high water mark for the next
  7909. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  7910. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  7911. */
  7912. // if (s.high_water < s.window_size) {
  7913. // var curr = s.strstart + s.lookahead;
  7914. // var init = 0;
  7915. //
  7916. // if (s.high_water < curr) {
  7917. // /* Previous high water mark below current data -- zero WIN_INIT
  7918. // * bytes or up to end of window, whichever is less.
  7919. // */
  7920. // init = s.window_size - curr;
  7921. // if (init > WIN_INIT)
  7922. // init = WIN_INIT;
  7923. // zmemzero(s->window + curr, (unsigned)init);
  7924. // s->high_water = curr + init;
  7925. // }
  7926. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  7927. // /* High water mark at or above current data, but below current data
  7928. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  7929. // * to end of window, whichever is less.
  7930. // */
  7931. // init = (ulg)curr + WIN_INIT - s->high_water;
  7932. // if (init > s->window_size - s->high_water)
  7933. // init = s->window_size - s->high_water;
  7934. // zmemzero(s->window + s->high_water, (unsigned)init);
  7935. // s->high_water += init;
  7936. // }
  7937. // }
  7938. //
  7939. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  7940. // "not enough room for search");
  7941. }
  7942. /* ===========================================================================
  7943. * Copy without compression as much as possible from the input stream, return
  7944. * the current block state.
  7945. * This function does not insert new strings in the dictionary since
  7946. * uncompressible data is probably not useful. This function is used
  7947. * only for the level=0 compression option.
  7948. * NOTE: this function should be optimized to avoid extra copying from
  7949. * window to pending_buf.
  7950. */
  7951. function deflate_stored(s, flush) {
  7952. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  7953. * to pending_buf_size, and each stored block has a 5 byte header:
  7954. */
  7955. var max_block_size = 0xffff;
  7956. if (max_block_size > s.pending_buf_size - 5) {
  7957. max_block_size = s.pending_buf_size - 5;
  7958. }
  7959. /* Copy as much as possible from input to output: */
  7960. for (; ;) {
  7961. /* Fill the window as much as possible: */
  7962. if (s.lookahead <= 1) {
  7963. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  7964. // s->block_start >= (long)s->w_size, "slide too late");
  7965. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  7966. // s.block_start >= s.w_size)) {
  7967. // throw new Error("slide too late");
  7968. // }
  7969. fill_window(s);
  7970. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  7971. return BS_NEED_MORE;
  7972. }
  7973. if (s.lookahead === 0) {
  7974. break;
  7975. }
  7976. /* flush the current block */
  7977. }
  7978. //Assert(s->block_start >= 0L, "block gone");
  7979. // if (s.block_start < 0) throw new Error("block gone");
  7980. s.strstart += s.lookahead;
  7981. s.lookahead = 0;
  7982. /* Emit a stored block if pending_buf will be full: */
  7983. var max_start = s.block_start + max_block_size;
  7984. if (s.strstart === 0 || s.strstart >= max_start) {
  7985. /* strstart == 0 is possible when wraparound on 16-bit machine */
  7986. s.lookahead = s.strstart - max_start;
  7987. s.strstart = max_start;
  7988. /*** FLUSH_BLOCK(s, 0); ***/
  7989. flush_block_only(s, false);
  7990. if (s.strm.avail_out === 0) {
  7991. return BS_NEED_MORE;
  7992. }
  7993. /***/
  7994. }
  7995. /* Flush if we may have to slide, otherwise block_start may become
  7996. * negative and the data will be gone:
  7997. */
  7998. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  7999. /*** FLUSH_BLOCK(s, 0); ***/
  8000. flush_block_only(s, false);
  8001. if (s.strm.avail_out === 0) {
  8002. return BS_NEED_MORE;
  8003. }
  8004. /***/
  8005. }
  8006. }
  8007. s.insert = 0;
  8008. if (flush === Z_FINISH) {
  8009. /*** FLUSH_BLOCK(s, 1); ***/
  8010. flush_block_only(s, true);
  8011. if (s.strm.avail_out === 0) {
  8012. return BS_FINISH_STARTED;
  8013. }
  8014. /***/
  8015. return BS_FINISH_DONE;
  8016. }
  8017. if (s.strstart > s.block_start) {
  8018. /*** FLUSH_BLOCK(s, 0); ***/
  8019. flush_block_only(s, false);
  8020. if (s.strm.avail_out === 0) {
  8021. return BS_NEED_MORE;
  8022. }
  8023. /***/
  8024. }
  8025. return BS_NEED_MORE;
  8026. }
  8027. /* ===========================================================================
  8028. * Compress as much as possible from the input stream, return the current
  8029. * block state.
  8030. * This function does not perform lazy evaluation of matches and inserts
  8031. * new strings in the dictionary only for unmatched strings or for short
  8032. * matches. It is used only for the fast compression options.
  8033. */
  8034. function deflate_fast(s, flush) {
  8035. var hash_head; /* head of the hash chain */
  8036. var bflush; /* set if current block must be flushed */
  8037. for (; ;) {
  8038. /* Make sure that we always have enough lookahead, except
  8039. * at the end of the input file. We need MAX_MATCH bytes
  8040. * for the next match, plus MIN_MATCH bytes to insert the
  8041. * string following the next match.
  8042. */
  8043. if (s.lookahead < MIN_LOOKAHEAD) {
  8044. fill_window(s);
  8045. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  8046. return BS_NEED_MORE;
  8047. }
  8048. if (s.lookahead === 0) {
  8049. break; /* flush the current block */
  8050. }
  8051. }
  8052. /* Insert the string window[strstart .. strstart+2] in the
  8053. * dictionary, and set hash_head to the head of the hash chain:
  8054. */
  8055. hash_head = 0/*NIL*/;
  8056. if (s.lookahead >= MIN_MATCH) {
  8057. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  8058. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  8059. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  8060. s.head[s.ins_h] = s.strstart;
  8061. /***/
  8062. }
  8063. /* Find the longest match, discarding those <= prev_length.
  8064. * At this point we have always match_length < MIN_MATCH
  8065. */
  8066. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  8067. /* To simplify the code, we prevent matches with the string
  8068. * of window index 0 (in particular we have to avoid a match
  8069. * of the string with itself at the start of the input file).
  8070. */
  8071. s.match_length = longest_match(s, hash_head);
  8072. /* longest_match() sets match_start */
  8073. }
  8074. if (s.match_length >= MIN_MATCH) {
  8075. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  8076. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  8077. s.match_length - MIN_MATCH, bflush); ***/
  8078. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  8079. s.lookahead -= s.match_length;
  8080. /* Insert new strings in the hash table only if the match length
  8081. * is not too large. This saves time but degrades compression.
  8082. */
  8083. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  8084. s.match_length--; /* string at strstart already in table */
  8085. do {
  8086. s.strstart++;
  8087. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  8088. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  8089. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  8090. s.head[s.ins_h] = s.strstart;
  8091. /***/
  8092. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  8093. * always MIN_MATCH bytes ahead.
  8094. */
  8095. } while (--s.match_length !== 0);
  8096. s.strstart++;
  8097. } else {
  8098. s.strstart += s.match_length;
  8099. s.match_length = 0;
  8100. s.ins_h = s.window[s.strstart];
  8101. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  8102. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  8103. //#if MIN_MATCH != 3
  8104. // Call UPDATE_HASH() MIN_MATCH-3 more times
  8105. //#endif
  8106. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  8107. * matter since it will be recomputed at next deflate call.
  8108. */
  8109. }
  8110. } else {
  8111. /* No match, output a literal byte */
  8112. //Tracevv((stderr,"%c", s.window[s.strstart]));
  8113. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  8114. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  8115. s.lookahead--;
  8116. s.strstart++;
  8117. }
  8118. if (bflush) {
  8119. /*** FLUSH_BLOCK(s, 0); ***/
  8120. flush_block_only(s, false);
  8121. if (s.strm.avail_out === 0) {
  8122. return BS_NEED_MORE;
  8123. }
  8124. /***/
  8125. }
  8126. }
  8127. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  8128. if (flush === Z_FINISH) {
  8129. /*** FLUSH_BLOCK(s, 1); ***/
  8130. flush_block_only(s, true);
  8131. if (s.strm.avail_out === 0) {
  8132. return BS_FINISH_STARTED;
  8133. }
  8134. /***/
  8135. return BS_FINISH_DONE;
  8136. }
  8137. if (s.last_lit) {
  8138. /*** FLUSH_BLOCK(s, 0); ***/
  8139. flush_block_only(s, false);
  8140. if (s.strm.avail_out === 0) {
  8141. return BS_NEED_MORE;
  8142. }
  8143. /***/
  8144. }
  8145. return BS_BLOCK_DONE;
  8146. }
  8147. /* ===========================================================================
  8148. * Same as above, but achieves better compression. We use a lazy
  8149. * evaluation for matches: a match is finally adopted only if there is
  8150. * no better match at the next window position.
  8151. */
  8152. function deflate_slow(s, flush) {
  8153. var hash_head; /* head of hash chain */
  8154. var bflush; /* set if current block must be flushed */
  8155. var max_insert;
  8156. /* Process the input block. */
  8157. for (; ;) {
  8158. /* Make sure that we always have enough lookahead, except
  8159. * at the end of the input file. We need MAX_MATCH bytes
  8160. * for the next match, plus MIN_MATCH bytes to insert the
  8161. * string following the next match.
  8162. */
  8163. if (s.lookahead < MIN_LOOKAHEAD) {
  8164. fill_window(s);
  8165. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  8166. return BS_NEED_MORE;
  8167. }
  8168. if (s.lookahead === 0) { break; } /* flush the current block */
  8169. }
  8170. /* Insert the string window[strstart .. strstart+2] in the
  8171. * dictionary, and set hash_head to the head of the hash chain:
  8172. */
  8173. hash_head = 0/*NIL*/;
  8174. if (s.lookahead >= MIN_MATCH) {
  8175. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  8176. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  8177. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  8178. s.head[s.ins_h] = s.strstart;
  8179. /***/
  8180. }
  8181. /* Find the longest match, discarding those <= prev_length.
  8182. */
  8183. s.prev_length = s.match_length;
  8184. s.prev_match = s.match_start;
  8185. s.match_length = MIN_MATCH - 1;
  8186. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  8187. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  8188. /* To simplify the code, we prevent matches with the string
  8189. * of window index 0 (in particular we have to avoid a match
  8190. * of the string with itself at the start of the input file).
  8191. */
  8192. s.match_length = longest_match(s, hash_head);
  8193. /* longest_match() sets match_start */
  8194. if (s.match_length <= 5 &&
  8195. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  8196. /* If prev_match is also MIN_MATCH, match_start is garbage
  8197. * but we will ignore the current match anyway.
  8198. */
  8199. s.match_length = MIN_MATCH - 1;
  8200. }
  8201. }
  8202. /* If there was a match at the previous step and the current
  8203. * match is not better, output the previous match:
  8204. */
  8205. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  8206. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  8207. /* Do not insert strings in hash table beyond this. */
  8208. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  8209. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  8210. s.prev_length - MIN_MATCH, bflush);***/
  8211. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  8212. /* Insert in hash table all strings up to the end of the match.
  8213. * strstart-1 and strstart are already inserted. If there is not
  8214. * enough lookahead, the last two strings are not inserted in
  8215. * the hash table.
  8216. */
  8217. s.lookahead -= s.prev_length - 1;
  8218. s.prev_length -= 2;
  8219. do {
  8220. if (++s.strstart <= max_insert) {
  8221. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  8222. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  8223. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  8224. s.head[s.ins_h] = s.strstart;
  8225. /***/
  8226. }
  8227. } while (--s.prev_length !== 0);
  8228. s.match_available = 0;
  8229. s.match_length = MIN_MATCH - 1;
  8230. s.strstart++;
  8231. if (bflush) {
  8232. /*** FLUSH_BLOCK(s, 0); ***/
  8233. flush_block_only(s, false);
  8234. if (s.strm.avail_out === 0) {
  8235. return BS_NEED_MORE;
  8236. }
  8237. /***/
  8238. }
  8239. } else if (s.match_available) {
  8240. /* If there was no match at the previous position, output a
  8241. * single literal. If there was a match but the current match
  8242. * is longer, truncate the previous match to a single literal.
  8243. */
  8244. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  8245. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  8246. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  8247. if (bflush) {
  8248. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  8249. flush_block_only(s, false);
  8250. /***/
  8251. }
  8252. s.strstart++;
  8253. s.lookahead--;
  8254. if (s.strm.avail_out === 0) {
  8255. return BS_NEED_MORE;
  8256. }
  8257. } else {
  8258. /* There is no previous match to compare with, wait for
  8259. * the next step to decide.
  8260. */
  8261. s.match_available = 1;
  8262. s.strstart++;
  8263. s.lookahead--;
  8264. }
  8265. }
  8266. //Assert (flush != Z_NO_FLUSH, "no flush?");
  8267. if (s.match_available) {
  8268. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  8269. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  8270. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  8271. s.match_available = 0;
  8272. }
  8273. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  8274. if (flush === Z_FINISH) {
  8275. /*** FLUSH_BLOCK(s, 1); ***/
  8276. flush_block_only(s, true);
  8277. if (s.strm.avail_out === 0) {
  8278. return BS_FINISH_STARTED;
  8279. }
  8280. /***/
  8281. return BS_FINISH_DONE;
  8282. }
  8283. if (s.last_lit) {
  8284. /*** FLUSH_BLOCK(s, 0); ***/
  8285. flush_block_only(s, false);
  8286. if (s.strm.avail_out === 0) {
  8287. return BS_NEED_MORE;
  8288. }
  8289. /***/
  8290. }
  8291. return BS_BLOCK_DONE;
  8292. }
  8293. /* ===========================================================================
  8294. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  8295. * one. Do not maintain a hash table. (It will be regenerated if this run of
  8296. * deflate switches away from Z_RLE.)
  8297. */
  8298. function deflate_rle(s, flush) {
  8299. var bflush; /* set if current block must be flushed */
  8300. var prev; /* byte at distance one to match */
  8301. var scan, strend; /* scan goes up to strend for length of run */
  8302. var _win = s.window;
  8303. for (; ;) {
  8304. /* Make sure that we always have enough lookahead, except
  8305. * at the end of the input file. We need MAX_MATCH bytes
  8306. * for the longest run, plus one for the unrolled loop.
  8307. */
  8308. if (s.lookahead <= MAX_MATCH) {
  8309. fill_window(s);
  8310. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  8311. return BS_NEED_MORE;
  8312. }
  8313. if (s.lookahead === 0) { break; } /* flush the current block */
  8314. }
  8315. /* See how many times the previous byte repeats */
  8316. s.match_length = 0;
  8317. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  8318. scan = s.strstart - 1;
  8319. prev = _win[scan];
  8320. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  8321. strend = s.strstart + MAX_MATCH;
  8322. do {
  8323. /*jshint noempty:false*/
  8324. } while (prev === _win[++scan] && prev === _win[++scan] &&
  8325. prev === _win[++scan] && prev === _win[++scan] &&
  8326. prev === _win[++scan] && prev === _win[++scan] &&
  8327. prev === _win[++scan] && prev === _win[++scan] &&
  8328. scan < strend);
  8329. s.match_length = MAX_MATCH - (strend - scan);
  8330. if (s.match_length > s.lookahead) {
  8331. s.match_length = s.lookahead;
  8332. }
  8333. }
  8334. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  8335. }
  8336. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  8337. if (s.match_length >= MIN_MATCH) {
  8338. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  8339. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  8340. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  8341. s.lookahead -= s.match_length;
  8342. s.strstart += s.match_length;
  8343. s.match_length = 0;
  8344. } else {
  8345. /* No match, output a literal byte */
  8346. //Tracevv((stderr,"%c", s->window[s->strstart]));
  8347. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  8348. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  8349. s.lookahead--;
  8350. s.strstart++;
  8351. }
  8352. if (bflush) {
  8353. /*** FLUSH_BLOCK(s, 0); ***/
  8354. flush_block_only(s, false);
  8355. if (s.strm.avail_out === 0) {
  8356. return BS_NEED_MORE;
  8357. }
  8358. /***/
  8359. }
  8360. }
  8361. s.insert = 0;
  8362. if (flush === Z_FINISH) {
  8363. /*** FLUSH_BLOCK(s, 1); ***/
  8364. flush_block_only(s, true);
  8365. if (s.strm.avail_out === 0) {
  8366. return BS_FINISH_STARTED;
  8367. }
  8368. /***/
  8369. return BS_FINISH_DONE;
  8370. }
  8371. if (s.last_lit) {
  8372. /*** FLUSH_BLOCK(s, 0); ***/
  8373. flush_block_only(s, false);
  8374. if (s.strm.avail_out === 0) {
  8375. return BS_NEED_MORE;
  8376. }
  8377. /***/
  8378. }
  8379. return BS_BLOCK_DONE;
  8380. }
  8381. /* ===========================================================================
  8382. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  8383. * (It will be regenerated if this run of deflate switches away from Huffman.)
  8384. */
  8385. function deflate_huff(s, flush) {
  8386. var bflush; /* set if current block must be flushed */
  8387. for (; ;) {
  8388. /* Make sure that we have a literal to write. */
  8389. if (s.lookahead === 0) {
  8390. fill_window(s);
  8391. if (s.lookahead === 0) {
  8392. if (flush === Z_NO_FLUSH) {
  8393. return BS_NEED_MORE;
  8394. }
  8395. break; /* flush the current block */
  8396. }
  8397. }
  8398. /* Output a literal byte */
  8399. s.match_length = 0;
  8400. //Tracevv((stderr,"%c", s->window[s->strstart]));
  8401. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  8402. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  8403. s.lookahead--;
  8404. s.strstart++;
  8405. if (bflush) {
  8406. /*** FLUSH_BLOCK(s, 0); ***/
  8407. flush_block_only(s, false);
  8408. if (s.strm.avail_out === 0) {
  8409. return BS_NEED_MORE;
  8410. }
  8411. /***/
  8412. }
  8413. }
  8414. s.insert = 0;
  8415. if (flush === Z_FINISH) {
  8416. /*** FLUSH_BLOCK(s, 1); ***/
  8417. flush_block_only(s, true);
  8418. if (s.strm.avail_out === 0) {
  8419. return BS_FINISH_STARTED;
  8420. }
  8421. /***/
  8422. return BS_FINISH_DONE;
  8423. }
  8424. if (s.last_lit) {
  8425. /*** FLUSH_BLOCK(s, 0); ***/
  8426. flush_block_only(s, false);
  8427. if (s.strm.avail_out === 0) {
  8428. return BS_NEED_MORE;
  8429. }
  8430. /***/
  8431. }
  8432. return BS_BLOCK_DONE;
  8433. }
  8434. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  8435. * the desired pack level (0..9). The values given below have been tuned to
  8436. * exclude worst case performance for pathological files. Better values may be
  8437. * found for specific files.
  8438. */
  8439. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  8440. this.good_length = good_length;
  8441. this.max_lazy = max_lazy;
  8442. this.nice_length = nice_length;
  8443. this.max_chain = max_chain;
  8444. this.func = func;
  8445. }
  8446. var configuration_table;
  8447. configuration_table = [
  8448. /* good lazy nice chain */
  8449. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  8450. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  8451. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  8452. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  8453. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  8454. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  8455. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  8456. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  8457. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  8458. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  8459. ];
  8460. /* ===========================================================================
  8461. * Initialize the "longest match" routines for a new zlib stream
  8462. */
  8463. function lm_init(s) {
  8464. s.window_size = 2 * s.w_size;
  8465. /*** CLEAR_HASH(s); ***/
  8466. zero(s.head); // Fill with NIL (= 0);
  8467. /* Set the default configuration parameters:
  8468. */
  8469. s.max_lazy_match = configuration_table[s.level].max_lazy;
  8470. s.good_match = configuration_table[s.level].good_length;
  8471. s.nice_match = configuration_table[s.level].nice_length;
  8472. s.max_chain_length = configuration_table[s.level].max_chain;
  8473. s.strstart = 0;
  8474. s.block_start = 0;
  8475. s.lookahead = 0;
  8476. s.insert = 0;
  8477. s.match_length = s.prev_length = MIN_MATCH - 1;
  8478. s.match_available = 0;
  8479. s.ins_h = 0;
  8480. }
  8481. function DeflateState() {
  8482. this.strm = null; /* pointer back to this zlib stream */
  8483. this.status = 0; /* as the name implies */
  8484. this.pending_buf = null; /* output still pending */
  8485. this.pending_buf_size = 0; /* size of pending_buf */
  8486. this.pending_out = 0; /* next pending byte to output to the stream */
  8487. this.pending = 0; /* nb of bytes in the pending buffer */
  8488. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8489. this.gzhead = null; /* gzip header information to write */
  8490. this.gzindex = 0; /* where in extra, name, or comment */
  8491. this.method = Z_DEFLATED; /* can only be DEFLATED */
  8492. this.last_flush = -1; /* value of flush param for previous deflate call */
  8493. this.w_size = 0; /* LZ77 window size (32K by default) */
  8494. this.w_bits = 0; /* log2(w_size) (8..16) */
  8495. this.w_mask = 0; /* w_size - 1 */
  8496. this.window = null;
  8497. /* Sliding window. Input bytes are read into the second half of the window,
  8498. * and move to the first half later to keep a dictionary of at least wSize
  8499. * bytes. With this organization, matches are limited to a distance of
  8500. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  8501. * performed with a length multiple of the block size.
  8502. */
  8503. this.window_size = 0;
  8504. /* Actual size of window: 2*wSize, except when the user input buffer
  8505. * is directly used as sliding window.
  8506. */
  8507. this.prev = null;
  8508. /* Link to older string with same hash index. To limit the size of this
  8509. * array to 64K, this link is maintained only for the last 32K strings.
  8510. * An index in this array is thus a window index modulo 32K.
  8511. */
  8512. this.head = null; /* Heads of the hash chains or NIL. */
  8513. this.ins_h = 0; /* hash index of string to be inserted */
  8514. this.hash_size = 0; /* number of elements in hash table */
  8515. this.hash_bits = 0; /* log2(hash_size) */
  8516. this.hash_mask = 0; /* hash_size-1 */
  8517. this.hash_shift = 0;
  8518. /* Number of bits by which ins_h must be shifted at each input
  8519. * step. It must be such that after MIN_MATCH steps, the oldest
  8520. * byte no longer takes part in the hash key, that is:
  8521. * hash_shift * MIN_MATCH >= hash_bits
  8522. */
  8523. this.block_start = 0;
  8524. /* Window position at the beginning of the current output block. Gets
  8525. * negative when the window is moved backwards.
  8526. */
  8527. this.match_length = 0; /* length of best match */
  8528. this.prev_match = 0; /* previous match */
  8529. this.match_available = 0; /* set if previous match exists */
  8530. this.strstart = 0; /* start of string to insert */
  8531. this.match_start = 0; /* start of matching string */
  8532. this.lookahead = 0; /* number of valid bytes ahead in window */
  8533. this.prev_length = 0;
  8534. /* Length of the best match at previous step. Matches not greater than this
  8535. * are discarded. This is used in the lazy match evaluation.
  8536. */
  8537. this.max_chain_length = 0;
  8538. /* To speed up deflation, hash chains are never searched beyond this
  8539. * length. A higher limit improves compression ratio but degrades the
  8540. * speed.
  8541. */
  8542. this.max_lazy_match = 0;
  8543. /* Attempt to find a better match only when the current match is strictly
  8544. * smaller than this value. This mechanism is used only for compression
  8545. * levels >= 4.
  8546. */
  8547. // That's alias to max_lazy_match, don't use directly
  8548. //this.max_insert_length = 0;
  8549. /* Insert new strings in the hash table only if the match length is not
  8550. * greater than this length. This saves time but degrades compression.
  8551. * max_insert_length is used only for compression levels <= 3.
  8552. */
  8553. this.level = 0; /* compression level (1..9) */
  8554. this.strategy = 0; /* favor or force Huffman coding*/
  8555. this.good_match = 0;
  8556. /* Use a faster search when the previous match is longer than this */
  8557. this.nice_match = 0; /* Stop searching when current match exceeds this */
  8558. /* used by trees.c: */
  8559. /* Didn't use ct_data typedef below to suppress compiler warning */
  8560. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  8561. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  8562. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  8563. // Use flat array of DOUBLE size, with interleaved fata,
  8564. // because JS does not support effective
  8565. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  8566. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  8567. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  8568. zero(this.dyn_ltree);
  8569. zero(this.dyn_dtree);
  8570. zero(this.bl_tree);
  8571. this.l_desc = null; /* desc. for literal tree */
  8572. this.d_desc = null; /* desc. for distance tree */
  8573. this.bl_desc = null; /* desc. for bit length tree */
  8574. //ush bl_count[MAX_BITS+1];
  8575. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  8576. /* number of codes at each bit length for an optimal tree */
  8577. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  8578. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  8579. zero(this.heap);
  8580. this.heap_len = 0; /* number of elements in the heap */
  8581. this.heap_max = 0; /* element of largest frequency */
  8582. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  8583. * The same heap array is used to build all trees.
  8584. */
  8585. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  8586. zero(this.depth);
  8587. /* Depth of each subtree used as tie breaker for trees of equal frequency
  8588. */
  8589. this.l_buf = 0; /* buffer index for literals or lengths */
  8590. this.lit_bufsize = 0;
  8591. /* Size of match buffer for literals/lengths. There are 4 reasons for
  8592. * limiting lit_bufsize to 64K:
  8593. * - frequencies can be kept in 16 bit counters
  8594. * - if compression is not successful for the first block, all input
  8595. * data is still in the window so we can still emit a stored block even
  8596. * when input comes from standard input. (This can also be done for
  8597. * all blocks if lit_bufsize is not greater than 32K.)
  8598. * - if compression is not successful for a file smaller than 64K, we can
  8599. * even emit a stored file instead of a stored block (saving 5 bytes).
  8600. * This is applicable only for zip (not gzip or zlib).
  8601. * - creating new Huffman trees less frequently may not provide fast
  8602. * adaptation to changes in the input data statistics. (Take for
  8603. * example a binary file with poorly compressible code followed by
  8604. * a highly compressible string table.) Smaller buffer sizes give
  8605. * fast adaptation but have of course the overhead of transmitting
  8606. * trees more frequently.
  8607. * - I can't count above 4
  8608. */
  8609. this.last_lit = 0; /* running index in l_buf */
  8610. this.d_buf = 0;
  8611. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  8612. * the same number of elements. To use different lengths, an extra flag
  8613. * array would be necessary.
  8614. */
  8615. this.opt_len = 0; /* bit length of current block with optimal trees */
  8616. this.static_len = 0; /* bit length of current block with static trees */
  8617. this.matches = 0; /* number of string matches in current block */
  8618. this.insert = 0; /* bytes at end of window left to insert */
  8619. this.bi_buf = 0;
  8620. /* Output buffer. bits are inserted starting at the bottom (least
  8621. * significant bits).
  8622. */
  8623. this.bi_valid = 0;
  8624. /* Number of valid bits in bi_buf. All bits above the last valid bit
  8625. * are always zero.
  8626. */
  8627. // Used for window memory init. We safely ignore it for JS. That makes
  8628. // sense only for pointers and memory check tools.
  8629. //this.high_water = 0;
  8630. /* High water mark offset in window for initialized bytes -- bytes above
  8631. * this are set to zero in order to avoid memory check warnings when
  8632. * longest match routines access bytes past the input. This is then
  8633. * updated to the new high water mark.
  8634. */
  8635. }
  8636. function deflateResetKeep(strm) {
  8637. var s;
  8638. if (!strm || !strm.state) {
  8639. return err(strm, Z_STREAM_ERROR);
  8640. }
  8641. strm.total_in = strm.total_out = 0;
  8642. strm.data_type = Z_UNKNOWN;
  8643. s = strm.state;
  8644. s.pending = 0;
  8645. s.pending_out = 0;
  8646. if (s.wrap < 0) {
  8647. s.wrap = -s.wrap;
  8648. /* was made negative by deflate(..., Z_FINISH); */
  8649. }
  8650. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  8651. strm.adler = (s.wrap === 2) ?
  8652. 0 // crc32(0, Z_NULL, 0)
  8653. :
  8654. 1; // adler32(0, Z_NULL, 0)
  8655. s.last_flush = Z_NO_FLUSH;
  8656. trees._tr_init(s);
  8657. return Z_OK;
  8658. }
  8659. function deflateReset(strm) {
  8660. var ret = deflateResetKeep(strm);
  8661. if (ret === Z_OK) {
  8662. lm_init(strm.state);
  8663. }
  8664. return ret;
  8665. }
  8666. function deflateSetHeader(strm, head) {
  8667. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8668. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  8669. strm.state.gzhead = head;
  8670. return Z_OK;
  8671. }
  8672. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  8673. if (!strm) { // === Z_NULL
  8674. return Z_STREAM_ERROR;
  8675. }
  8676. var wrap = 1;
  8677. if (level === Z_DEFAULT_COMPRESSION) {
  8678. level = 6;
  8679. }
  8680. if (windowBits < 0) { /* suppress zlib wrapper */
  8681. wrap = 0;
  8682. windowBits = -windowBits;
  8683. }
  8684. else if (windowBits > 15) {
  8685. wrap = 2; /* write gzip wrapper instead */
  8686. windowBits -= 16;
  8687. }
  8688. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  8689. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  8690. strategy < 0 || strategy > Z_FIXED) {
  8691. return err(strm, Z_STREAM_ERROR);
  8692. }
  8693. if (windowBits === 8) {
  8694. windowBits = 9;
  8695. }
  8696. /* until 256-byte window bug fixed */
  8697. var s = new DeflateState();
  8698. strm.state = s;
  8699. s.strm = strm;
  8700. s.wrap = wrap;
  8701. s.gzhead = null;
  8702. s.w_bits = windowBits;
  8703. s.w_size = 1 << s.w_bits;
  8704. s.w_mask = s.w_size - 1;
  8705. s.hash_bits = memLevel + 7;
  8706. s.hash_size = 1 << s.hash_bits;
  8707. s.hash_mask = s.hash_size - 1;
  8708. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  8709. s.window = new utils.Buf8(s.w_size * 2);
  8710. s.head = new utils.Buf16(s.hash_size);
  8711. s.prev = new utils.Buf16(s.w_size);
  8712. // Don't need mem init magic for JS.
  8713. //s.high_water = 0; /* nothing written to s->window yet */
  8714. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  8715. s.pending_buf_size = s.lit_bufsize * 4;
  8716. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  8717. //s->pending_buf = (uchf *) overlay;
  8718. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  8719. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  8720. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  8721. s.d_buf = 1 * s.lit_bufsize;
  8722. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  8723. s.l_buf = (1 + 2) * s.lit_bufsize;
  8724. s.level = level;
  8725. s.strategy = strategy;
  8726. s.method = method;
  8727. return deflateReset(strm);
  8728. }
  8729. function deflateInit(strm, level) {
  8730. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  8731. }
  8732. function deflate(strm, flush) {
  8733. var old_flush, s;
  8734. var beg, val; // for gzip header write only
  8735. if (!strm || !strm.state ||
  8736. flush > Z_BLOCK || flush < 0) {
  8737. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  8738. }
  8739. s = strm.state;
  8740. if (!strm.output ||
  8741. (!strm.input && strm.avail_in !== 0) ||
  8742. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  8743. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  8744. }
  8745. s.strm = strm; /* just in case */
  8746. old_flush = s.last_flush;
  8747. s.last_flush = flush;
  8748. /* Write the header */
  8749. if (s.status === INIT_STATE) {
  8750. if (s.wrap === 2) { // GZIP header
  8751. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  8752. put_byte(s, 31);
  8753. put_byte(s, 139);
  8754. put_byte(s, 8);
  8755. if (!s.gzhead) { // s->gzhead == Z_NULL
  8756. put_byte(s, 0);
  8757. put_byte(s, 0);
  8758. put_byte(s, 0);
  8759. put_byte(s, 0);
  8760. put_byte(s, 0);
  8761. put_byte(s, s.level === 9 ? 2 :
  8762. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  8763. 4 : 0));
  8764. put_byte(s, OS_CODE);
  8765. s.status = BUSY_STATE;
  8766. }
  8767. else {
  8768. put_byte(s, (s.gzhead.text ? 1 : 0) +
  8769. (s.gzhead.hcrc ? 2 : 0) +
  8770. (!s.gzhead.extra ? 0 : 4) +
  8771. (!s.gzhead.name ? 0 : 8) +
  8772. (!s.gzhead.comment ? 0 : 16)
  8773. );
  8774. put_byte(s, s.gzhead.time & 0xff);
  8775. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  8776. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  8777. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  8778. put_byte(s, s.level === 9 ? 2 :
  8779. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  8780. 4 : 0));
  8781. put_byte(s, s.gzhead.os & 0xff);
  8782. if (s.gzhead.extra && s.gzhead.extra.length) {
  8783. put_byte(s, s.gzhead.extra.length & 0xff);
  8784. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  8785. }
  8786. if (s.gzhead.hcrc) {
  8787. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  8788. }
  8789. s.gzindex = 0;
  8790. s.status = EXTRA_STATE;
  8791. }
  8792. }
  8793. else // DEFLATE header
  8794. {
  8795. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  8796. var level_flags = -1;
  8797. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  8798. level_flags = 0;
  8799. } else if (s.level < 6) {
  8800. level_flags = 1;
  8801. } else if (s.level === 6) {
  8802. level_flags = 2;
  8803. } else {
  8804. level_flags = 3;
  8805. }
  8806. header |= (level_flags << 6);
  8807. if (s.strstart !== 0) { header |= PRESET_DICT; }
  8808. header += 31 - (header % 31);
  8809. s.status = BUSY_STATE;
  8810. putShortMSB(s, header);
  8811. /* Save the adler32 of the preset dictionary: */
  8812. if (s.strstart !== 0) {
  8813. putShortMSB(s, strm.adler >>> 16);
  8814. putShortMSB(s, strm.adler & 0xffff);
  8815. }
  8816. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  8817. }
  8818. }
  8819. //#ifdef GZIP
  8820. if (s.status === EXTRA_STATE) {
  8821. if (s.gzhead.extra/* != Z_NULL*/) {
  8822. beg = s.pending; /* start of bytes to update crc */
  8823. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  8824. if (s.pending === s.pending_buf_size) {
  8825. if (s.gzhead.hcrc && s.pending > beg) {
  8826. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8827. }
  8828. flush_pending(strm);
  8829. beg = s.pending;
  8830. if (s.pending === s.pending_buf_size) {
  8831. break;
  8832. }
  8833. }
  8834. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  8835. s.gzindex++;
  8836. }
  8837. if (s.gzhead.hcrc && s.pending > beg) {
  8838. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8839. }
  8840. if (s.gzindex === s.gzhead.extra.length) {
  8841. s.gzindex = 0;
  8842. s.status = NAME_STATE;
  8843. }
  8844. }
  8845. else {
  8846. s.status = NAME_STATE;
  8847. }
  8848. }
  8849. if (s.status === NAME_STATE) {
  8850. if (s.gzhead.name/* != Z_NULL*/) {
  8851. beg = s.pending; /* start of bytes to update crc */
  8852. //int val;
  8853. do {
  8854. if (s.pending === s.pending_buf_size) {
  8855. if (s.gzhead.hcrc && s.pending > beg) {
  8856. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8857. }
  8858. flush_pending(strm);
  8859. beg = s.pending;
  8860. if (s.pending === s.pending_buf_size) {
  8861. val = 1;
  8862. break;
  8863. }
  8864. }
  8865. // JS specific: little magic to add zero terminator to end of string
  8866. if (s.gzindex < s.gzhead.name.length) {
  8867. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  8868. } else {
  8869. val = 0;
  8870. }
  8871. put_byte(s, val);
  8872. } while (val !== 0);
  8873. if (s.gzhead.hcrc && s.pending > beg) {
  8874. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8875. }
  8876. if (val === 0) {
  8877. s.gzindex = 0;
  8878. s.status = COMMENT_STATE;
  8879. }
  8880. }
  8881. else {
  8882. s.status = COMMENT_STATE;
  8883. }
  8884. }
  8885. if (s.status === COMMENT_STATE) {
  8886. if (s.gzhead.comment/* != Z_NULL*/) {
  8887. beg = s.pending; /* start of bytes to update crc */
  8888. //int val;
  8889. do {
  8890. if (s.pending === s.pending_buf_size) {
  8891. if (s.gzhead.hcrc && s.pending > beg) {
  8892. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8893. }
  8894. flush_pending(strm);
  8895. beg = s.pending;
  8896. if (s.pending === s.pending_buf_size) {
  8897. val = 1;
  8898. break;
  8899. }
  8900. }
  8901. // JS specific: little magic to add zero terminator to end of string
  8902. if (s.gzindex < s.gzhead.comment.length) {
  8903. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  8904. } else {
  8905. val = 0;
  8906. }
  8907. put_byte(s, val);
  8908. } while (val !== 0);
  8909. if (s.gzhead.hcrc && s.pending > beg) {
  8910. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8911. }
  8912. if (val === 0) {
  8913. s.status = HCRC_STATE;
  8914. }
  8915. }
  8916. else {
  8917. s.status = HCRC_STATE;
  8918. }
  8919. }
  8920. if (s.status === HCRC_STATE) {
  8921. if (s.gzhead.hcrc) {
  8922. if (s.pending + 2 > s.pending_buf_size) {
  8923. flush_pending(strm);
  8924. }
  8925. if (s.pending + 2 <= s.pending_buf_size) {
  8926. put_byte(s, strm.adler & 0xff);
  8927. put_byte(s, (strm.adler >> 8) & 0xff);
  8928. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  8929. s.status = BUSY_STATE;
  8930. }
  8931. }
  8932. else {
  8933. s.status = BUSY_STATE;
  8934. }
  8935. }
  8936. //#endif
  8937. /* Flush as much pending output as possible */
  8938. if (s.pending !== 0) {
  8939. flush_pending(strm);
  8940. if (strm.avail_out === 0) {
  8941. /* Since avail_out is 0, deflate will be called again with
  8942. * more output space, but possibly with both pending and
  8943. * avail_in equal to zero. There won't be anything to do,
  8944. * but this is not an error situation so make sure we
  8945. * return OK instead of BUF_ERROR at next call of deflate:
  8946. */
  8947. s.last_flush = -1;
  8948. return Z_OK;
  8949. }
  8950. /* Make sure there is something to do and avoid duplicate consecutive
  8951. * flushes. For repeated and useless calls with Z_FINISH, we keep
  8952. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  8953. */
  8954. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  8955. flush !== Z_FINISH) {
  8956. return err(strm, Z_BUF_ERROR);
  8957. }
  8958. /* User must not provide more input after the first FINISH: */
  8959. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  8960. return err(strm, Z_BUF_ERROR);
  8961. }
  8962. /* Start a new block or continue the current one.
  8963. */
  8964. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  8965. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  8966. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  8967. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  8968. configuration_table[s.level].func(s, flush));
  8969. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  8970. s.status = FINISH_STATE;
  8971. }
  8972. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  8973. if (strm.avail_out === 0) {
  8974. s.last_flush = -1;
  8975. /* avoid BUF_ERROR next call, see above */
  8976. }
  8977. return Z_OK;
  8978. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  8979. * of deflate should use the same flush parameter to make sure
  8980. * that the flush is complete. So we don't have to output an
  8981. * empty block here, this will be done at next call. This also
  8982. * ensures that for a very small output buffer, we emit at most
  8983. * one empty block.
  8984. */
  8985. }
  8986. if (bstate === BS_BLOCK_DONE) {
  8987. if (flush === Z_PARTIAL_FLUSH) {
  8988. trees._tr_align(s);
  8989. }
  8990. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  8991. trees._tr_stored_block(s, 0, 0, false);
  8992. /* For a full flush, this empty block will be recognized
  8993. * as a special marker by inflate_sync().
  8994. */
  8995. if (flush === Z_FULL_FLUSH) {
  8996. /*** CLEAR_HASH(s); ***/ /* forget history */
  8997. zero(s.head); // Fill with NIL (= 0);
  8998. if (s.lookahead === 0) {
  8999. s.strstart = 0;
  9000. s.block_start = 0;
  9001. s.insert = 0;
  9002. }
  9003. }
  9004. }
  9005. flush_pending(strm);
  9006. if (strm.avail_out === 0) {
  9007. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  9008. return Z_OK;
  9009. }
  9010. }
  9011. }
  9012. //Assert(strm->avail_out > 0, "bug2");
  9013. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  9014. if (flush !== Z_FINISH) { return Z_OK; }
  9015. if (s.wrap <= 0) { return Z_STREAM_END; }
  9016. /* Write the trailer */
  9017. if (s.wrap === 2) {
  9018. put_byte(s, strm.adler & 0xff);
  9019. put_byte(s, (strm.adler >> 8) & 0xff);
  9020. put_byte(s, (strm.adler >> 16) & 0xff);
  9021. put_byte(s, (strm.adler >> 24) & 0xff);
  9022. put_byte(s, strm.total_in & 0xff);
  9023. put_byte(s, (strm.total_in >> 8) & 0xff);
  9024. put_byte(s, (strm.total_in >> 16) & 0xff);
  9025. put_byte(s, (strm.total_in >> 24) & 0xff);
  9026. }
  9027. else {
  9028. putShortMSB(s, strm.adler >>> 16);
  9029. putShortMSB(s, strm.adler & 0xffff);
  9030. }
  9031. flush_pending(strm);
  9032. /* If avail_out is zero, the application will call deflate again
  9033. * to flush the rest.
  9034. */
  9035. if (s.wrap > 0) { s.wrap = -s.wrap; }
  9036. /* write the trailer only once! */
  9037. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  9038. }
  9039. function deflateEnd(strm) {
  9040. var status;
  9041. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  9042. return Z_STREAM_ERROR;
  9043. }
  9044. status = strm.state.status;
  9045. if (status !== INIT_STATE &&
  9046. status !== EXTRA_STATE &&
  9047. status !== NAME_STATE &&
  9048. status !== COMMENT_STATE &&
  9049. status !== HCRC_STATE &&
  9050. status !== BUSY_STATE &&
  9051. status !== FINISH_STATE
  9052. ) {
  9053. return err(strm, Z_STREAM_ERROR);
  9054. }
  9055. strm.state = null;
  9056. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  9057. }
  9058. /* =========================================================================
  9059. * Initializes the compression dictionary from the given byte
  9060. * sequence without producing any compressed output.
  9061. */
  9062. function deflateSetDictionary(strm, dictionary) {
  9063. var dictLength = dictionary.length;
  9064. var s;
  9065. var str, n;
  9066. var wrap;
  9067. var avail;
  9068. var next;
  9069. var input;
  9070. var tmpDict;
  9071. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  9072. return Z_STREAM_ERROR;
  9073. }
  9074. s = strm.state;
  9075. wrap = s.wrap;
  9076. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  9077. return Z_STREAM_ERROR;
  9078. }
  9079. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  9080. if (wrap === 1) {
  9081. /* adler32(strm->adler, dictionary, dictLength); */
  9082. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  9083. }
  9084. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  9085. /* if dictionary would fill window, just replace the history */
  9086. if (dictLength >= s.w_size) {
  9087. if (wrap === 0) { /* already empty otherwise */
  9088. /*** CLEAR_HASH(s); ***/
  9089. zero(s.head); // Fill with NIL (= 0);
  9090. s.strstart = 0;
  9091. s.block_start = 0;
  9092. s.insert = 0;
  9093. }
  9094. /* use the tail */
  9095. // dictionary = dictionary.slice(dictLength - s.w_size);
  9096. tmpDict = new utils.Buf8(s.w_size);
  9097. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  9098. dictionary = tmpDict;
  9099. dictLength = s.w_size;
  9100. }
  9101. /* insert dictionary into window and hash */
  9102. avail = strm.avail_in;
  9103. next = strm.next_in;
  9104. input = strm.input;
  9105. strm.avail_in = dictLength;
  9106. strm.next_in = 0;
  9107. strm.input = dictionary;
  9108. fill_window(s);
  9109. while (s.lookahead >= MIN_MATCH) {
  9110. str = s.strstart;
  9111. n = s.lookahead - (MIN_MATCH - 1);
  9112. do {
  9113. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  9114. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  9115. s.prev[str & s.w_mask] = s.head[s.ins_h];
  9116. s.head[s.ins_h] = str;
  9117. str++;
  9118. } while (--n);
  9119. s.strstart = str;
  9120. s.lookahead = MIN_MATCH - 1;
  9121. fill_window(s);
  9122. }
  9123. s.strstart += s.lookahead;
  9124. s.block_start = s.strstart;
  9125. s.insert = s.lookahead;
  9126. s.lookahead = 0;
  9127. s.match_length = s.prev_length = MIN_MATCH - 1;
  9128. s.match_available = 0;
  9129. strm.next_in = next;
  9130. strm.input = input;
  9131. strm.avail_in = avail;
  9132. s.wrap = wrap;
  9133. return Z_OK;
  9134. }
  9135. exports.deflateInit = deflateInit;
  9136. exports.deflateInit2 = deflateInit2;
  9137. exports.deflateReset = deflateReset;
  9138. exports.deflateResetKeep = deflateResetKeep;
  9139. exports.deflateSetHeader = deflateSetHeader;
  9140. exports.deflate = deflate;
  9141. exports.deflateEnd = deflateEnd;
  9142. exports.deflateSetDictionary = deflateSetDictionary;
  9143. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  9144. /* Not implemented
  9145. exports.deflateBound = deflateBound;
  9146. exports.deflateCopy = deflateCopy;
  9147. exports.deflateParams = deflateParams;
  9148. exports.deflatePending = deflatePending;
  9149. exports.deflatePrime = deflatePrime;
  9150. exports.deflateTune = deflateTune;
  9151. */
  9152. }, { "../utils/common": 50, "./adler32": 52, "./crc32": 54, "./messages": 60, "./trees": 61 }], 56: [function (require, module, exports) {
  9153. 'use strict';
  9154. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9155. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9156. //
  9157. // This software is provided 'as-is', without any express or implied
  9158. // warranty. In no event will the authors be held liable for any damages
  9159. // arising from the use of this software.
  9160. //
  9161. // Permission is granted to anyone to use this software for any purpose,
  9162. // including commercial applications, and to alter it and redistribute it
  9163. // freely, subject to the following restrictions:
  9164. //
  9165. // 1. The origin of this software must not be misrepresented; you must not
  9166. // claim that you wrote the original software. If you use this software
  9167. // in a product, an acknowledgment in the product documentation would be
  9168. // appreciated but is not required.
  9169. // 2. Altered source versions must be plainly marked as such, and must not be
  9170. // misrepresented as being the original software.
  9171. // 3. This notice may not be removed or altered from any source distribution.
  9172. function GZheader() {
  9173. /* true if compressed data believed to be text */
  9174. this.text = 0;
  9175. /* modification time */
  9176. this.time = 0;
  9177. /* extra flags (not used when writing a gzip file) */
  9178. this.xflags = 0;
  9179. /* operating system */
  9180. this.os = 0;
  9181. /* pointer to extra field or Z_NULL if none */
  9182. this.extra = null;
  9183. /* extra field length (valid if extra != Z_NULL) */
  9184. this.extra_len = 0; // Actually, we don't need it in JS,
  9185. // but leave for few code modifications
  9186. //
  9187. // Setup limits is not necessary because in js we should not preallocate memory
  9188. // for inflate use constant limit in 65536 bytes
  9189. //
  9190. /* space at extra (only when reading header) */
  9191. // this.extra_max = 0;
  9192. /* pointer to zero-terminated file name or Z_NULL */
  9193. this.name = '';
  9194. /* space at name (only when reading header) */
  9195. // this.name_max = 0;
  9196. /* pointer to zero-terminated comment or Z_NULL */
  9197. this.comment = '';
  9198. /* space at comment (only when reading header) */
  9199. // this.comm_max = 0;
  9200. /* true if there was or will be a header crc */
  9201. this.hcrc = 0;
  9202. /* true when done reading gzip header (not used when writing a gzip file) */
  9203. this.done = false;
  9204. }
  9205. module.exports = GZheader;
  9206. }, {}], 57: [function (require, module, exports) {
  9207. 'use strict';
  9208. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9209. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9210. //
  9211. // This software is provided 'as-is', without any express or implied
  9212. // warranty. In no event will the authors be held liable for any damages
  9213. // arising from the use of this software.
  9214. //
  9215. // Permission is granted to anyone to use this software for any purpose,
  9216. // including commercial applications, and to alter it and redistribute it
  9217. // freely, subject to the following restrictions:
  9218. //
  9219. // 1. The origin of this software must not be misrepresented; you must not
  9220. // claim that you wrote the original software. If you use this software
  9221. // in a product, an acknowledgment in the product documentation would be
  9222. // appreciated but is not required.
  9223. // 2. Altered source versions must be plainly marked as such, and must not be
  9224. // misrepresented as being the original software.
  9225. // 3. This notice may not be removed or altered from any source distribution.
  9226. // See state defs from inflate.js
  9227. var BAD = 30; /* got a data error -- remain here until reset */
  9228. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  9229. /*
  9230. Decode literal, length, and distance codes and write out the resulting
  9231. literal and match bytes until either not enough input or output is
  9232. available, an end-of-block is encountered, or a data error is encountered.
  9233. When large enough input and output buffers are supplied to inflate(), for
  9234. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  9235. inflate execution time is spent in this routine.
  9236. Entry assumptions:
  9237. state.mode === LEN
  9238. strm.avail_in >= 6
  9239. strm.avail_out >= 258
  9240. start >= strm.avail_out
  9241. state.bits < 8
  9242. On return, state.mode is one of:
  9243. LEN -- ran out of enough output space or enough available input
  9244. TYPE -- reached end of block code, inflate() to interpret next block
  9245. BAD -- error in block data
  9246. Notes:
  9247. - The maximum input bits used by a length/distance pair is 15 bits for the
  9248. length code, 5 bits for the length extra, 15 bits for the distance code,
  9249. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  9250. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  9251. checking for available input while decoding.
  9252. - The maximum bytes that a single length/distance pair can output is 258
  9253. bytes, which is the maximum length that can be coded. inflate_fast()
  9254. requires strm.avail_out >= 258 for each loop to avoid checking for
  9255. output space.
  9256. */
  9257. module.exports = function inflate_fast(strm, start) {
  9258. var state;
  9259. var _in; /* local strm.input */
  9260. var last; /* have enough input while in < last */
  9261. var _out; /* local strm.output */
  9262. var beg; /* inflate()'s initial strm.output */
  9263. var end; /* while out < end, enough space available */
  9264. //#ifdef INFLATE_STRICT
  9265. var dmax; /* maximum distance from zlib header */
  9266. //#endif
  9267. var wsize; /* window size or zero if not using window */
  9268. var whave; /* valid bytes in the window */
  9269. var wnext; /* window write index */
  9270. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  9271. var s_window; /* allocated sliding window, if wsize != 0 */
  9272. var hold; /* local strm.hold */
  9273. var bits; /* local strm.bits */
  9274. var lcode; /* local strm.lencode */
  9275. var dcode; /* local strm.distcode */
  9276. var lmask; /* mask for first level of length codes */
  9277. var dmask; /* mask for first level of distance codes */
  9278. var here; /* retrieved table entry */
  9279. var op; /* code bits, operation, extra bits, or */
  9280. /* window position, window bytes to copy */
  9281. var len; /* match length, unused bytes */
  9282. var dist; /* match distance */
  9283. var from; /* where to copy match from */
  9284. var from_source;
  9285. var input, output; // JS specific, because we have no pointers
  9286. /* copy state to local variables */
  9287. state = strm.state;
  9288. //here = state.here;
  9289. _in = strm.next_in;
  9290. input = strm.input;
  9291. last = _in + (strm.avail_in - 5);
  9292. _out = strm.next_out;
  9293. output = strm.output;
  9294. beg = _out - (start - strm.avail_out);
  9295. end = _out + (strm.avail_out - 257);
  9296. //#ifdef INFLATE_STRICT
  9297. dmax = state.dmax;
  9298. //#endif
  9299. wsize = state.wsize;
  9300. whave = state.whave;
  9301. wnext = state.wnext;
  9302. s_window = state.window;
  9303. hold = state.hold;
  9304. bits = state.bits;
  9305. lcode = state.lencode;
  9306. dcode = state.distcode;
  9307. lmask = (1 << state.lenbits) - 1;
  9308. dmask = (1 << state.distbits) - 1;
  9309. /* decode literals and length/distances until end-of-block or not enough
  9310. input data or output space */
  9311. top:
  9312. do {
  9313. if (bits < 15) {
  9314. hold += input[_in++] << bits;
  9315. bits += 8;
  9316. hold += input[_in++] << bits;
  9317. bits += 8;
  9318. }
  9319. here = lcode[hold & lmask];
  9320. dolen:
  9321. for (; ;) { // Goto emulation
  9322. op = here >>> 24/*here.bits*/;
  9323. hold >>>= op;
  9324. bits -= op;
  9325. op = (here >>> 16) & 0xff/*here.op*/;
  9326. if (op === 0) { /* literal */
  9327. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9328. // "inflate: literal '%c'\n" :
  9329. // "inflate: literal 0x%02x\n", here.val));
  9330. output[_out++] = here & 0xffff/*here.val*/;
  9331. }
  9332. else if (op & 16) { /* length base */
  9333. len = here & 0xffff/*here.val*/;
  9334. op &= 15; /* number of extra bits */
  9335. if (op) {
  9336. if (bits < op) {
  9337. hold += input[_in++] << bits;
  9338. bits += 8;
  9339. }
  9340. len += hold & ((1 << op) - 1);
  9341. hold >>>= op;
  9342. bits -= op;
  9343. }
  9344. //Tracevv((stderr, "inflate: length %u\n", len));
  9345. if (bits < 15) {
  9346. hold += input[_in++] << bits;
  9347. bits += 8;
  9348. hold += input[_in++] << bits;
  9349. bits += 8;
  9350. }
  9351. here = dcode[hold & dmask];
  9352. dodist:
  9353. for (; ;) { // goto emulation
  9354. op = here >>> 24/*here.bits*/;
  9355. hold >>>= op;
  9356. bits -= op;
  9357. op = (here >>> 16) & 0xff/*here.op*/;
  9358. if (op & 16) { /* distance base */
  9359. dist = here & 0xffff/*here.val*/;
  9360. op &= 15; /* number of extra bits */
  9361. if (bits < op) {
  9362. hold += input[_in++] << bits;
  9363. bits += 8;
  9364. if (bits < op) {
  9365. hold += input[_in++] << bits;
  9366. bits += 8;
  9367. }
  9368. }
  9369. dist += hold & ((1 << op) - 1);
  9370. //#ifdef INFLATE_STRICT
  9371. if (dist > dmax) {
  9372. strm.msg = 'invalid distance too far back';
  9373. state.mode = BAD;
  9374. break top;
  9375. }
  9376. //#endif
  9377. hold >>>= op;
  9378. bits -= op;
  9379. //Tracevv((stderr, "inflate: distance %u\n", dist));
  9380. op = _out - beg; /* max distance in output */
  9381. if (dist > op) { /* see if copy from window */
  9382. op = dist - op; /* distance back in window */
  9383. if (op > whave) {
  9384. if (state.sane) {
  9385. strm.msg = 'invalid distance too far back';
  9386. state.mode = BAD;
  9387. break top;
  9388. }
  9389. // (!) This block is disabled in zlib defaults,
  9390. // don't enable it for binary compatibility
  9391. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9392. // if (len <= op - whave) {
  9393. // do {
  9394. // output[_out++] = 0;
  9395. // } while (--len);
  9396. // continue top;
  9397. // }
  9398. // len -= op - whave;
  9399. // do {
  9400. // output[_out++] = 0;
  9401. // } while (--op > whave);
  9402. // if (op === 0) {
  9403. // from = _out - dist;
  9404. // do {
  9405. // output[_out++] = output[from++];
  9406. // } while (--len);
  9407. // continue top;
  9408. // }
  9409. //#endif
  9410. }
  9411. from = 0; // window index
  9412. from_source = s_window;
  9413. if (wnext === 0) { /* very common case */
  9414. from += wsize - op;
  9415. if (op < len) { /* some from window */
  9416. len -= op;
  9417. do {
  9418. output[_out++] = s_window[from++];
  9419. } while (--op);
  9420. from = _out - dist; /* rest from output */
  9421. from_source = output;
  9422. }
  9423. }
  9424. else if (wnext < op) { /* wrap around window */
  9425. from += wsize + wnext - op;
  9426. op -= wnext;
  9427. if (op < len) { /* some from end of window */
  9428. len -= op;
  9429. do {
  9430. output[_out++] = s_window[from++];
  9431. } while (--op);
  9432. from = 0;
  9433. if (wnext < len) { /* some from start of window */
  9434. op = wnext;
  9435. len -= op;
  9436. do {
  9437. output[_out++] = s_window[from++];
  9438. } while (--op);
  9439. from = _out - dist; /* rest from output */
  9440. from_source = output;
  9441. }
  9442. }
  9443. }
  9444. else { /* contiguous in window */
  9445. from += wnext - op;
  9446. if (op < len) { /* some from window */
  9447. len -= op;
  9448. do {
  9449. output[_out++] = s_window[from++];
  9450. } while (--op);
  9451. from = _out - dist; /* rest from output */
  9452. from_source = output;
  9453. }
  9454. }
  9455. while (len > 2) {
  9456. output[_out++] = from_source[from++];
  9457. output[_out++] = from_source[from++];
  9458. output[_out++] = from_source[from++];
  9459. len -= 3;
  9460. }
  9461. if (len) {
  9462. output[_out++] = from_source[from++];
  9463. if (len > 1) {
  9464. output[_out++] = from_source[from++];
  9465. }
  9466. }
  9467. }
  9468. else {
  9469. from = _out - dist; /* copy direct from output */
  9470. do { /* minimum length is three */
  9471. output[_out++] = output[from++];
  9472. output[_out++] = output[from++];
  9473. output[_out++] = output[from++];
  9474. len -= 3;
  9475. } while (len > 2);
  9476. if (len) {
  9477. output[_out++] = output[from++];
  9478. if (len > 1) {
  9479. output[_out++] = output[from++];
  9480. }
  9481. }
  9482. }
  9483. }
  9484. else if ((op & 64) === 0) { /* 2nd level distance code */
  9485. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  9486. continue dodist;
  9487. }
  9488. else {
  9489. strm.msg = 'invalid distance code';
  9490. state.mode = BAD;
  9491. break top;
  9492. }
  9493. break; // need to emulate goto via "continue"
  9494. }
  9495. }
  9496. else if ((op & 64) === 0) { /* 2nd level length code */
  9497. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  9498. continue dolen;
  9499. }
  9500. else if (op & 32) { /* end-of-block */
  9501. //Tracevv((stderr, "inflate: end of block\n"));
  9502. state.mode = TYPE;
  9503. break top;
  9504. }
  9505. else {
  9506. strm.msg = 'invalid literal/length code';
  9507. state.mode = BAD;
  9508. break top;
  9509. }
  9510. break; // need to emulate goto via "continue"
  9511. }
  9512. } while (_in < last && _out < end);
  9513. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  9514. len = bits >> 3;
  9515. _in -= len;
  9516. bits -= len << 3;
  9517. hold &= (1 << bits) - 1;
  9518. /* update state and return */
  9519. strm.next_in = _in;
  9520. strm.next_out = _out;
  9521. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  9522. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  9523. state.hold = hold;
  9524. state.bits = bits;
  9525. return;
  9526. };
  9527. }, {}], 58: [function (require, module, exports) {
  9528. 'use strict';
  9529. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9530. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9531. //
  9532. // This software is provided 'as-is', without any express or implied
  9533. // warranty. In no event will the authors be held liable for any damages
  9534. // arising from the use of this software.
  9535. //
  9536. // Permission is granted to anyone to use this software for any purpose,
  9537. // including commercial applications, and to alter it and redistribute it
  9538. // freely, subject to the following restrictions:
  9539. //
  9540. // 1. The origin of this software must not be misrepresented; you must not
  9541. // claim that you wrote the original software. If you use this software
  9542. // in a product, an acknowledgment in the product documentation would be
  9543. // appreciated but is not required.
  9544. // 2. Altered source versions must be plainly marked as such, and must not be
  9545. // misrepresented as being the original software.
  9546. // 3. This notice may not be removed or altered from any source distribution.
  9547. var utils = require('../utils/common');
  9548. var adler32 = require('./adler32');
  9549. var crc32 = require('./crc32');
  9550. var inflate_fast = require('./inffast');
  9551. var inflate_table = require('./inftrees');
  9552. var CODES = 0;
  9553. var LENS = 1;
  9554. var DISTS = 2;
  9555. /* Public constants ==========================================================*/
  9556. /* ===========================================================================*/
  9557. /* Allowed flush values; see deflate() and inflate() below for details */
  9558. //var Z_NO_FLUSH = 0;
  9559. //var Z_PARTIAL_FLUSH = 1;
  9560. //var Z_SYNC_FLUSH = 2;
  9561. //var Z_FULL_FLUSH = 3;
  9562. var Z_FINISH = 4;
  9563. var Z_BLOCK = 5;
  9564. var Z_TREES = 6;
  9565. /* Return codes for the compression/decompression functions. Negative values
  9566. * are errors, positive values are used for special but normal events.
  9567. */
  9568. var Z_OK = 0;
  9569. var Z_STREAM_END = 1;
  9570. var Z_NEED_DICT = 2;
  9571. //var Z_ERRNO = -1;
  9572. var Z_STREAM_ERROR = -2;
  9573. var Z_DATA_ERROR = -3;
  9574. var Z_MEM_ERROR = -4;
  9575. var Z_BUF_ERROR = -5;
  9576. //var Z_VERSION_ERROR = -6;
  9577. /* The deflate compression method */
  9578. var Z_DEFLATED = 8;
  9579. /* STATES ====================================================================*/
  9580. /* ===========================================================================*/
  9581. var HEAD = 1; /* i: waiting for magic header */
  9582. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  9583. var TIME = 3; /* i: waiting for modification time (gzip) */
  9584. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  9585. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  9586. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  9587. var NAME = 7; /* i: waiting for end of file name (gzip) */
  9588. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  9589. var HCRC = 9; /* i: waiting for header crc (gzip) */
  9590. var DICTID = 10; /* i: waiting for dictionary check value */
  9591. var DICT = 11; /* waiting for inflateSetDictionary() call */
  9592. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  9593. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  9594. var STORED = 14; /* i: waiting for stored size (length and complement) */
  9595. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  9596. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  9597. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  9598. var LENLENS = 18; /* i: waiting for code length code lengths */
  9599. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  9600. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  9601. var LEN = 21; /* i: waiting for length/lit/eob code */
  9602. var LENEXT = 22; /* i: waiting for length extra bits */
  9603. var DIST = 23; /* i: waiting for distance code */
  9604. var DISTEXT = 24; /* i: waiting for distance extra bits */
  9605. var MATCH = 25; /* o: waiting for output space to copy string */
  9606. var LIT = 26; /* o: waiting for output space to write literal */
  9607. var CHECK = 27; /* i: waiting for 32-bit check value */
  9608. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  9609. var DONE = 29; /* finished check, done -- remain here until reset */
  9610. var BAD = 30; /* got a data error -- remain here until reset */
  9611. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  9612. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  9613. /* ===========================================================================*/
  9614. var ENOUGH_LENS = 852;
  9615. var ENOUGH_DISTS = 592;
  9616. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9617. var MAX_WBITS = 15;
  9618. /* 32K LZ77 window */
  9619. var DEF_WBITS = MAX_WBITS;
  9620. function zswap32(q) {
  9621. return (((q >>> 24) & 0xff) +
  9622. ((q >>> 8) & 0xff00) +
  9623. ((q & 0xff00) << 8) +
  9624. ((q & 0xff) << 24));
  9625. }
  9626. function InflateState() {
  9627. this.mode = 0; /* current inflate mode */
  9628. this.last = false; /* true if processing last block */
  9629. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  9630. this.havedict = false; /* true if dictionary provided */
  9631. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  9632. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  9633. this.check = 0; /* protected copy of check value */
  9634. this.total = 0; /* protected copy of output count */
  9635. // TODO: may be {}
  9636. this.head = null; /* where to save gzip header information */
  9637. /* sliding window */
  9638. this.wbits = 0; /* log base 2 of requested window size */
  9639. this.wsize = 0; /* window size or zero if not using window */
  9640. this.whave = 0; /* valid bytes in the window */
  9641. this.wnext = 0; /* window write index */
  9642. this.window = null; /* allocated sliding window, if needed */
  9643. /* bit accumulator */
  9644. this.hold = 0; /* input bit accumulator */
  9645. this.bits = 0; /* number of bits in "in" */
  9646. /* for string and stored block copying */
  9647. this.length = 0; /* literal or length of data to copy */
  9648. this.offset = 0; /* distance back to copy string from */
  9649. /* for table and code decoding */
  9650. this.extra = 0; /* extra bits needed */
  9651. /* fixed and dynamic code tables */
  9652. this.lencode = null; /* starting table for length/literal codes */
  9653. this.distcode = null; /* starting table for distance codes */
  9654. this.lenbits = 0; /* index bits for lencode */
  9655. this.distbits = 0; /* index bits for distcode */
  9656. /* dynamic table building */
  9657. this.ncode = 0; /* number of code length code lengths */
  9658. this.nlen = 0; /* number of length code lengths */
  9659. this.ndist = 0; /* number of distance code lengths */
  9660. this.have = 0; /* number of code lengths in lens[] */
  9661. this.next = null; /* next available space in codes[] */
  9662. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  9663. this.work = new utils.Buf16(288); /* work area for code table building */
  9664. /*
  9665. because we don't have pointers in js, we use lencode and distcode directly
  9666. as buffers so we don't need codes
  9667. */
  9668. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  9669. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  9670. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  9671. this.sane = 0; /* if false, allow invalid distance too far */
  9672. this.back = 0; /* bits back of last unprocessed length/lit */
  9673. this.was = 0; /* initial length of match */
  9674. }
  9675. function inflateResetKeep(strm) {
  9676. var state;
  9677. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9678. state = strm.state;
  9679. strm.total_in = strm.total_out = state.total = 0;
  9680. strm.msg = ''; /*Z_NULL*/
  9681. if (state.wrap) { /* to support ill-conceived Java test suite */
  9682. strm.adler = state.wrap & 1;
  9683. }
  9684. state.mode = HEAD;
  9685. state.last = 0;
  9686. state.havedict = 0;
  9687. state.dmax = 32768;
  9688. state.head = null/*Z_NULL*/;
  9689. state.hold = 0;
  9690. state.bits = 0;
  9691. //state.lencode = state.distcode = state.next = state.codes;
  9692. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  9693. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  9694. state.sane = 1;
  9695. state.back = -1;
  9696. //Tracev((stderr, "inflate: reset\n"));
  9697. return Z_OK;
  9698. }
  9699. function inflateReset(strm) {
  9700. var state;
  9701. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9702. state = strm.state;
  9703. state.wsize = 0;
  9704. state.whave = 0;
  9705. state.wnext = 0;
  9706. return inflateResetKeep(strm);
  9707. }
  9708. function inflateReset2(strm, windowBits) {
  9709. var wrap;
  9710. var state;
  9711. /* get the state */
  9712. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9713. state = strm.state;
  9714. /* extract wrap request from windowBits parameter */
  9715. if (windowBits < 0) {
  9716. wrap = 0;
  9717. windowBits = -windowBits;
  9718. }
  9719. else {
  9720. wrap = (windowBits >> 4) + 1;
  9721. if (windowBits < 48) {
  9722. windowBits &= 15;
  9723. }
  9724. }
  9725. /* set number of window bits, free window if different */
  9726. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  9727. return Z_STREAM_ERROR;
  9728. }
  9729. if (state.window !== null && state.wbits !== windowBits) {
  9730. state.window = null;
  9731. }
  9732. /* update state and reset the rest of it */
  9733. state.wrap = wrap;
  9734. state.wbits = windowBits;
  9735. return inflateReset(strm);
  9736. }
  9737. function inflateInit2(strm, windowBits) {
  9738. var ret;
  9739. var state;
  9740. if (!strm) { return Z_STREAM_ERROR; }
  9741. //strm.msg = Z_NULL; /* in case we return an error */
  9742. state = new InflateState();
  9743. //if (state === Z_NULL) return Z_MEM_ERROR;
  9744. //Tracev((stderr, "inflate: allocated\n"));
  9745. strm.state = state;
  9746. state.window = null/*Z_NULL*/;
  9747. ret = inflateReset2(strm, windowBits);
  9748. if (ret !== Z_OK) {
  9749. strm.state = null/*Z_NULL*/;
  9750. }
  9751. return ret;
  9752. }
  9753. function inflateInit(strm) {
  9754. return inflateInit2(strm, DEF_WBITS);
  9755. }
  9756. /*
  9757. Return state with length and distance decoding tables and index sizes set to
  9758. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  9759. If BUILDFIXED is defined, then instead this routine builds the tables the
  9760. first time it's called, and returns those tables the first time and
  9761. thereafter. This reduces the size of the code by about 2K bytes, in
  9762. exchange for a little execution time. However, BUILDFIXED should not be
  9763. used for threaded applications, since the rewriting of the tables and virgin
  9764. may not be thread-safe.
  9765. */
  9766. var virgin = true;
  9767. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  9768. function fixedtables(state) {
  9769. /* build fixed huffman tables if first call (may not be thread safe) */
  9770. if (virgin) {
  9771. var sym;
  9772. lenfix = new utils.Buf32(512);
  9773. distfix = new utils.Buf32(32);
  9774. /* literal/length table */
  9775. sym = 0;
  9776. while (sym < 144) { state.lens[sym++] = 8; }
  9777. while (sym < 256) { state.lens[sym++] = 9; }
  9778. while (sym < 280) { state.lens[sym++] = 7; }
  9779. while (sym < 288) { state.lens[sym++] = 8; }
  9780. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  9781. /* distance table */
  9782. sym = 0;
  9783. while (sym < 32) { state.lens[sym++] = 5; }
  9784. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  9785. /* do this just once */
  9786. virgin = false;
  9787. }
  9788. state.lencode = lenfix;
  9789. state.lenbits = 9;
  9790. state.distcode = distfix;
  9791. state.distbits = 5;
  9792. }
  9793. /*
  9794. Update the window with the last wsize (normally 32K) bytes written before
  9795. returning. If window does not exist yet, create it. This is only called
  9796. when a window is already in use, or when output has been written during this
  9797. inflate call, but the end of the deflate stream has not been reached yet.
  9798. It is also called to create a window for dictionary data when a dictionary
  9799. is loaded.
  9800. Providing output buffers larger than 32K to inflate() should provide a speed
  9801. advantage, since only the last 32K of output is copied to the sliding window
  9802. upon return from inflate(), and since all distances after the first 32K of
  9803. output will fall in the output data, making match copies simpler and faster.
  9804. The advantage may be dependent on the size of the processor's data caches.
  9805. */
  9806. function updatewindow(strm, src, end, copy) {
  9807. var dist;
  9808. var state = strm.state;
  9809. /* if it hasn't been done already, allocate space for the window */
  9810. if (state.window === null) {
  9811. state.wsize = 1 << state.wbits;
  9812. state.wnext = 0;
  9813. state.whave = 0;
  9814. state.window = new utils.Buf8(state.wsize);
  9815. }
  9816. /* copy state->wsize or less output bytes into the circular window */
  9817. if (copy >= state.wsize) {
  9818. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  9819. state.wnext = 0;
  9820. state.whave = state.wsize;
  9821. }
  9822. else {
  9823. dist = state.wsize - state.wnext;
  9824. if (dist > copy) {
  9825. dist = copy;
  9826. }
  9827. //zmemcpy(state->window + state->wnext, end - copy, dist);
  9828. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  9829. copy -= dist;
  9830. if (copy) {
  9831. //zmemcpy(state->window, end - copy, copy);
  9832. utils.arraySet(state.window, src, end - copy, copy, 0);
  9833. state.wnext = copy;
  9834. state.whave = state.wsize;
  9835. }
  9836. else {
  9837. state.wnext += dist;
  9838. if (state.wnext === state.wsize) { state.wnext = 0; }
  9839. if (state.whave < state.wsize) { state.whave += dist; }
  9840. }
  9841. }
  9842. return 0;
  9843. }
  9844. function inflate(strm, flush) {
  9845. var state;
  9846. var input, output; // input/output buffers
  9847. var next; /* next input INDEX */
  9848. var put; /* next output INDEX */
  9849. var have, left; /* available input and output */
  9850. var hold; /* bit buffer */
  9851. var bits; /* bits in bit buffer */
  9852. var _in, _out; /* save starting available input and output */
  9853. var copy; /* number of stored or match bytes to copy */
  9854. var from; /* where to copy match bytes from */
  9855. var from_source;
  9856. var here = 0; /* current decoding table entry */
  9857. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  9858. //var last; /* parent table entry */
  9859. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  9860. var len; /* length to copy for repeats, bits to drop */
  9861. var ret; /* return code */
  9862. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  9863. var opts;
  9864. var n; // temporary var for NEED_BITS
  9865. var order = /* permutation of code lengths */
  9866. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  9867. if (!strm || !strm.state || !strm.output ||
  9868. (!strm.input && strm.avail_in !== 0)) {
  9869. return Z_STREAM_ERROR;
  9870. }
  9871. state = strm.state;
  9872. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  9873. //--- LOAD() ---
  9874. put = strm.next_out;
  9875. output = strm.output;
  9876. left = strm.avail_out;
  9877. next = strm.next_in;
  9878. input = strm.input;
  9879. have = strm.avail_in;
  9880. hold = state.hold;
  9881. bits = state.bits;
  9882. //---
  9883. _in = have;
  9884. _out = left;
  9885. ret = Z_OK;
  9886. inf_leave: // goto emulation
  9887. for (; ;) {
  9888. switch (state.mode) {
  9889. case HEAD:
  9890. if (state.wrap === 0) {
  9891. state.mode = TYPEDO;
  9892. break;
  9893. }
  9894. //=== NEEDBITS(16);
  9895. while (bits < 16) {
  9896. if (have === 0) { break inf_leave; }
  9897. have--;
  9898. hold += input[next++] << bits;
  9899. bits += 8;
  9900. }
  9901. //===//
  9902. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  9903. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  9904. //=== CRC2(state.check, hold);
  9905. hbuf[0] = hold & 0xff;
  9906. hbuf[1] = (hold >>> 8) & 0xff;
  9907. state.check = crc32(state.check, hbuf, 2, 0);
  9908. //===//
  9909. //=== INITBITS();
  9910. hold = 0;
  9911. bits = 0;
  9912. //===//
  9913. state.mode = FLAGS;
  9914. break;
  9915. }
  9916. state.flags = 0; /* expect zlib header */
  9917. if (state.head) {
  9918. state.head.done = false;
  9919. }
  9920. if (!(state.wrap & 1) || /* check if zlib header allowed */
  9921. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  9922. strm.msg = 'incorrect header check';
  9923. state.mode = BAD;
  9924. break;
  9925. }
  9926. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  9927. strm.msg = 'unknown compression method';
  9928. state.mode = BAD;
  9929. break;
  9930. }
  9931. //--- DROPBITS(4) ---//
  9932. hold >>>= 4;
  9933. bits -= 4;
  9934. //---//
  9935. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  9936. if (state.wbits === 0) {
  9937. state.wbits = len;
  9938. }
  9939. else if (len > state.wbits) {
  9940. strm.msg = 'invalid window size';
  9941. state.mode = BAD;
  9942. break;
  9943. }
  9944. state.dmax = 1 << len;
  9945. //Tracev((stderr, "inflate: zlib header ok\n"));
  9946. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9947. state.mode = hold & 0x200 ? DICTID : TYPE;
  9948. //=== INITBITS();
  9949. hold = 0;
  9950. bits = 0;
  9951. //===//
  9952. break;
  9953. case FLAGS:
  9954. //=== NEEDBITS(16); */
  9955. while (bits < 16) {
  9956. if (have === 0) { break inf_leave; }
  9957. have--;
  9958. hold += input[next++] << bits;
  9959. bits += 8;
  9960. }
  9961. //===//
  9962. state.flags = hold;
  9963. if ((state.flags & 0xff) !== Z_DEFLATED) {
  9964. strm.msg = 'unknown compression method';
  9965. state.mode = BAD;
  9966. break;
  9967. }
  9968. if (state.flags & 0xe000) {
  9969. strm.msg = 'unknown header flags set';
  9970. state.mode = BAD;
  9971. break;
  9972. }
  9973. if (state.head) {
  9974. state.head.text = ((hold >> 8) & 1);
  9975. }
  9976. if (state.flags & 0x0200) {
  9977. //=== CRC2(state.check, hold);
  9978. hbuf[0] = hold & 0xff;
  9979. hbuf[1] = (hold >>> 8) & 0xff;
  9980. state.check = crc32(state.check, hbuf, 2, 0);
  9981. //===//
  9982. }
  9983. //=== INITBITS();
  9984. hold = 0;
  9985. bits = 0;
  9986. //===//
  9987. state.mode = TIME;
  9988. /* falls through */
  9989. case TIME:
  9990. //=== NEEDBITS(32); */
  9991. while (bits < 32) {
  9992. if (have === 0) { break inf_leave; }
  9993. have--;
  9994. hold += input[next++] << bits;
  9995. bits += 8;
  9996. }
  9997. //===//
  9998. if (state.head) {
  9999. state.head.time = hold;
  10000. }
  10001. if (state.flags & 0x0200) {
  10002. //=== CRC4(state.check, hold)
  10003. hbuf[0] = hold & 0xff;
  10004. hbuf[1] = (hold >>> 8) & 0xff;
  10005. hbuf[2] = (hold >>> 16) & 0xff;
  10006. hbuf[3] = (hold >>> 24) & 0xff;
  10007. state.check = crc32(state.check, hbuf, 4, 0);
  10008. //===
  10009. }
  10010. //=== INITBITS();
  10011. hold = 0;
  10012. bits = 0;
  10013. //===//
  10014. state.mode = OS;
  10015. /* falls through */
  10016. case OS:
  10017. //=== NEEDBITS(16); */
  10018. while (bits < 16) {
  10019. if (have === 0) { break inf_leave; }
  10020. have--;
  10021. hold += input[next++] << bits;
  10022. bits += 8;
  10023. }
  10024. //===//
  10025. if (state.head) {
  10026. state.head.xflags = (hold & 0xff);
  10027. state.head.os = (hold >> 8);
  10028. }
  10029. if (state.flags & 0x0200) {
  10030. //=== CRC2(state.check, hold);
  10031. hbuf[0] = hold & 0xff;
  10032. hbuf[1] = (hold >>> 8) & 0xff;
  10033. state.check = crc32(state.check, hbuf, 2, 0);
  10034. //===//
  10035. }
  10036. //=== INITBITS();
  10037. hold = 0;
  10038. bits = 0;
  10039. //===//
  10040. state.mode = EXLEN;
  10041. /* falls through */
  10042. case EXLEN:
  10043. if (state.flags & 0x0400) {
  10044. //=== NEEDBITS(16); */
  10045. while (bits < 16) {
  10046. if (have === 0) { break inf_leave; }
  10047. have--;
  10048. hold += input[next++] << bits;
  10049. bits += 8;
  10050. }
  10051. //===//
  10052. state.length = hold;
  10053. if (state.head) {
  10054. state.head.extra_len = hold;
  10055. }
  10056. if (state.flags & 0x0200) {
  10057. //=== CRC2(state.check, hold);
  10058. hbuf[0] = hold & 0xff;
  10059. hbuf[1] = (hold >>> 8) & 0xff;
  10060. state.check = crc32(state.check, hbuf, 2, 0);
  10061. //===//
  10062. }
  10063. //=== INITBITS();
  10064. hold = 0;
  10065. bits = 0;
  10066. //===//
  10067. }
  10068. else if (state.head) {
  10069. state.head.extra = null/*Z_NULL*/;
  10070. }
  10071. state.mode = EXTRA;
  10072. /* falls through */
  10073. case EXTRA:
  10074. if (state.flags & 0x0400) {
  10075. copy = state.length;
  10076. if (copy > have) { copy = have; }
  10077. if (copy) {
  10078. if (state.head) {
  10079. len = state.head.extra_len - state.length;
  10080. if (!state.head.extra) {
  10081. // Use untyped array for more convenient processing later
  10082. state.head.extra = new Array(state.head.extra_len);
  10083. }
  10084. utils.arraySet(
  10085. state.head.extra,
  10086. input,
  10087. next,
  10088. // extra field is limited to 65536 bytes
  10089. // - no need for additional size check
  10090. copy,
  10091. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  10092. len
  10093. );
  10094. //zmemcpy(state.head.extra + len, next,
  10095. // len + copy > state.head.extra_max ?
  10096. // state.head.extra_max - len : copy);
  10097. }
  10098. if (state.flags & 0x0200) {
  10099. state.check = crc32(state.check, input, copy, next);
  10100. }
  10101. have -= copy;
  10102. next += copy;
  10103. state.length -= copy;
  10104. }
  10105. if (state.length) { break inf_leave; }
  10106. }
  10107. state.length = 0;
  10108. state.mode = NAME;
  10109. /* falls through */
  10110. case NAME:
  10111. if (state.flags & 0x0800) {
  10112. if (have === 0) { break inf_leave; }
  10113. copy = 0;
  10114. do {
  10115. // TODO: 2 or 1 bytes?
  10116. len = input[next + copy++];
  10117. /* use constant limit because in js we should not preallocate memory */
  10118. if (state.head && len &&
  10119. (state.length < 65536 /*state.head.name_max*/)) {
  10120. state.head.name += String.fromCharCode(len);
  10121. }
  10122. } while (len && copy < have);
  10123. if (state.flags & 0x0200) {
  10124. state.check = crc32(state.check, input, copy, next);
  10125. }
  10126. have -= copy;
  10127. next += copy;
  10128. if (len) { break inf_leave; }
  10129. }
  10130. else if (state.head) {
  10131. state.head.name = null;
  10132. }
  10133. state.length = 0;
  10134. state.mode = COMMENT;
  10135. /* falls through */
  10136. case COMMENT:
  10137. if (state.flags & 0x1000) {
  10138. if (have === 0) { break inf_leave; }
  10139. copy = 0;
  10140. do {
  10141. len = input[next + copy++];
  10142. /* use constant limit because in js we should not preallocate memory */
  10143. if (state.head && len &&
  10144. (state.length < 65536 /*state.head.comm_max*/)) {
  10145. state.head.comment += String.fromCharCode(len);
  10146. }
  10147. } while (len && copy < have);
  10148. if (state.flags & 0x0200) {
  10149. state.check = crc32(state.check, input, copy, next);
  10150. }
  10151. have -= copy;
  10152. next += copy;
  10153. if (len) { break inf_leave; }
  10154. }
  10155. else if (state.head) {
  10156. state.head.comment = null;
  10157. }
  10158. state.mode = HCRC;
  10159. /* falls through */
  10160. case HCRC:
  10161. if (state.flags & 0x0200) {
  10162. //=== NEEDBITS(16); */
  10163. while (bits < 16) {
  10164. if (have === 0) { break inf_leave; }
  10165. have--;
  10166. hold += input[next++] << bits;
  10167. bits += 8;
  10168. }
  10169. //===//
  10170. if (hold !== (state.check & 0xffff)) {
  10171. strm.msg = 'header crc mismatch';
  10172. state.mode = BAD;
  10173. break;
  10174. }
  10175. //=== INITBITS();
  10176. hold = 0;
  10177. bits = 0;
  10178. //===//
  10179. }
  10180. if (state.head) {
  10181. state.head.hcrc = ((state.flags >> 9) & 1);
  10182. state.head.done = true;
  10183. }
  10184. strm.adler = state.check = 0;
  10185. state.mode = TYPE;
  10186. break;
  10187. case DICTID:
  10188. //=== NEEDBITS(32); */
  10189. while (bits < 32) {
  10190. if (have === 0) { break inf_leave; }
  10191. have--;
  10192. hold += input[next++] << bits;
  10193. bits += 8;
  10194. }
  10195. //===//
  10196. strm.adler = state.check = zswap32(hold);
  10197. //=== INITBITS();
  10198. hold = 0;
  10199. bits = 0;
  10200. //===//
  10201. state.mode = DICT;
  10202. /* falls through */
  10203. case DICT:
  10204. if (state.havedict === 0) {
  10205. //--- RESTORE() ---
  10206. strm.next_out = put;
  10207. strm.avail_out = left;
  10208. strm.next_in = next;
  10209. strm.avail_in = have;
  10210. state.hold = hold;
  10211. state.bits = bits;
  10212. //---
  10213. return Z_NEED_DICT;
  10214. }
  10215. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  10216. state.mode = TYPE;
  10217. /* falls through */
  10218. case TYPE:
  10219. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  10220. /* falls through */
  10221. case TYPEDO:
  10222. if (state.last) {
  10223. //--- BYTEBITS() ---//
  10224. hold >>>= bits & 7;
  10225. bits -= bits & 7;
  10226. //---//
  10227. state.mode = CHECK;
  10228. break;
  10229. }
  10230. //=== NEEDBITS(3); */
  10231. while (bits < 3) {
  10232. if (have === 0) { break inf_leave; }
  10233. have--;
  10234. hold += input[next++] << bits;
  10235. bits += 8;
  10236. }
  10237. //===//
  10238. state.last = (hold & 0x01)/*BITS(1)*/;
  10239. //--- DROPBITS(1) ---//
  10240. hold >>>= 1;
  10241. bits -= 1;
  10242. //---//
  10243. switch ((hold & 0x03)/*BITS(2)*/) {
  10244. case 0: /* stored block */
  10245. //Tracev((stderr, "inflate: stored block%s\n",
  10246. // state.last ? " (last)" : ""));
  10247. state.mode = STORED;
  10248. break;
  10249. case 1: /* fixed block */
  10250. fixedtables(state);
  10251. //Tracev((stderr, "inflate: fixed codes block%s\n",
  10252. // state.last ? " (last)" : ""));
  10253. state.mode = LEN_; /* decode codes */
  10254. if (flush === Z_TREES) {
  10255. //--- DROPBITS(2) ---//
  10256. hold >>>= 2;
  10257. bits -= 2;
  10258. //---//
  10259. break inf_leave;
  10260. }
  10261. break;
  10262. case 2: /* dynamic block */
  10263. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  10264. // state.last ? " (last)" : ""));
  10265. state.mode = TABLE;
  10266. break;
  10267. case 3:
  10268. strm.msg = 'invalid block type';
  10269. state.mode = BAD;
  10270. }
  10271. //--- DROPBITS(2) ---//
  10272. hold >>>= 2;
  10273. bits -= 2;
  10274. //---//
  10275. break;
  10276. case STORED:
  10277. //--- BYTEBITS() ---// /* go to byte boundary */
  10278. hold >>>= bits & 7;
  10279. bits -= bits & 7;
  10280. //---//
  10281. //=== NEEDBITS(32); */
  10282. while (bits < 32) {
  10283. if (have === 0) { break inf_leave; }
  10284. have--;
  10285. hold += input[next++] << bits;
  10286. bits += 8;
  10287. }
  10288. //===//
  10289. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  10290. strm.msg = 'invalid stored block lengths';
  10291. state.mode = BAD;
  10292. break;
  10293. }
  10294. state.length = hold & 0xffff;
  10295. //Tracev((stderr, "inflate: stored length %u\n",
  10296. // state.length));
  10297. //=== INITBITS();
  10298. hold = 0;
  10299. bits = 0;
  10300. //===//
  10301. state.mode = COPY_;
  10302. if (flush === Z_TREES) { break inf_leave; }
  10303. /* falls through */
  10304. case COPY_:
  10305. state.mode = COPY;
  10306. /* falls through */
  10307. case COPY:
  10308. copy = state.length;
  10309. if (copy) {
  10310. if (copy > have) { copy = have; }
  10311. if (copy > left) { copy = left; }
  10312. if (copy === 0) { break inf_leave; }
  10313. //--- zmemcpy(put, next, copy); ---
  10314. utils.arraySet(output, input, next, copy, put);
  10315. //---//
  10316. have -= copy;
  10317. next += copy;
  10318. left -= copy;
  10319. put += copy;
  10320. state.length -= copy;
  10321. break;
  10322. }
  10323. //Tracev((stderr, "inflate: stored end\n"));
  10324. state.mode = TYPE;
  10325. break;
  10326. case TABLE:
  10327. //=== NEEDBITS(14); */
  10328. while (bits < 14) {
  10329. if (have === 0) { break inf_leave; }
  10330. have--;
  10331. hold += input[next++] << bits;
  10332. bits += 8;
  10333. }
  10334. //===//
  10335. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  10336. //--- DROPBITS(5) ---//
  10337. hold >>>= 5;
  10338. bits -= 5;
  10339. //---//
  10340. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  10341. //--- DROPBITS(5) ---//
  10342. hold >>>= 5;
  10343. bits -= 5;
  10344. //---//
  10345. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  10346. //--- DROPBITS(4) ---//
  10347. hold >>>= 4;
  10348. bits -= 4;
  10349. //---//
  10350. //#ifndef PKZIP_BUG_WORKAROUND
  10351. if (state.nlen > 286 || state.ndist > 30) {
  10352. strm.msg = 'too many length or distance symbols';
  10353. state.mode = BAD;
  10354. break;
  10355. }
  10356. //#endif
  10357. //Tracev((stderr, "inflate: table sizes ok\n"));
  10358. state.have = 0;
  10359. state.mode = LENLENS;
  10360. /* falls through */
  10361. case LENLENS:
  10362. while (state.have < state.ncode) {
  10363. //=== NEEDBITS(3);
  10364. while (bits < 3) {
  10365. if (have === 0) { break inf_leave; }
  10366. have--;
  10367. hold += input[next++] << bits;
  10368. bits += 8;
  10369. }
  10370. //===//
  10371. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  10372. //--- DROPBITS(3) ---//
  10373. hold >>>= 3;
  10374. bits -= 3;
  10375. //---//
  10376. }
  10377. while (state.have < 19) {
  10378. state.lens[order[state.have++]] = 0;
  10379. }
  10380. // We have separate tables & no pointers. 2 commented lines below not needed.
  10381. //state.next = state.codes;
  10382. //state.lencode = state.next;
  10383. // Switch to use dynamic table
  10384. state.lencode = state.lendyn;
  10385. state.lenbits = 7;
  10386. opts = { bits: state.lenbits };
  10387. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  10388. state.lenbits = opts.bits;
  10389. if (ret) {
  10390. strm.msg = 'invalid code lengths set';
  10391. state.mode = BAD;
  10392. break;
  10393. }
  10394. //Tracev((stderr, "inflate: code lengths ok\n"));
  10395. state.have = 0;
  10396. state.mode = CODELENS;
  10397. /* falls through */
  10398. case CODELENS:
  10399. while (state.have < state.nlen + state.ndist) {
  10400. for (; ;) {
  10401. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  10402. here_bits = here >>> 24;
  10403. here_op = (here >>> 16) & 0xff;
  10404. here_val = here & 0xffff;
  10405. if ((here_bits) <= bits) { break; }
  10406. //--- PULLBYTE() ---//
  10407. if (have === 0) { break inf_leave; }
  10408. have--;
  10409. hold += input[next++] << bits;
  10410. bits += 8;
  10411. //---//
  10412. }
  10413. if (here_val < 16) {
  10414. //--- DROPBITS(here.bits) ---//
  10415. hold >>>= here_bits;
  10416. bits -= here_bits;
  10417. //---//
  10418. state.lens[state.have++] = here_val;
  10419. }
  10420. else {
  10421. if (here_val === 16) {
  10422. //=== NEEDBITS(here.bits + 2);
  10423. n = here_bits + 2;
  10424. while (bits < n) {
  10425. if (have === 0) { break inf_leave; }
  10426. have--;
  10427. hold += input[next++] << bits;
  10428. bits += 8;
  10429. }
  10430. //===//
  10431. //--- DROPBITS(here.bits) ---//
  10432. hold >>>= here_bits;
  10433. bits -= here_bits;
  10434. //---//
  10435. if (state.have === 0) {
  10436. strm.msg = 'invalid bit length repeat';
  10437. state.mode = BAD;
  10438. break;
  10439. }
  10440. len = state.lens[state.have - 1];
  10441. copy = 3 + (hold & 0x03);//BITS(2);
  10442. //--- DROPBITS(2) ---//
  10443. hold >>>= 2;
  10444. bits -= 2;
  10445. //---//
  10446. }
  10447. else if (here_val === 17) {
  10448. //=== NEEDBITS(here.bits + 3);
  10449. n = here_bits + 3;
  10450. while (bits < n) {
  10451. if (have === 0) { break inf_leave; }
  10452. have--;
  10453. hold += input[next++] << bits;
  10454. bits += 8;
  10455. }
  10456. //===//
  10457. //--- DROPBITS(here.bits) ---//
  10458. hold >>>= here_bits;
  10459. bits -= here_bits;
  10460. //---//
  10461. len = 0;
  10462. copy = 3 + (hold & 0x07);//BITS(3);
  10463. //--- DROPBITS(3) ---//
  10464. hold >>>= 3;
  10465. bits -= 3;
  10466. //---//
  10467. }
  10468. else {
  10469. //=== NEEDBITS(here.bits + 7);
  10470. n = here_bits + 7;
  10471. while (bits < n) {
  10472. if (have === 0) { break inf_leave; }
  10473. have--;
  10474. hold += input[next++] << bits;
  10475. bits += 8;
  10476. }
  10477. //===//
  10478. //--- DROPBITS(here.bits) ---//
  10479. hold >>>= here_bits;
  10480. bits -= here_bits;
  10481. //---//
  10482. len = 0;
  10483. copy = 11 + (hold & 0x7f);//BITS(7);
  10484. //--- DROPBITS(7) ---//
  10485. hold >>>= 7;
  10486. bits -= 7;
  10487. //---//
  10488. }
  10489. if (state.have + copy > state.nlen + state.ndist) {
  10490. strm.msg = 'invalid bit length repeat';
  10491. state.mode = BAD;
  10492. break;
  10493. }
  10494. while (copy--) {
  10495. state.lens[state.have++] = len;
  10496. }
  10497. }
  10498. }
  10499. /* handle error breaks in while */
  10500. if (state.mode === BAD) { break; }
  10501. /* check for end-of-block code (better have one) */
  10502. if (state.lens[256] === 0) {
  10503. strm.msg = 'invalid code -- missing end-of-block';
  10504. state.mode = BAD;
  10505. break;
  10506. }
  10507. /* build code tables -- note: do not change the lenbits or distbits
  10508. values here (9 and 6) without reading the comments in inftrees.h
  10509. concerning the ENOUGH constants, which depend on those values */
  10510. state.lenbits = 9;
  10511. opts = { bits: state.lenbits };
  10512. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  10513. // We have separate tables & no pointers. 2 commented lines below not needed.
  10514. // state.next_index = opts.table_index;
  10515. state.lenbits = opts.bits;
  10516. // state.lencode = state.next;
  10517. if (ret) {
  10518. strm.msg = 'invalid literal/lengths set';
  10519. state.mode = BAD;
  10520. break;
  10521. }
  10522. state.distbits = 6;
  10523. //state.distcode.copy(state.codes);
  10524. // Switch to use dynamic table
  10525. state.distcode = state.distdyn;
  10526. opts = { bits: state.distbits };
  10527. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  10528. // We have separate tables & no pointers. 2 commented lines below not needed.
  10529. // state.next_index = opts.table_index;
  10530. state.distbits = opts.bits;
  10531. // state.distcode = state.next;
  10532. if (ret) {
  10533. strm.msg = 'invalid distances set';
  10534. state.mode = BAD;
  10535. break;
  10536. }
  10537. //Tracev((stderr, 'inflate: codes ok\n'));
  10538. state.mode = LEN_;
  10539. if (flush === Z_TREES) { break inf_leave; }
  10540. /* falls through */
  10541. case LEN_:
  10542. state.mode = LEN;
  10543. /* falls through */
  10544. case LEN:
  10545. if (have >= 6 && left >= 258) {
  10546. //--- RESTORE() ---
  10547. strm.next_out = put;
  10548. strm.avail_out = left;
  10549. strm.next_in = next;
  10550. strm.avail_in = have;
  10551. state.hold = hold;
  10552. state.bits = bits;
  10553. //---
  10554. inflate_fast(strm, _out);
  10555. //--- LOAD() ---
  10556. put = strm.next_out;
  10557. output = strm.output;
  10558. left = strm.avail_out;
  10559. next = strm.next_in;
  10560. input = strm.input;
  10561. have = strm.avail_in;
  10562. hold = state.hold;
  10563. bits = state.bits;
  10564. //---
  10565. if (state.mode === TYPE) {
  10566. state.back = -1;
  10567. }
  10568. break;
  10569. }
  10570. state.back = 0;
  10571. for (; ;) {
  10572. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  10573. here_bits = here >>> 24;
  10574. here_op = (here >>> 16) & 0xff;
  10575. here_val = here & 0xffff;
  10576. if (here_bits <= bits) { break; }
  10577. //--- PULLBYTE() ---//
  10578. if (have === 0) { break inf_leave; }
  10579. have--;
  10580. hold += input[next++] << bits;
  10581. bits += 8;
  10582. //---//
  10583. }
  10584. if (here_op && (here_op & 0xf0) === 0) {
  10585. last_bits = here_bits;
  10586. last_op = here_op;
  10587. last_val = here_val;
  10588. for (; ;) {
  10589. here = state.lencode[last_val +
  10590. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  10591. here_bits = here >>> 24;
  10592. here_op = (here >>> 16) & 0xff;
  10593. here_val = here & 0xffff;
  10594. if ((last_bits + here_bits) <= bits) { break; }
  10595. //--- PULLBYTE() ---//
  10596. if (have === 0) { break inf_leave; }
  10597. have--;
  10598. hold += input[next++] << bits;
  10599. bits += 8;
  10600. //---//
  10601. }
  10602. //--- DROPBITS(last.bits) ---//
  10603. hold >>>= last_bits;
  10604. bits -= last_bits;
  10605. //---//
  10606. state.back += last_bits;
  10607. }
  10608. //--- DROPBITS(here.bits) ---//
  10609. hold >>>= here_bits;
  10610. bits -= here_bits;
  10611. //---//
  10612. state.back += here_bits;
  10613. state.length = here_val;
  10614. if (here_op === 0) {
  10615. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  10616. // "inflate: literal '%c'\n" :
  10617. // "inflate: literal 0x%02x\n", here.val));
  10618. state.mode = LIT;
  10619. break;
  10620. }
  10621. if (here_op & 32) {
  10622. //Tracevv((stderr, "inflate: end of block\n"));
  10623. state.back = -1;
  10624. state.mode = TYPE;
  10625. break;
  10626. }
  10627. if (here_op & 64) {
  10628. strm.msg = 'invalid literal/length code';
  10629. state.mode = BAD;
  10630. break;
  10631. }
  10632. state.extra = here_op & 15;
  10633. state.mode = LENEXT;
  10634. /* falls through */
  10635. case LENEXT:
  10636. if (state.extra) {
  10637. //=== NEEDBITS(state.extra);
  10638. n = state.extra;
  10639. while (bits < n) {
  10640. if (have === 0) { break inf_leave; }
  10641. have--;
  10642. hold += input[next++] << bits;
  10643. bits += 8;
  10644. }
  10645. //===//
  10646. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  10647. //--- DROPBITS(state.extra) ---//
  10648. hold >>>= state.extra;
  10649. bits -= state.extra;
  10650. //---//
  10651. state.back += state.extra;
  10652. }
  10653. //Tracevv((stderr, "inflate: length %u\n", state.length));
  10654. state.was = state.length;
  10655. state.mode = DIST;
  10656. /* falls through */
  10657. case DIST:
  10658. for (; ;) {
  10659. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  10660. here_bits = here >>> 24;
  10661. here_op = (here >>> 16) & 0xff;
  10662. here_val = here & 0xffff;
  10663. if ((here_bits) <= bits) { break; }
  10664. //--- PULLBYTE() ---//
  10665. if (have === 0) { break inf_leave; }
  10666. have--;
  10667. hold += input[next++] << bits;
  10668. bits += 8;
  10669. //---//
  10670. }
  10671. if ((here_op & 0xf0) === 0) {
  10672. last_bits = here_bits;
  10673. last_op = here_op;
  10674. last_val = here_val;
  10675. for (; ;) {
  10676. here = state.distcode[last_val +
  10677. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  10678. here_bits = here >>> 24;
  10679. here_op = (here >>> 16) & 0xff;
  10680. here_val = here & 0xffff;
  10681. if ((last_bits + here_bits) <= bits) { break; }
  10682. //--- PULLBYTE() ---//
  10683. if (have === 0) { break inf_leave; }
  10684. have--;
  10685. hold += input[next++] << bits;
  10686. bits += 8;
  10687. //---//
  10688. }
  10689. //--- DROPBITS(last.bits) ---//
  10690. hold >>>= last_bits;
  10691. bits -= last_bits;
  10692. //---//
  10693. state.back += last_bits;
  10694. }
  10695. //--- DROPBITS(here.bits) ---//
  10696. hold >>>= here_bits;
  10697. bits -= here_bits;
  10698. //---//
  10699. state.back += here_bits;
  10700. if (here_op & 64) {
  10701. strm.msg = 'invalid distance code';
  10702. state.mode = BAD;
  10703. break;
  10704. }
  10705. state.offset = here_val;
  10706. state.extra = (here_op) & 15;
  10707. state.mode = DISTEXT;
  10708. /* falls through */
  10709. case DISTEXT:
  10710. if (state.extra) {
  10711. //=== NEEDBITS(state.extra);
  10712. n = state.extra;
  10713. while (bits < n) {
  10714. if (have === 0) { break inf_leave; }
  10715. have--;
  10716. hold += input[next++] << bits;
  10717. bits += 8;
  10718. }
  10719. //===//
  10720. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  10721. //--- DROPBITS(state.extra) ---//
  10722. hold >>>= state.extra;
  10723. bits -= state.extra;
  10724. //---//
  10725. state.back += state.extra;
  10726. }
  10727. //#ifdef INFLATE_STRICT
  10728. if (state.offset > state.dmax) {
  10729. strm.msg = 'invalid distance too far back';
  10730. state.mode = BAD;
  10731. break;
  10732. }
  10733. //#endif
  10734. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  10735. state.mode = MATCH;
  10736. /* falls through */
  10737. case MATCH:
  10738. if (left === 0) { break inf_leave; }
  10739. copy = _out - left;
  10740. if (state.offset > copy) { /* copy from window */
  10741. copy = state.offset - copy;
  10742. if (copy > state.whave) {
  10743. if (state.sane) {
  10744. strm.msg = 'invalid distance too far back';
  10745. state.mode = BAD;
  10746. break;
  10747. }
  10748. // (!) This block is disabled in zlib defaults,
  10749. // don't enable it for binary compatibility
  10750. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  10751. // Trace((stderr, "inflate.c too far\n"));
  10752. // copy -= state.whave;
  10753. // if (copy > state.length) { copy = state.length; }
  10754. // if (copy > left) { copy = left; }
  10755. // left -= copy;
  10756. // state.length -= copy;
  10757. // do {
  10758. // output[put++] = 0;
  10759. // } while (--copy);
  10760. // if (state.length === 0) { state.mode = LEN; }
  10761. // break;
  10762. //#endif
  10763. }
  10764. if (copy > state.wnext) {
  10765. copy -= state.wnext;
  10766. from = state.wsize - copy;
  10767. }
  10768. else {
  10769. from = state.wnext - copy;
  10770. }
  10771. if (copy > state.length) { copy = state.length; }
  10772. from_source = state.window;
  10773. }
  10774. else { /* copy from output */
  10775. from_source = output;
  10776. from = put - state.offset;
  10777. copy = state.length;
  10778. }
  10779. if (copy > left) { copy = left; }
  10780. left -= copy;
  10781. state.length -= copy;
  10782. do {
  10783. output[put++] = from_source[from++];
  10784. } while (--copy);
  10785. if (state.length === 0) { state.mode = LEN; }
  10786. break;
  10787. case LIT:
  10788. if (left === 0) { break inf_leave; }
  10789. output[put++] = state.length;
  10790. left--;
  10791. state.mode = LEN;
  10792. break;
  10793. case CHECK:
  10794. if (state.wrap) {
  10795. //=== NEEDBITS(32);
  10796. while (bits < 32) {
  10797. if (have === 0) { break inf_leave; }
  10798. have--;
  10799. // Use '|' instead of '+' to make sure that result is signed
  10800. hold |= input[next++] << bits;
  10801. bits += 8;
  10802. }
  10803. //===//
  10804. _out -= left;
  10805. strm.total_out += _out;
  10806. state.total += _out;
  10807. if (_out) {
  10808. strm.adler = state.check =
  10809. /*UPDATE(state.check, put - _out, _out);*/
  10810. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  10811. }
  10812. _out = left;
  10813. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  10814. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  10815. strm.msg = 'incorrect data check';
  10816. state.mode = BAD;
  10817. break;
  10818. }
  10819. //=== INITBITS();
  10820. hold = 0;
  10821. bits = 0;
  10822. //===//
  10823. //Tracev((stderr, "inflate: check matches trailer\n"));
  10824. }
  10825. state.mode = LENGTH;
  10826. /* falls through */
  10827. case LENGTH:
  10828. if (state.wrap && state.flags) {
  10829. //=== NEEDBITS(32);
  10830. while (bits < 32) {
  10831. if (have === 0) { break inf_leave; }
  10832. have--;
  10833. hold += input[next++] << bits;
  10834. bits += 8;
  10835. }
  10836. //===//
  10837. if (hold !== (state.total & 0xffffffff)) {
  10838. strm.msg = 'incorrect length check';
  10839. state.mode = BAD;
  10840. break;
  10841. }
  10842. //=== INITBITS();
  10843. hold = 0;
  10844. bits = 0;
  10845. //===//
  10846. //Tracev((stderr, "inflate: length matches trailer\n"));
  10847. }
  10848. state.mode = DONE;
  10849. /* falls through */
  10850. case DONE:
  10851. ret = Z_STREAM_END;
  10852. break inf_leave;
  10853. case BAD:
  10854. ret = Z_DATA_ERROR;
  10855. break inf_leave;
  10856. case MEM:
  10857. return Z_MEM_ERROR;
  10858. case SYNC:
  10859. /* falls through */
  10860. default:
  10861. return Z_STREAM_ERROR;
  10862. }
  10863. }
  10864. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  10865. /*
  10866. Return from inflate(), updating the total counts and the check value.
  10867. If there was no progress during the inflate() call, return a buffer
  10868. error. Call updatewindow() to create and/or update the window state.
  10869. Note: a memory error from inflate() is non-recoverable.
  10870. */
  10871. //--- RESTORE() ---
  10872. strm.next_out = put;
  10873. strm.avail_out = left;
  10874. strm.next_in = next;
  10875. strm.avail_in = have;
  10876. state.hold = hold;
  10877. state.bits = bits;
  10878. //---
  10879. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  10880. (state.mode < CHECK || flush !== Z_FINISH))) {
  10881. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  10882. state.mode = MEM;
  10883. return Z_MEM_ERROR;
  10884. }
  10885. }
  10886. _in -= strm.avail_in;
  10887. _out -= strm.avail_out;
  10888. strm.total_in += _in;
  10889. strm.total_out += _out;
  10890. state.total += _out;
  10891. if (state.wrap && _out) {
  10892. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  10893. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  10894. }
  10895. strm.data_type = state.bits + (state.last ? 64 : 0) +
  10896. (state.mode === TYPE ? 128 : 0) +
  10897. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  10898. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  10899. ret = Z_BUF_ERROR;
  10900. }
  10901. return ret;
  10902. }
  10903. function inflateEnd(strm) {
  10904. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  10905. return Z_STREAM_ERROR;
  10906. }
  10907. var state = strm.state;
  10908. if (state.window) {
  10909. state.window = null;
  10910. }
  10911. strm.state = null;
  10912. return Z_OK;
  10913. }
  10914. function inflateGetHeader(strm, head) {
  10915. var state;
  10916. /* check state */
  10917. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  10918. state = strm.state;
  10919. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  10920. /* save header structure */
  10921. state.head = head;
  10922. head.done = false;
  10923. return Z_OK;
  10924. }
  10925. function inflateSetDictionary(strm, dictionary) {
  10926. var dictLength = dictionary.length;
  10927. var state;
  10928. var dictid;
  10929. var ret;
  10930. /* check state */
  10931. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  10932. state = strm.state;
  10933. if (state.wrap !== 0 && state.mode !== DICT) {
  10934. return Z_STREAM_ERROR;
  10935. }
  10936. /* check for correct dictionary identifier */
  10937. if (state.mode === DICT) {
  10938. dictid = 1; /* adler32(0, null, 0)*/
  10939. /* dictid = adler32(dictid, dictionary, dictLength); */
  10940. dictid = adler32(dictid, dictionary, dictLength, 0);
  10941. if (dictid !== state.check) {
  10942. return Z_DATA_ERROR;
  10943. }
  10944. }
  10945. /* copy dictionary to window using updatewindow(), which will amend the
  10946. existing dictionary if appropriate */
  10947. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  10948. if (ret) {
  10949. state.mode = MEM;
  10950. return Z_MEM_ERROR;
  10951. }
  10952. state.havedict = 1;
  10953. // Tracev((stderr, "inflate: dictionary set\n"));
  10954. return Z_OK;
  10955. }
  10956. exports.inflateReset = inflateReset;
  10957. exports.inflateReset2 = inflateReset2;
  10958. exports.inflateResetKeep = inflateResetKeep;
  10959. exports.inflateInit = inflateInit;
  10960. exports.inflateInit2 = inflateInit2;
  10961. exports.inflate = inflate;
  10962. exports.inflateEnd = inflateEnd;
  10963. exports.inflateGetHeader = inflateGetHeader;
  10964. exports.inflateSetDictionary = inflateSetDictionary;
  10965. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  10966. /* Not implemented
  10967. exports.inflateCopy = inflateCopy;
  10968. exports.inflateGetDictionary = inflateGetDictionary;
  10969. exports.inflateMark = inflateMark;
  10970. exports.inflatePrime = inflatePrime;
  10971. exports.inflateSync = inflateSync;
  10972. exports.inflateSyncPoint = inflateSyncPoint;
  10973. exports.inflateUndermine = inflateUndermine;
  10974. */
  10975. }, { "../utils/common": 50, "./adler32": 52, "./crc32": 54, "./inffast": 57, "./inftrees": 59 }], 59: [function (require, module, exports) {
  10976. 'use strict';
  10977. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10978. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10979. //
  10980. // This software is provided 'as-is', without any express or implied
  10981. // warranty. In no event will the authors be held liable for any damages
  10982. // arising from the use of this software.
  10983. //
  10984. // Permission is granted to anyone to use this software for any purpose,
  10985. // including commercial applications, and to alter it and redistribute it
  10986. // freely, subject to the following restrictions:
  10987. //
  10988. // 1. The origin of this software must not be misrepresented; you must not
  10989. // claim that you wrote the original software. If you use this software
  10990. // in a product, an acknowledgment in the product documentation would be
  10991. // appreciated but is not required.
  10992. // 2. Altered source versions must be plainly marked as such, and must not be
  10993. // misrepresented as being the original software.
  10994. // 3. This notice may not be removed or altered from any source distribution.
  10995. var utils = require('../utils/common');
  10996. var MAXBITS = 15;
  10997. var ENOUGH_LENS = 852;
  10998. var ENOUGH_DISTS = 592;
  10999. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  11000. var CODES = 0;
  11001. var LENS = 1;
  11002. var DISTS = 2;
  11003. var lbase = [ /* Length codes 257..285 base */
  11004. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  11005. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  11006. ];
  11007. var lext = [ /* Length codes 257..285 extra */
  11008. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  11009. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  11010. ];
  11011. var dbase = [ /* Distance codes 0..29 base */
  11012. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  11013. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  11014. 8193, 12289, 16385, 24577, 0, 0
  11015. ];
  11016. var dext = [ /* Distance codes 0..29 extra */
  11017. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  11018. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  11019. 28, 28, 29, 29, 64, 64
  11020. ];
  11021. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
  11022. var bits = opts.bits;
  11023. //here = opts.here; /* table entry for duplication */
  11024. var len = 0; /* a code's length in bits */
  11025. var sym = 0; /* index of code symbols */
  11026. var min = 0, max = 0; /* minimum and maximum code lengths */
  11027. var root = 0; /* number of index bits for root table */
  11028. var curr = 0; /* number of index bits for current table */
  11029. var drop = 0; /* code bits to drop for sub-table */
  11030. var left = 0; /* number of prefix codes available */
  11031. var used = 0; /* code entries in table used */
  11032. var huff = 0; /* Huffman code */
  11033. var incr; /* for incrementing code, index */
  11034. var fill; /* index for replicating entries */
  11035. var low; /* low bits for current root entry */
  11036. var mask; /* mask for low root bits */
  11037. var next; /* next available space in table */
  11038. var base = null; /* base value table to use */
  11039. var base_index = 0;
  11040. // var shoextra; /* extra bits table to use */
  11041. var end; /* use base and extra for symbol > end */
  11042. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  11043. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  11044. var extra = null;
  11045. var extra_index = 0;
  11046. var here_bits, here_op, here_val;
  11047. /*
  11048. Process a set of code lengths to create a canonical Huffman code. The
  11049. code lengths are lens[0..codes-1]. Each length corresponds to the
  11050. symbols 0..codes-1. The Huffman code is generated by first sorting the
  11051. symbols by length from short to long, and retaining the symbol order
  11052. for codes with equal lengths. Then the code starts with all zero bits
  11053. for the first code of the shortest length, and the codes are integer
  11054. increments for the same length, and zeros are appended as the length
  11055. increases. For the deflate format, these bits are stored backwards
  11056. from their more natural integer increment ordering, and so when the
  11057. decoding tables are built in the large loop below, the integer codes
  11058. are incremented backwards.
  11059. This routine assumes, but does not check, that all of the entries in
  11060. lens[] are in the range 0..MAXBITS. The caller must assure this.
  11061. 1..MAXBITS is interpreted as that code length. zero means that that
  11062. symbol does not occur in this code.
  11063. The codes are sorted by computing a count of codes for each length,
  11064. creating from that a table of starting indices for each length in the
  11065. sorted table, and then entering the symbols in order in the sorted
  11066. table. The sorted table is work[], with that space being provided by
  11067. the caller.
  11068. The length counts are used for other purposes as well, i.e. finding
  11069. the minimum and maximum length codes, determining if there are any
  11070. codes at all, checking for a valid set of lengths, and looking ahead
  11071. at length counts to determine sub-table sizes when building the
  11072. decoding tables.
  11073. */
  11074. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  11075. for (len = 0; len <= MAXBITS; len++) {
  11076. count[len] = 0;
  11077. }
  11078. for (sym = 0; sym < codes; sym++) {
  11079. count[lens[lens_index + sym]]++;
  11080. }
  11081. /* bound code lengths, force root to be within code lengths */
  11082. root = bits;
  11083. for (max = MAXBITS; max >= 1; max--) {
  11084. if (count[max] !== 0) { break; }
  11085. }
  11086. if (root > max) {
  11087. root = max;
  11088. }
  11089. if (max === 0) { /* no symbols to code at all */
  11090. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  11091. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  11092. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  11093. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  11094. //table.op[opts.table_index] = 64;
  11095. //table.bits[opts.table_index] = 1;
  11096. //table.val[opts.table_index++] = 0;
  11097. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  11098. opts.bits = 1;
  11099. return 0; /* no symbols, but wait for decoding to report error */
  11100. }
  11101. for (min = 1; min < max; min++) {
  11102. if (count[min] !== 0) { break; }
  11103. }
  11104. if (root < min) {
  11105. root = min;
  11106. }
  11107. /* check for an over-subscribed or incomplete set of lengths */
  11108. left = 1;
  11109. for (len = 1; len <= MAXBITS; len++) {
  11110. left <<= 1;
  11111. left -= count[len];
  11112. if (left < 0) {
  11113. return -1;
  11114. } /* over-subscribed */
  11115. }
  11116. if (left > 0 && (type === CODES || max !== 1)) {
  11117. return -1; /* incomplete set */
  11118. }
  11119. /* generate offsets into symbol table for each length for sorting */
  11120. offs[1] = 0;
  11121. for (len = 1; len < MAXBITS; len++) {
  11122. offs[len + 1] = offs[len] + count[len];
  11123. }
  11124. /* sort symbols by length, by symbol order within each length */
  11125. for (sym = 0; sym < codes; sym++) {
  11126. if (lens[lens_index + sym] !== 0) {
  11127. work[offs[lens[lens_index + sym]]++] = sym;
  11128. }
  11129. }
  11130. /*
  11131. Create and fill in decoding tables. In this loop, the table being
  11132. filled is at next and has curr index bits. The code being used is huff
  11133. with length len. That code is converted to an index by dropping drop
  11134. bits off of the bottom. For codes where len is less than drop + curr,
  11135. those top drop + curr - len bits are incremented through all values to
  11136. fill the table with replicated entries.
  11137. root is the number of index bits for the root table. When len exceeds
  11138. root, sub-tables are created pointed to by the root entry with an index
  11139. of the low root bits of huff. This is saved in low to check for when a
  11140. new sub-table should be started. drop is zero when the root table is
  11141. being filled, and drop is root when sub-tables are being filled.
  11142. When a new sub-table is needed, it is necessary to look ahead in the
  11143. code lengths to determine what size sub-table is needed. The length
  11144. counts are used for this, and so count[] is decremented as codes are
  11145. entered in the tables.
  11146. used keeps track of how many table entries have been allocated from the
  11147. provided *table space. It is checked for LENS and DIST tables against
  11148. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  11149. the initial root table size constants. See the comments in inftrees.h
  11150. for more information.
  11151. sym increments through all symbols, and the loop terminates when
  11152. all codes of length max, i.e. all codes, have been processed. This
  11153. routine permits incomplete codes, so another loop after this one fills
  11154. in the rest of the decoding tables with invalid code markers.
  11155. */
  11156. /* set up for code type */
  11157. // poor man optimization - use if-else instead of switch,
  11158. // to avoid deopts in old v8
  11159. if (type === CODES) {
  11160. base = extra = work; /* dummy value--not used */
  11161. end = 19;
  11162. } else if (type === LENS) {
  11163. base = lbase;
  11164. base_index -= 257;
  11165. extra = lext;
  11166. extra_index -= 257;
  11167. end = 256;
  11168. } else { /* DISTS */
  11169. base = dbase;
  11170. extra = dext;
  11171. end = -1;
  11172. }
  11173. /* initialize opts for loop */
  11174. huff = 0; /* starting code */
  11175. sym = 0; /* starting code symbol */
  11176. len = min; /* starting code length */
  11177. next = table_index; /* current table to fill in */
  11178. curr = root; /* current table index bits */
  11179. drop = 0; /* current bits to drop from code for index */
  11180. low = -1; /* trigger new sub-table when len > root */
  11181. used = 1 << root; /* use root table entries */
  11182. mask = used - 1; /* mask for comparing low */
  11183. /* check available table space */
  11184. if ((type === LENS && used > ENOUGH_LENS) ||
  11185. (type === DISTS && used > ENOUGH_DISTS)) {
  11186. return 1;
  11187. }
  11188. /* process all codes and make table entries */
  11189. for (; ;) {
  11190. /* create table entry */
  11191. here_bits = len - drop;
  11192. if (work[sym] < end) {
  11193. here_op = 0;
  11194. here_val = work[sym];
  11195. }
  11196. else if (work[sym] > end) {
  11197. here_op = extra[extra_index + work[sym]];
  11198. here_val = base[base_index + work[sym]];
  11199. }
  11200. else {
  11201. here_op = 32 + 64; /* end of block */
  11202. here_val = 0;
  11203. }
  11204. /* replicate for those indices with low len bits equal to huff */
  11205. incr = 1 << (len - drop);
  11206. fill = 1 << curr;
  11207. min = fill; /* save offset to next table */
  11208. do {
  11209. fill -= incr;
  11210. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0;
  11211. } while (fill !== 0);
  11212. /* backwards increment the len-bit code huff */
  11213. incr = 1 << (len - 1);
  11214. while (huff & incr) {
  11215. incr >>= 1;
  11216. }
  11217. if (incr !== 0) {
  11218. huff &= incr - 1;
  11219. huff += incr;
  11220. } else {
  11221. huff = 0;
  11222. }
  11223. /* go to next symbol, update count, len */
  11224. sym++;
  11225. if (--count[len] === 0) {
  11226. if (len === max) { break; }
  11227. len = lens[lens_index + work[sym]];
  11228. }
  11229. /* create new sub-table if needed */
  11230. if (len > root && (huff & mask) !== low) {
  11231. /* if first time, transition to sub-tables */
  11232. if (drop === 0) {
  11233. drop = root;
  11234. }
  11235. /* increment past last table */
  11236. next += min; /* here min is 1 << curr */
  11237. /* determine length of next table */
  11238. curr = len - drop;
  11239. left = 1 << curr;
  11240. while (curr + drop < max) {
  11241. left -= count[curr + drop];
  11242. if (left <= 0) { break; }
  11243. curr++;
  11244. left <<= 1;
  11245. }
  11246. /* check for enough space */
  11247. used += 1 << curr;
  11248. if ((type === LENS && used > ENOUGH_LENS) ||
  11249. (type === DISTS && used > ENOUGH_DISTS)) {
  11250. return 1;
  11251. }
  11252. /* point entry in root table to sub-table */
  11253. low = huff & mask;
  11254. /*table.op[low] = curr;
  11255. table.bits[low] = root;
  11256. table.val[low] = next - opts.table_index;*/
  11257. table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0;
  11258. }
  11259. }
  11260. /* fill in remaining table entry if code is incomplete (guaranteed to have
  11261. at most one remaining entry, since if the code is incomplete, the
  11262. maximum code length that was allowed to get this far is one bit) */
  11263. if (huff !== 0) {
  11264. //table.op[next + huff] = 64; /* invalid code marker */
  11265. //table.bits[next + huff] = len - drop;
  11266. //table.val[next + huff] = 0;
  11267. table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0;
  11268. }
  11269. /* set return parameters */
  11270. //opts.table_index += used;
  11271. opts.bits = root;
  11272. return 0;
  11273. };
  11274. }, { "../utils/common": 50 }], 60: [function (require, module, exports) {
  11275. 'use strict';
  11276. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11277. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11278. //
  11279. // This software is provided 'as-is', without any express or implied
  11280. // warranty. In no event will the authors be held liable for any damages
  11281. // arising from the use of this software.
  11282. //
  11283. // Permission is granted to anyone to use this software for any purpose,
  11284. // including commercial applications, and to alter it and redistribute it
  11285. // freely, subject to the following restrictions:
  11286. //
  11287. // 1. The origin of this software must not be misrepresented; you must not
  11288. // claim that you wrote the original software. If you use this software
  11289. // in a product, an acknowledgment in the product documentation would be
  11290. // appreciated but is not required.
  11291. // 2. Altered source versions must be plainly marked as such, and must not be
  11292. // misrepresented as being the original software.
  11293. // 3. This notice may not be removed or altered from any source distribution.
  11294. module.exports = {
  11295. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  11296. 1: 'stream end', /* Z_STREAM_END 1 */
  11297. 0: '', /* Z_OK 0 */
  11298. '-1': 'file error', /* Z_ERRNO (-1) */
  11299. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  11300. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  11301. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  11302. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  11303. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  11304. };
  11305. }, {}], 61: [function (require, module, exports) {
  11306. 'use strict';
  11307. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11308. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11309. //
  11310. // This software is provided 'as-is', without any express or implied
  11311. // warranty. In no event will the authors be held liable for any damages
  11312. // arising from the use of this software.
  11313. //
  11314. // Permission is granted to anyone to use this software for any purpose,
  11315. // including commercial applications, and to alter it and redistribute it
  11316. // freely, subject to the following restrictions:
  11317. //
  11318. // 1. The origin of this software must not be misrepresented; you must not
  11319. // claim that you wrote the original software. If you use this software
  11320. // in a product, an acknowledgment in the product documentation would be
  11321. // appreciated but is not required.
  11322. // 2. Altered source versions must be plainly marked as such, and must not be
  11323. // misrepresented as being the original software.
  11324. // 3. This notice may not be removed or altered from any source distribution.
  11325. /* eslint-disable space-unary-ops */
  11326. var utils = require('../utils/common');
  11327. /* Public constants ==========================================================*/
  11328. /* ===========================================================================*/
  11329. //var Z_FILTERED = 1;
  11330. //var Z_HUFFMAN_ONLY = 2;
  11331. //var Z_RLE = 3;
  11332. var Z_FIXED = 4;
  11333. //var Z_DEFAULT_STRATEGY = 0;
  11334. /* Possible values of the data_type field (though see inflate()) */
  11335. var Z_BINARY = 0;
  11336. var Z_TEXT = 1;
  11337. //var Z_ASCII = 1; // = Z_TEXT
  11338. var Z_UNKNOWN = 2;
  11339. /*============================================================================*/
  11340. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11341. // From zutil.h
  11342. var STORED_BLOCK = 0;
  11343. var STATIC_TREES = 1;
  11344. var DYN_TREES = 2;
  11345. /* The three kinds of block type */
  11346. var MIN_MATCH = 3;
  11347. var MAX_MATCH = 258;
  11348. /* The minimum and maximum match lengths */
  11349. // From deflate.h
  11350. /* ===========================================================================
  11351. * Internal compression state.
  11352. */
  11353. var LENGTH_CODES = 29;
  11354. /* number of length codes, not counting the special END_BLOCK code */
  11355. var LITERALS = 256;
  11356. /* number of literal bytes 0..255 */
  11357. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11358. /* number of Literal or Length codes, including the END_BLOCK code */
  11359. var D_CODES = 30;
  11360. /* number of distance codes */
  11361. var BL_CODES = 19;
  11362. /* number of codes used to transfer the bit lengths */
  11363. var HEAP_SIZE = 2 * L_CODES + 1;
  11364. /* maximum heap size */
  11365. var MAX_BITS = 15;
  11366. /* All codes must not exceed MAX_BITS bits */
  11367. var Buf_size = 16;
  11368. /* size of bit buffer in bi_buf */
  11369. /* ===========================================================================
  11370. * Constants
  11371. */
  11372. var MAX_BL_BITS = 7;
  11373. /* Bit length codes must not exceed MAX_BL_BITS bits */
  11374. var END_BLOCK = 256;
  11375. /* end of block literal code */
  11376. var REP_3_6 = 16;
  11377. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  11378. var REPZ_3_10 = 17;
  11379. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  11380. var REPZ_11_138 = 18;
  11381. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  11382. /* eslint-disable comma-spacing,array-bracket-spacing */
  11383. var extra_lbits = /* extra bits for each length code */
  11384. [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];
  11385. var extra_dbits = /* extra bits for each distance code */
  11386. [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];
  11387. var extra_blbits = /* extra bits for each bit length code */
  11388. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  11389. var bl_order =
  11390. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  11391. /* eslint-enable comma-spacing,array-bracket-spacing */
  11392. /* The lengths of the bit length codes are sent in order of decreasing
  11393. * probability, to avoid transmitting the lengths for unused bit length codes.
  11394. */
  11395. /* ===========================================================================
  11396. * Local data. These are initialized only once.
  11397. */
  11398. // We pre-fill arrays with 0 to avoid uninitialized gaps
  11399. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  11400. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  11401. var static_ltree = new Array((L_CODES + 2) * 2);
  11402. zero(static_ltree);
  11403. /* The static literal tree. Since the bit lengths are imposed, there is no
  11404. * need for the L_CODES extra codes used during heap construction. However
  11405. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  11406. * below).
  11407. */
  11408. var static_dtree = new Array(D_CODES * 2);
  11409. zero(static_dtree);
  11410. /* The static distance tree. (Actually a trivial tree since all codes use
  11411. * 5 bits.)
  11412. */
  11413. var _dist_code = new Array(DIST_CODE_LEN);
  11414. zero(_dist_code);
  11415. /* Distance codes. The first 256 values correspond to the distances
  11416. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  11417. * the 15 bit distances.
  11418. */
  11419. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  11420. zero(_length_code);
  11421. /* length code for each normalized match length (0 == MIN_MATCH) */
  11422. var base_length = new Array(LENGTH_CODES);
  11423. zero(base_length);
  11424. /* First normalized length for each code (0 = MIN_MATCH) */
  11425. var base_dist = new Array(D_CODES);
  11426. zero(base_dist);
  11427. /* First normalized distance for each code (0 = distance of 1) */
  11428. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  11429. this.static_tree = static_tree; /* static tree or NULL */
  11430. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  11431. this.extra_base = extra_base; /* base index for extra_bits */
  11432. this.elems = elems; /* max number of elements in the tree */
  11433. this.max_length = max_length; /* max bit length for the codes */
  11434. // show if `static_tree` has data or dummy - needed for monomorphic objects
  11435. this.has_stree = static_tree && static_tree.length;
  11436. }
  11437. var static_l_desc;
  11438. var static_d_desc;
  11439. var static_bl_desc;
  11440. function TreeDesc(dyn_tree, stat_desc) {
  11441. this.dyn_tree = dyn_tree; /* the dynamic tree */
  11442. this.max_code = 0; /* largest code with non zero frequency */
  11443. this.stat_desc = stat_desc; /* the corresponding static tree */
  11444. }
  11445. function d_code(dist) {
  11446. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  11447. }
  11448. /* ===========================================================================
  11449. * Output a short LSB first on the stream.
  11450. * IN assertion: there is enough room in pendingBuf.
  11451. */
  11452. function put_short(s, w) {
  11453. // put_byte(s, (uch)((w) & 0xff));
  11454. // put_byte(s, (uch)((ush)(w) >> 8));
  11455. s.pending_buf[s.pending++] = (w) & 0xff;
  11456. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  11457. }
  11458. /* ===========================================================================
  11459. * Send a value on a given number of bits.
  11460. * IN assertion: length <= 16 and value fits in length bits.
  11461. */
  11462. function send_bits(s, value, length) {
  11463. if (s.bi_valid > (Buf_size - length)) {
  11464. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  11465. put_short(s, s.bi_buf);
  11466. s.bi_buf = value >> (Buf_size - s.bi_valid);
  11467. s.bi_valid += length - Buf_size;
  11468. } else {
  11469. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  11470. s.bi_valid += length;
  11471. }
  11472. }
  11473. function send_code(s, c, tree) {
  11474. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  11475. }
  11476. /* ===========================================================================
  11477. * Reverse the first len bits of a code, using straightforward code (a faster
  11478. * method would use a table)
  11479. * IN assertion: 1 <= len <= 15
  11480. */
  11481. function bi_reverse(code, len) {
  11482. var res = 0;
  11483. do {
  11484. res |= code & 1;
  11485. code >>>= 1;
  11486. res <<= 1;
  11487. } while (--len > 0);
  11488. return res >>> 1;
  11489. }
  11490. /* ===========================================================================
  11491. * Flush the bit buffer, keeping at most 7 bits in it.
  11492. */
  11493. function bi_flush(s) {
  11494. if (s.bi_valid === 16) {
  11495. put_short(s, s.bi_buf);
  11496. s.bi_buf = 0;
  11497. s.bi_valid = 0;
  11498. } else if (s.bi_valid >= 8) {
  11499. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  11500. s.bi_buf >>= 8;
  11501. s.bi_valid -= 8;
  11502. }
  11503. }
  11504. /* ===========================================================================
  11505. * Compute the optimal bit lengths for a tree and update the total bit length
  11506. * for the current block.
  11507. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  11508. * above are the tree nodes sorted by increasing frequency.
  11509. * OUT assertions: the field len is set to the optimal bit length, the
  11510. * array bl_count contains the frequencies for each bit length.
  11511. * The length opt_len is updated; static_len is also updated if stree is
  11512. * not null.
  11513. */
  11514. function gen_bitlen(s, desc)
  11515. // deflate_state *s;
  11516. // tree_desc *desc; /* the tree descriptor */
  11517. {
  11518. var tree = desc.dyn_tree;
  11519. var max_code = desc.max_code;
  11520. var stree = desc.stat_desc.static_tree;
  11521. var has_stree = desc.stat_desc.has_stree;
  11522. var extra = desc.stat_desc.extra_bits;
  11523. var base = desc.stat_desc.extra_base;
  11524. var max_length = desc.stat_desc.max_length;
  11525. var h; /* heap index */
  11526. var n, m; /* iterate over the tree elements */
  11527. var bits; /* bit length */
  11528. var xbits; /* extra bits */
  11529. var f; /* frequency */
  11530. var overflow = 0; /* number of elements with bit length too large */
  11531. for (bits = 0; bits <= MAX_BITS; bits++) {
  11532. s.bl_count[bits] = 0;
  11533. }
  11534. /* In a first pass, compute the optimal bit lengths (which may
  11535. * overflow in the case of the bit length tree).
  11536. */
  11537. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  11538. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  11539. n = s.heap[h];
  11540. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  11541. if (bits > max_length) {
  11542. bits = max_length;
  11543. overflow++;
  11544. }
  11545. tree[n * 2 + 1]/*.Len*/ = bits;
  11546. /* We overwrite tree[n].Dad which is no longer needed */
  11547. if (n > max_code) { continue; } /* not a leaf node */
  11548. s.bl_count[bits]++;
  11549. xbits = 0;
  11550. if (n >= base) {
  11551. xbits = extra[n - base];
  11552. }
  11553. f = tree[n * 2]/*.Freq*/;
  11554. s.opt_len += f * (bits + xbits);
  11555. if (has_stree) {
  11556. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  11557. }
  11558. }
  11559. if (overflow === 0) { return; }
  11560. // Trace((stderr,"\nbit length overflow\n"));
  11561. /* This happens for example on obj2 and pic of the Calgary corpus */
  11562. /* Find the first bit length which could increase: */
  11563. do {
  11564. bits = max_length - 1;
  11565. while (s.bl_count[bits] === 0) { bits--; }
  11566. s.bl_count[bits]--; /* move one leaf down the tree */
  11567. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  11568. s.bl_count[max_length]--;
  11569. /* The brother of the overflow item also moves one step up,
  11570. * but this does not affect bl_count[max_length]
  11571. */
  11572. overflow -= 2;
  11573. } while (overflow > 0);
  11574. /* Now recompute all bit lengths, scanning in increasing frequency.
  11575. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  11576. * lengths instead of fixing only the wrong ones. This idea is taken
  11577. * from 'ar' written by Haruhiko Okumura.)
  11578. */
  11579. for (bits = max_length; bits !== 0; bits--) {
  11580. n = s.bl_count[bits];
  11581. while (n !== 0) {
  11582. m = s.heap[--h];
  11583. if (m > max_code) { continue; }
  11584. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  11585. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  11586. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  11587. tree[m * 2 + 1]/*.Len*/ = bits;
  11588. }
  11589. n--;
  11590. }
  11591. }
  11592. }
  11593. /* ===========================================================================
  11594. * Generate the codes for a given tree and bit counts (which need not be
  11595. * optimal).
  11596. * IN assertion: the array bl_count contains the bit length statistics for
  11597. * the given tree and the field len is set for all tree elements.
  11598. * OUT assertion: the field code is set for all tree elements of non
  11599. * zero code length.
  11600. */
  11601. function gen_codes(tree, max_code, bl_count)
  11602. // ct_data *tree; /* the tree to decorate */
  11603. // int max_code; /* largest code with non zero frequency */
  11604. // ushf *bl_count; /* number of codes at each bit length */
  11605. {
  11606. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  11607. var code = 0; /* running code value */
  11608. var bits; /* bit index */
  11609. var n; /* code index */
  11610. /* The distribution counts are first used to generate the code values
  11611. * without bit reversal.
  11612. */
  11613. for (bits = 1; bits <= MAX_BITS; bits++) {
  11614. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  11615. }
  11616. /* Check that the bit counts in bl_count are consistent. The last code
  11617. * must be all ones.
  11618. */
  11619. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  11620. // "inconsistent bit counts");
  11621. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  11622. for (n = 0; n <= max_code; n++) {
  11623. var len = tree[n * 2 + 1]/*.Len*/;
  11624. if (len === 0) { continue; }
  11625. /* Now reverse the bits */
  11626. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  11627. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  11628. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  11629. }
  11630. }
  11631. /* ===========================================================================
  11632. * Initialize the various 'constant' tables.
  11633. */
  11634. function tr_static_init() {
  11635. var n; /* iterates over tree elements */
  11636. var bits; /* bit counter */
  11637. var length; /* length value */
  11638. var code; /* code value */
  11639. var dist; /* distance index */
  11640. var bl_count = new Array(MAX_BITS + 1);
  11641. /* number of codes at each bit length for an optimal tree */
  11642. // do check in _tr_init()
  11643. //if (static_init_done) return;
  11644. /* For some embedded targets, global variables are not initialized: */
  11645. /*#ifdef NO_INIT_GLOBAL_POINTERS
  11646. static_l_desc.static_tree = static_ltree;
  11647. static_l_desc.extra_bits = extra_lbits;
  11648. static_d_desc.static_tree = static_dtree;
  11649. static_d_desc.extra_bits = extra_dbits;
  11650. static_bl_desc.extra_bits = extra_blbits;
  11651. #endif*/
  11652. /* Initialize the mapping length (0..255) -> length code (0..28) */
  11653. length = 0;
  11654. for (code = 0; code < LENGTH_CODES - 1; code++) {
  11655. base_length[code] = length;
  11656. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  11657. _length_code[length++] = code;
  11658. }
  11659. }
  11660. //Assert (length == 256, "tr_static_init: length != 256");
  11661. /* Note that the length 255 (match length 258) can be represented
  11662. * in two different ways: code 284 + 5 bits or code 285, so we
  11663. * overwrite length_code[255] to use the best encoding:
  11664. */
  11665. _length_code[length - 1] = code;
  11666. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  11667. dist = 0;
  11668. for (code = 0; code < 16; code++) {
  11669. base_dist[code] = dist;
  11670. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  11671. _dist_code[dist++] = code;
  11672. }
  11673. }
  11674. //Assert (dist == 256, "tr_static_init: dist != 256");
  11675. dist >>= 7; /* from now on, all distances are divided by 128 */
  11676. for (; code < D_CODES; code++) {
  11677. base_dist[code] = dist << 7;
  11678. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  11679. _dist_code[256 + dist++] = code;
  11680. }
  11681. }
  11682. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  11683. /* Construct the codes of the static literal tree */
  11684. for (bits = 0; bits <= MAX_BITS; bits++) {
  11685. bl_count[bits] = 0;
  11686. }
  11687. n = 0;
  11688. while (n <= 143) {
  11689. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11690. n++;
  11691. bl_count[8]++;
  11692. }
  11693. while (n <= 255) {
  11694. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  11695. n++;
  11696. bl_count[9]++;
  11697. }
  11698. while (n <= 279) {
  11699. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  11700. n++;
  11701. bl_count[7]++;
  11702. }
  11703. while (n <= 287) {
  11704. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11705. n++;
  11706. bl_count[8]++;
  11707. }
  11708. /* Codes 286 and 287 do not exist, but we must include them in the
  11709. * tree construction to get a canonical Huffman tree (longest code
  11710. * all ones)
  11711. */
  11712. gen_codes(static_ltree, L_CODES + 1, bl_count);
  11713. /* The static distance tree is trivial: */
  11714. for (n = 0; n < D_CODES; n++) {
  11715. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  11716. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  11717. }
  11718. // Now data ready and we can init static trees
  11719. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  11720. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  11721. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  11722. //static_init_done = true;
  11723. }
  11724. /* ===========================================================================
  11725. * Initialize a new block.
  11726. */
  11727. function init_block(s) {
  11728. var n; /* iterates over tree elements */
  11729. /* Initialize the trees. */
  11730. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  11731. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  11732. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  11733. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  11734. s.opt_len = s.static_len = 0;
  11735. s.last_lit = s.matches = 0;
  11736. }
  11737. /* ===========================================================================
  11738. * Flush the bit buffer and align the output on a byte boundary
  11739. */
  11740. function bi_windup(s) {
  11741. if (s.bi_valid > 8) {
  11742. put_short(s, s.bi_buf);
  11743. } else if (s.bi_valid > 0) {
  11744. //put_byte(s, (Byte)s->bi_buf);
  11745. s.pending_buf[s.pending++] = s.bi_buf;
  11746. }
  11747. s.bi_buf = 0;
  11748. s.bi_valid = 0;
  11749. }
  11750. /* ===========================================================================
  11751. * Copy a stored block, storing first the length and its
  11752. * one's complement if requested.
  11753. */
  11754. function copy_block(s, buf, len, header)
  11755. //DeflateState *s;
  11756. //charf *buf; /* the input data */
  11757. //unsigned len; /* its length */
  11758. //int header; /* true if block header must be written */
  11759. {
  11760. bi_windup(s); /* align on byte boundary */
  11761. if (header) {
  11762. put_short(s, len);
  11763. put_short(s, ~len);
  11764. }
  11765. // while (len--) {
  11766. // put_byte(s, *buf++);
  11767. // }
  11768. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  11769. s.pending += len;
  11770. }
  11771. /* ===========================================================================
  11772. * Compares to subtrees, using the tree depth as tie breaker when
  11773. * the subtrees have equal frequency. This minimizes the worst case length.
  11774. */
  11775. function smaller(tree, n, m, depth) {
  11776. var _n2 = n * 2;
  11777. var _m2 = m * 2;
  11778. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  11779. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  11780. }
  11781. /* ===========================================================================
  11782. * Restore the heap property by moving down the tree starting at node k,
  11783. * exchanging a node with the smallest of its two sons if necessary, stopping
  11784. * when the heap property is re-established (each father smaller than its
  11785. * two sons).
  11786. */
  11787. function pqdownheap(s, tree, k)
  11788. // deflate_state *s;
  11789. // ct_data *tree; /* the tree to restore */
  11790. // int k; /* node to move down */
  11791. {
  11792. var v = s.heap[k];
  11793. var j = k << 1; /* left son of k */
  11794. while (j <= s.heap_len) {
  11795. /* Set j to the smallest of the two sons: */
  11796. if (j < s.heap_len &&
  11797. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  11798. j++;
  11799. }
  11800. /* Exit if v is smaller than both sons */
  11801. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  11802. /* Exchange v with the smallest son */
  11803. s.heap[k] = s.heap[j];
  11804. k = j;
  11805. /* And continue down the tree, setting j to the left son of k */
  11806. j <<= 1;
  11807. }
  11808. s.heap[k] = v;
  11809. }
  11810. // inlined manually
  11811. // var SMALLEST = 1;
  11812. /* ===========================================================================
  11813. * Send the block data compressed using the given Huffman trees
  11814. */
  11815. function compress_block(s, ltree, dtree)
  11816. // deflate_state *s;
  11817. // const ct_data *ltree; /* literal tree */
  11818. // const ct_data *dtree; /* distance tree */
  11819. {
  11820. var dist; /* distance of matched string */
  11821. var lc; /* match length or unmatched char (if dist == 0) */
  11822. var lx = 0; /* running index in l_buf */
  11823. var code; /* the code to send */
  11824. var extra; /* number of extra bits to send */
  11825. if (s.last_lit !== 0) {
  11826. do {
  11827. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  11828. lc = s.pending_buf[s.l_buf + lx];
  11829. lx++;
  11830. if (dist === 0) {
  11831. send_code(s, lc, ltree); /* send a literal byte */
  11832. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  11833. } else {
  11834. /* Here, lc is the match length - MIN_MATCH */
  11835. code = _length_code[lc];
  11836. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  11837. extra = extra_lbits[code];
  11838. if (extra !== 0) {
  11839. lc -= base_length[code];
  11840. send_bits(s, lc, extra); /* send the extra length bits */
  11841. }
  11842. dist--; /* dist is now the match distance - 1 */
  11843. code = d_code(dist);
  11844. //Assert (code < D_CODES, "bad d_code");
  11845. send_code(s, code, dtree); /* send the distance code */
  11846. extra = extra_dbits[code];
  11847. if (extra !== 0) {
  11848. dist -= base_dist[code];
  11849. send_bits(s, dist, extra); /* send the extra distance bits */
  11850. }
  11851. } /* literal or match pair ? */
  11852. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  11853. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  11854. // "pendingBuf overflow");
  11855. } while (lx < s.last_lit);
  11856. }
  11857. send_code(s, END_BLOCK, ltree);
  11858. }
  11859. /* ===========================================================================
  11860. * Construct one Huffman tree and assigns the code bit strings and lengths.
  11861. * Update the total bit length for the current block.
  11862. * IN assertion: the field freq is set for all tree elements.
  11863. * OUT assertions: the fields len and code are set to the optimal bit length
  11864. * and corresponding code. The length opt_len is updated; static_len is
  11865. * also updated if stree is not null. The field max_code is set.
  11866. */
  11867. function build_tree(s, desc)
  11868. // deflate_state *s;
  11869. // tree_desc *desc; /* the tree descriptor */
  11870. {
  11871. var tree = desc.dyn_tree;
  11872. var stree = desc.stat_desc.static_tree;
  11873. var has_stree = desc.stat_desc.has_stree;
  11874. var elems = desc.stat_desc.elems;
  11875. var n, m; /* iterate over heap elements */
  11876. var max_code = -1; /* largest code with non zero frequency */
  11877. var node; /* new node being created */
  11878. /* Construct the initial heap, with least frequent element in
  11879. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  11880. * heap[0] is not used.
  11881. */
  11882. s.heap_len = 0;
  11883. s.heap_max = HEAP_SIZE;
  11884. for (n = 0; n < elems; n++) {
  11885. if (tree[n * 2]/*.Freq*/ !== 0) {
  11886. s.heap[++s.heap_len] = max_code = n;
  11887. s.depth[n] = 0;
  11888. } else {
  11889. tree[n * 2 + 1]/*.Len*/ = 0;
  11890. }
  11891. }
  11892. /* The pkzip format requires that at least one distance code exists,
  11893. * and that at least one bit should be sent even if there is only one
  11894. * possible code. So to avoid special checks later on we force at least
  11895. * two codes of non zero frequency.
  11896. */
  11897. while (s.heap_len < 2) {
  11898. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  11899. tree[node * 2]/*.Freq*/ = 1;
  11900. s.depth[node] = 0;
  11901. s.opt_len--;
  11902. if (has_stree) {
  11903. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  11904. }
  11905. /* node is 0 or 1 so it does not have extra bits */
  11906. }
  11907. desc.max_code = max_code;
  11908. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  11909. * establish sub-heaps of increasing lengths:
  11910. */
  11911. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  11912. /* Construct the Huffman tree by repeatedly combining the least two
  11913. * frequent nodes.
  11914. */
  11915. node = elems; /* next internal node of the tree */
  11916. do {
  11917. //pqremove(s, tree, n); /* n = node of least frequency */
  11918. /*** pqremove ***/
  11919. n = s.heap[1/*SMALLEST*/];
  11920. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  11921. pqdownheap(s, tree, 1/*SMALLEST*/);
  11922. /***/
  11923. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  11924. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  11925. s.heap[--s.heap_max] = m;
  11926. /* Create a new node father of n and m */
  11927. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  11928. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  11929. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  11930. /* and insert the new node in the heap */
  11931. s.heap[1/*SMALLEST*/] = node++;
  11932. pqdownheap(s, tree, 1/*SMALLEST*/);
  11933. } while (s.heap_len >= 2);
  11934. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  11935. /* At this point, the fields freq and dad are set. We can now
  11936. * generate the bit lengths.
  11937. */
  11938. gen_bitlen(s, desc);
  11939. /* The field len is now set, we can generate the bit codes */
  11940. gen_codes(tree, max_code, s.bl_count);
  11941. }
  11942. /* ===========================================================================
  11943. * Scan a literal or distance tree to determine the frequencies of the codes
  11944. * in the bit length tree.
  11945. */
  11946. function scan_tree(s, tree, max_code)
  11947. // deflate_state *s;
  11948. // ct_data *tree; /* the tree to be scanned */
  11949. // int max_code; /* and its largest code of non zero frequency */
  11950. {
  11951. var n; /* iterates over all tree elements */
  11952. var prevlen = -1; /* last emitted length */
  11953. var curlen; /* length of current code */
  11954. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11955. var count = 0; /* repeat count of the current code */
  11956. var max_count = 7; /* max repeat count */
  11957. var min_count = 4; /* min repeat count */
  11958. if (nextlen === 0) {
  11959. max_count = 138;
  11960. min_count = 3;
  11961. }
  11962. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11963. for (n = 0; n <= max_code; n++) {
  11964. curlen = nextlen;
  11965. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11966. if (++count < max_count && curlen === nextlen) {
  11967. continue;
  11968. } else if (count < min_count) {
  11969. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11970. } else if (curlen !== 0) {
  11971. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11972. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11973. } else if (count <= 10) {
  11974. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11975. } else {
  11976. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11977. }
  11978. count = 0;
  11979. prevlen = curlen;
  11980. if (nextlen === 0) {
  11981. max_count = 138;
  11982. min_count = 3;
  11983. } else if (curlen === nextlen) {
  11984. max_count = 6;
  11985. min_count = 3;
  11986. } else {
  11987. max_count = 7;
  11988. min_count = 4;
  11989. }
  11990. }
  11991. }
  11992. /* ===========================================================================
  11993. * Send a literal or distance tree in compressed form, using the codes in
  11994. * bl_tree.
  11995. */
  11996. function send_tree(s, tree, max_code)
  11997. // deflate_state *s;
  11998. // ct_data *tree; /* the tree to be scanned */
  11999. // int max_code; /* and its largest code of non zero frequency */
  12000. {
  12001. var n; /* iterates over all tree elements */
  12002. var prevlen = -1; /* last emitted length */
  12003. var curlen; /* length of current code */
  12004. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  12005. var count = 0; /* repeat count of the current code */
  12006. var max_count = 7; /* max repeat count */
  12007. var min_count = 4; /* min repeat count */
  12008. /* tree[max_code+1].Len = -1; */ /* guard already set */
  12009. if (nextlen === 0) {
  12010. max_count = 138;
  12011. min_count = 3;
  12012. }
  12013. for (n = 0; n <= max_code; n++) {
  12014. curlen = nextlen;
  12015. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  12016. if (++count < max_count && curlen === nextlen) {
  12017. continue;
  12018. } else if (count < min_count) {
  12019. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  12020. } else if (curlen !== 0) {
  12021. if (curlen !== prevlen) {
  12022. send_code(s, curlen, s.bl_tree);
  12023. count--;
  12024. }
  12025. //Assert(count >= 3 && count <= 6, " 3_6?");
  12026. send_code(s, REP_3_6, s.bl_tree);
  12027. send_bits(s, count - 3, 2);
  12028. } else if (count <= 10) {
  12029. send_code(s, REPZ_3_10, s.bl_tree);
  12030. send_bits(s, count - 3, 3);
  12031. } else {
  12032. send_code(s, REPZ_11_138, s.bl_tree);
  12033. send_bits(s, count - 11, 7);
  12034. }
  12035. count = 0;
  12036. prevlen = curlen;
  12037. if (nextlen === 0) {
  12038. max_count = 138;
  12039. min_count = 3;
  12040. } else if (curlen === nextlen) {
  12041. max_count = 6;
  12042. min_count = 3;
  12043. } else {
  12044. max_count = 7;
  12045. min_count = 4;
  12046. }
  12047. }
  12048. }
  12049. /* ===========================================================================
  12050. * Construct the Huffman tree for the bit lengths and return the index in
  12051. * bl_order of the last bit length code to send.
  12052. */
  12053. function build_bl_tree(s) {
  12054. var max_blindex; /* index of last bit length code of non zero freq */
  12055. /* Determine the bit length frequencies for literal and distance trees */
  12056. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  12057. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  12058. /* Build the bit length tree: */
  12059. build_tree(s, s.bl_desc);
  12060. /* opt_len now includes the length of the tree representations, except
  12061. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  12062. */
  12063. /* Determine the number of bit length codes to send. The pkzip format
  12064. * requires that at least 4 bit length codes be sent. (appnote.txt says
  12065. * 3 but the actual value used is 4.)
  12066. */
  12067. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  12068. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  12069. break;
  12070. }
  12071. }
  12072. /* Update opt_len to include the bit length tree and counts */
  12073. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  12074. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  12075. // s->opt_len, s->static_len));
  12076. return max_blindex;
  12077. }
  12078. /* ===========================================================================
  12079. * Send the header for a block using dynamic Huffman trees: the counts, the
  12080. * lengths of the bit length codes, the literal tree and the distance tree.
  12081. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  12082. */
  12083. function send_all_trees(s, lcodes, dcodes, blcodes)
  12084. // deflate_state *s;
  12085. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  12086. {
  12087. var rank; /* index in bl_order */
  12088. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  12089. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  12090. // "too many codes");
  12091. //Tracev((stderr, "\nbl counts: "));
  12092. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  12093. send_bits(s, dcodes - 1, 5);
  12094. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  12095. for (rank = 0; rank < blcodes; rank++) {
  12096. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  12097. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  12098. }
  12099. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  12100. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  12101. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  12102. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  12103. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  12104. }
  12105. /* ===========================================================================
  12106. * Check if the data type is TEXT or BINARY, using the following algorithm:
  12107. * - TEXT if the two conditions below are satisfied:
  12108. * a) There are no non-portable control characters belonging to the
  12109. * "black list" (0..6, 14..25, 28..31).
  12110. * b) There is at least one printable character belonging to the
  12111. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  12112. * - BINARY otherwise.
  12113. * - The following partially-portable control characters form a
  12114. * "gray list" that is ignored in this detection algorithm:
  12115. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  12116. * IN assertion: the fields Freq of dyn_ltree are set.
  12117. */
  12118. function detect_data_type(s) {
  12119. /* black_mask is the bit mask of black-listed bytes
  12120. * set bits 0..6, 14..25, and 28..31
  12121. * 0xf3ffc07f = binary 11110011111111111100000001111111
  12122. */
  12123. var black_mask = 0xf3ffc07f;
  12124. var n;
  12125. /* Check for non-textual ("black-listed") bytes. */
  12126. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  12127. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  12128. return Z_BINARY;
  12129. }
  12130. }
  12131. /* Check for textual ("white-listed") bytes. */
  12132. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  12133. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  12134. return Z_TEXT;
  12135. }
  12136. for (n = 32; n < LITERALS; n++) {
  12137. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  12138. return Z_TEXT;
  12139. }
  12140. }
  12141. /* There are no "black-listed" or "white-listed" bytes:
  12142. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  12143. */
  12144. return Z_BINARY;
  12145. }
  12146. var static_init_done = false;
  12147. /* ===========================================================================
  12148. * Initialize the tree data structures for a new zlib stream.
  12149. */
  12150. function _tr_init(s) {
  12151. if (!static_init_done) {
  12152. tr_static_init();
  12153. static_init_done = true;
  12154. }
  12155. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  12156. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  12157. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  12158. s.bi_buf = 0;
  12159. s.bi_valid = 0;
  12160. /* Initialize the first block of the first file: */
  12161. init_block(s);
  12162. }
  12163. /* ===========================================================================
  12164. * Send a stored block
  12165. */
  12166. function _tr_stored_block(s, buf, stored_len, last)
  12167. //DeflateState *s;
  12168. //charf *buf; /* input block */
  12169. //ulg stored_len; /* length of input block */
  12170. //int last; /* one if this is the last block for a file */
  12171. {
  12172. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  12173. copy_block(s, buf, stored_len, true); /* with header */
  12174. }
  12175. /* ===========================================================================
  12176. * Send one empty static block to give enough lookahead for inflate.
  12177. * This takes 10 bits, of which 7 may remain in the bit buffer.
  12178. */
  12179. function _tr_align(s) {
  12180. send_bits(s, STATIC_TREES << 1, 3);
  12181. send_code(s, END_BLOCK, static_ltree);
  12182. bi_flush(s);
  12183. }
  12184. /* ===========================================================================
  12185. * Determine the best encoding for the current block: dynamic trees, static
  12186. * trees or store, and output the encoded block to the zip file.
  12187. */
  12188. function _tr_flush_block(s, buf, stored_len, last)
  12189. //DeflateState *s;
  12190. //charf *buf; /* input block, or NULL if too old */
  12191. //ulg stored_len; /* length of input block */
  12192. //int last; /* one if this is the last block for a file */
  12193. {
  12194. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  12195. var max_blindex = 0; /* index of last bit length code of non zero freq */
  12196. /* Build the Huffman trees unless a stored block is forced */
  12197. if (s.level > 0) {
  12198. /* Check if the file is binary or text */
  12199. if (s.strm.data_type === Z_UNKNOWN) {
  12200. s.strm.data_type = detect_data_type(s);
  12201. }
  12202. /* Construct the literal and distance trees */
  12203. build_tree(s, s.l_desc);
  12204. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  12205. // s->static_len));
  12206. build_tree(s, s.d_desc);
  12207. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  12208. // s->static_len));
  12209. /* At this point, opt_len and static_len are the total bit lengths of
  12210. * the compressed block data, excluding the tree representations.
  12211. */
  12212. /* Build the bit length tree for the above two trees, and get the index
  12213. * in bl_order of the last bit length code to send.
  12214. */
  12215. max_blindex = build_bl_tree(s);
  12216. /* Determine the best encoding. Compute the block lengths in bytes. */
  12217. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  12218. static_lenb = (s.static_len + 3 + 7) >>> 3;
  12219. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  12220. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  12221. // s->last_lit));
  12222. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  12223. } else {
  12224. // Assert(buf != (char*)0, "lost buf");
  12225. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  12226. }
  12227. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  12228. /* 4: two words for the lengths */
  12229. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  12230. * Otherwise we can't have processed more than WSIZE input bytes since
  12231. * the last block flush, because compression would have been
  12232. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  12233. * transform a block into a stored block.
  12234. */
  12235. _tr_stored_block(s, buf, stored_len, last);
  12236. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  12237. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  12238. compress_block(s, static_ltree, static_dtree);
  12239. } else {
  12240. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  12241. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  12242. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  12243. }
  12244. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  12245. /* The above check is made mod 2^32, for files larger than 512 MB
  12246. * and uLong implemented on 32 bits.
  12247. */
  12248. init_block(s);
  12249. if (last) {
  12250. bi_windup(s);
  12251. }
  12252. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  12253. // s->compressed_len-7*last));
  12254. }
  12255. /* ===========================================================================
  12256. * Save the match info and tally the frequency counts. Return true if
  12257. * the current block must be flushed.
  12258. */
  12259. function _tr_tally(s, dist, lc)
  12260. // deflate_state *s;
  12261. // unsigned dist; /* distance of matched string */
  12262. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  12263. {
  12264. //var out_length, in_length, dcode;
  12265. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  12266. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  12267. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  12268. s.last_lit++;
  12269. if (dist === 0) {
  12270. /* lc is the unmatched char */
  12271. s.dyn_ltree[lc * 2]/*.Freq*/++;
  12272. } else {
  12273. s.matches++;
  12274. /* Here, lc is the match length - MIN_MATCH */
  12275. dist--; /* dist = match distance - 1 */
  12276. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  12277. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  12278. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  12279. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  12280. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  12281. }
  12282. // (!) This block is disabled in zlib defaults,
  12283. // don't enable it for binary compatibility
  12284. //#ifdef TRUNCATE_BLOCK
  12285. // /* Try to guess if it is profitable to stop the current block here */
  12286. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  12287. // /* Compute an upper bound for the compressed length */
  12288. // out_length = s.last_lit*8;
  12289. // in_length = s.strstart - s.block_start;
  12290. //
  12291. // for (dcode = 0; dcode < D_CODES; dcode++) {
  12292. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  12293. // }
  12294. // out_length >>>= 3;
  12295. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  12296. // // s->last_lit, in_length, out_length,
  12297. // // 100L - out_length*100L/in_length));
  12298. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  12299. // return true;
  12300. // }
  12301. // }
  12302. //#endif
  12303. return (s.last_lit === s.lit_bufsize - 1);
  12304. /* We avoid equality with lit_bufsize because of wraparound at 64K
  12305. * on 16 bit machines and because stored blocks are restricted to
  12306. * 64K-1 bytes.
  12307. */
  12308. }
  12309. exports._tr_init = _tr_init;
  12310. exports._tr_stored_block = _tr_stored_block;
  12311. exports._tr_flush_block = _tr_flush_block;
  12312. exports._tr_tally = _tr_tally;
  12313. exports._tr_align = _tr_align;
  12314. }, { "../utils/common": 50 }], 62: [function (require, module, exports) {
  12315. 'use strict';
  12316. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  12317. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  12318. //
  12319. // This software is provided 'as-is', without any express or implied
  12320. // warranty. In no event will the authors be held liable for any damages
  12321. // arising from the use of this software.
  12322. //
  12323. // Permission is granted to anyone to use this software for any purpose,
  12324. // including commercial applications, and to alter it and redistribute it
  12325. // freely, subject to the following restrictions:
  12326. //
  12327. // 1. The origin of this software must not be misrepresented; you must not
  12328. // claim that you wrote the original software. If you use this software
  12329. // in a product, an acknowledgment in the product documentation would be
  12330. // appreciated but is not required.
  12331. // 2. Altered source versions must be plainly marked as such, and must not be
  12332. // misrepresented as being the original software.
  12333. // 3. This notice may not be removed or altered from any source distribution.
  12334. function ZStream() {
  12335. /* next input byte */
  12336. this.input = null; // JS specific, because we have no pointers
  12337. this.next_in = 0;
  12338. /* number of bytes available at input */
  12339. this.avail_in = 0;
  12340. /* total number of input bytes read so far */
  12341. this.total_in = 0;
  12342. /* next output byte should be put there */
  12343. this.output = null; // JS specific, because we have no pointers
  12344. this.next_out = 0;
  12345. /* remaining free space at output */
  12346. this.avail_out = 0;
  12347. /* total number of bytes output so far */
  12348. this.total_out = 0;
  12349. /* last error message, NULL if no error */
  12350. this.msg = ''/*Z_NULL*/;
  12351. /* not visible by applications */
  12352. this.state = null;
  12353. /* best guess about the data type: binary or text */
  12354. this.data_type = 2/*Z_UNKNOWN*/;
  12355. /* adler32 value of the uncompressed data */
  12356. this.adler = 0;
  12357. }
  12358. module.exports = ZStream;
  12359. }, {}], 63: [function (require, module, exports) {
  12360. (function (process) {
  12361. 'use strict';
  12362. if (typeof process === 'undefined' ||
  12363. !process.version ||
  12364. process.version.indexOf('v0.') === 0 ||
  12365. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  12366. module.exports = { nextTick: nextTick };
  12367. } else {
  12368. module.exports = process
  12369. }
  12370. function nextTick(fn, arg1, arg2, arg3) {
  12371. if (typeof fn !== 'function') {
  12372. throw new TypeError('"callback" argument must be a function');
  12373. }
  12374. var len = arguments.length;
  12375. var args, i;
  12376. switch (len) {
  12377. case 0:
  12378. case 1:
  12379. return process.nextTick(fn);
  12380. case 2:
  12381. return process.nextTick(function afterTickOne() {
  12382. fn.call(null, arg1);
  12383. });
  12384. case 3:
  12385. return process.nextTick(function afterTickTwo() {
  12386. fn.call(null, arg1, arg2);
  12387. });
  12388. case 4:
  12389. return process.nextTick(function afterTickThree() {
  12390. fn.call(null, arg1, arg2, arg3);
  12391. });
  12392. default:
  12393. args = new Array(len - 1);
  12394. i = 0;
  12395. while (i < args.length) {
  12396. args[i++] = arguments[i];
  12397. }
  12398. return process.nextTick(function afterTick() {
  12399. fn.apply(null, args);
  12400. });
  12401. }
  12402. }
  12403. }).call(this, require('_process'))
  12404. }, { "_process": 64 }], 64: [function (require, module, exports) {
  12405. // shim for using process in browser
  12406. var process = module.exports = {};
  12407. // cached from whatever global is present so that test runners that stub it
  12408. // don't break things. But we need to wrap it in a try catch in case it is
  12409. // wrapped in strict mode code which doesn't define any globals. It's inside a
  12410. // function because try/catches deoptimize in certain engines.
  12411. var cachedSetTimeout;
  12412. var cachedClearTimeout;
  12413. function defaultSetTimout() {
  12414. throw new Error('setTimeout has not been defined');
  12415. }
  12416. function defaultClearTimeout() {
  12417. throw new Error('clearTimeout has not been defined');
  12418. }
  12419. (function () {
  12420. try {
  12421. if (typeof setTimeout === 'function') {
  12422. cachedSetTimeout = setTimeout;
  12423. } else {
  12424. cachedSetTimeout = defaultSetTimout;
  12425. }
  12426. } catch (e) {
  12427. cachedSetTimeout = defaultSetTimout;
  12428. }
  12429. try {
  12430. if (typeof clearTimeout === 'function') {
  12431. cachedClearTimeout = clearTimeout;
  12432. } else {
  12433. cachedClearTimeout = defaultClearTimeout;
  12434. }
  12435. } catch (e) {
  12436. cachedClearTimeout = defaultClearTimeout;
  12437. }
  12438. }())
  12439. function runTimeout(fun) {
  12440. if (cachedSetTimeout === setTimeout) {
  12441. //normal enviroments in sane situations
  12442. return setTimeout(fun, 0);
  12443. }
  12444. // if setTimeout wasn't available but was latter defined
  12445. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12446. cachedSetTimeout = setTimeout;
  12447. return setTimeout(fun, 0);
  12448. }
  12449. try {
  12450. // when when somebody has screwed with setTimeout but no I.E. maddness
  12451. return cachedSetTimeout(fun, 0);
  12452. } catch (e) {
  12453. try {
  12454. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12455. return cachedSetTimeout.call(null, fun, 0);
  12456. } catch (e) {
  12457. // 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
  12458. return cachedSetTimeout.call(this, fun, 0);
  12459. }
  12460. }
  12461. }
  12462. function runClearTimeout(marker) {
  12463. if (cachedClearTimeout === clearTimeout) {
  12464. //normal enviroments in sane situations
  12465. return clearTimeout(marker);
  12466. }
  12467. // if clearTimeout wasn't available but was latter defined
  12468. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12469. cachedClearTimeout = clearTimeout;
  12470. return clearTimeout(marker);
  12471. }
  12472. try {
  12473. // when when somebody has screwed with setTimeout but no I.E. maddness
  12474. return cachedClearTimeout(marker);
  12475. } catch (e) {
  12476. try {
  12477. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12478. return cachedClearTimeout.call(null, marker);
  12479. } catch (e) {
  12480. // 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.
  12481. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  12482. return cachedClearTimeout.call(this, marker);
  12483. }
  12484. }
  12485. }
  12486. var queue = [];
  12487. var draining = false;
  12488. var currentQueue;
  12489. var queueIndex = -1;
  12490. function cleanUpNextTick() {
  12491. if (!draining || !currentQueue) {
  12492. return;
  12493. }
  12494. draining = false;
  12495. if (currentQueue.length) {
  12496. queue = currentQueue.concat(queue);
  12497. } else {
  12498. queueIndex = -1;
  12499. }
  12500. if (queue.length) {
  12501. drainQueue();
  12502. }
  12503. }
  12504. function drainQueue() {
  12505. if (draining) {
  12506. return;
  12507. }
  12508. var timeout = runTimeout(cleanUpNextTick);
  12509. draining = true;
  12510. var len = queue.length;
  12511. while (len) {
  12512. currentQueue = queue;
  12513. queue = [];
  12514. while (++queueIndex < len) {
  12515. if (currentQueue) {
  12516. currentQueue[queueIndex].run();
  12517. }
  12518. }
  12519. queueIndex = -1;
  12520. len = queue.length;
  12521. }
  12522. currentQueue = null;
  12523. draining = false;
  12524. runClearTimeout(timeout);
  12525. }
  12526. process.nextTick = function (fun) {
  12527. var args = new Array(arguments.length - 1);
  12528. if (arguments.length > 1) {
  12529. for (var i = 1; i < arguments.length; i++) {
  12530. args[i - 1] = arguments[i];
  12531. }
  12532. }
  12533. queue.push(new Item(fun, args));
  12534. if (queue.length === 1 && !draining) {
  12535. runTimeout(drainQueue);
  12536. }
  12537. };
  12538. // v8 likes predictible objects
  12539. function Item(fun, array) {
  12540. this.fun = fun;
  12541. this.array = array;
  12542. }
  12543. Item.prototype.run = function () {
  12544. this.fun.apply(null, this.array);
  12545. };
  12546. process.title = 'browser';
  12547. process.browser = true;
  12548. process.env = {};
  12549. process.argv = [];
  12550. process.version = ''; // empty string to avoid regexp issues
  12551. process.versions = {};
  12552. function noop() { }
  12553. process.on = noop;
  12554. process.addListener = noop;
  12555. process.once = noop;
  12556. process.off = noop;
  12557. process.removeListener = noop;
  12558. process.removeAllListeners = noop;
  12559. process.emit = noop;
  12560. process.prependListener = noop;
  12561. process.prependOnceListener = noop;
  12562. process.listeners = function (name) { return [] }
  12563. process.binding = function (name) {
  12564. throw new Error('process.binding is not supported');
  12565. };
  12566. process.cwd = function () { return '/' };
  12567. process.chdir = function (dir) {
  12568. throw new Error('process.chdir is not supported');
  12569. };
  12570. process.umask = function () { return 0; };
  12571. }, {}], 65: [function (require, module, exports) {
  12572. module.exports = require('./lib/_stream_duplex.js');
  12573. }, { "./lib/_stream_duplex.js": 66 }], 66: [function (require, module, exports) {
  12574. // Copyright Joyent, Inc. and other Node contributors.
  12575. //
  12576. // Permission is hereby granted, free of charge, to any person obtaining a
  12577. // copy of this software and associated documentation files (the
  12578. // "Software"), to deal in the Software without restriction, including
  12579. // without limitation the rights to use, copy, modify, merge, publish,
  12580. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12581. // persons to whom the Software is furnished to do so, subject to the
  12582. // following conditions:
  12583. //
  12584. // The above copyright notice and this permission notice shall be included
  12585. // in all copies or substantial portions of the Software.
  12586. //
  12587. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12588. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12589. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12590. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12591. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12592. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12593. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12594. // a duplex stream is just a stream that is both readable and writable.
  12595. // Since JS doesn't have multiple prototypal inheritance, this class
  12596. // prototypally inherits from Readable, and then parasitically from
  12597. // Writable.
  12598. 'use strict';
  12599. /*<replacement>*/
  12600. var pna = require('process-nextick-args');
  12601. /*</replacement>*/
  12602. /*<replacement>*/
  12603. var objectKeys = Object.keys || function (obj) {
  12604. var keys = [];
  12605. for (var key in obj) {
  12606. keys.push(key);
  12607. } return keys;
  12608. };
  12609. /*</replacement>*/
  12610. module.exports = Duplex;
  12611. /*<replacement>*/
  12612. var util = Object.create(require('core-util-is'));
  12613. util.inherits = require('inherits');
  12614. /*</replacement>*/
  12615. var Readable = require('./_stream_readable');
  12616. var Writable = require('./_stream_writable');
  12617. util.inherits(Duplex, Readable);
  12618. {
  12619. // avoid scope creep, the keys array can then be collected
  12620. var keys = objectKeys(Writable.prototype);
  12621. for (var v = 0; v < keys.length; v++) {
  12622. var method = keys[v];
  12623. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  12624. }
  12625. }
  12626. function Duplex(options) {
  12627. if (!(this instanceof Duplex)) return new Duplex(options);
  12628. Readable.call(this, options);
  12629. Writable.call(this, options);
  12630. if (options && options.readable === false) this.readable = false;
  12631. if (options && options.writable === false) this.writable = false;
  12632. this.allowHalfOpen = true;
  12633. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  12634. this.once('end', onend);
  12635. }
  12636. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  12637. // making it explicit this property is not enumerable
  12638. // because otherwise some prototype manipulation in
  12639. // userland will fail
  12640. enumerable: false,
  12641. get: function () {
  12642. return this._writableState.highWaterMark;
  12643. }
  12644. });
  12645. // the no-half-open enforcer
  12646. function onend() {
  12647. // if we allow half-open state, or if the writable side ended,
  12648. // then we're ok.
  12649. if (this.allowHalfOpen || this._writableState.ended) return;
  12650. // no more data can be written.
  12651. // But allow more writes to happen in this tick.
  12652. pna.nextTick(onEndNT, this);
  12653. }
  12654. function onEndNT(self) {
  12655. self.end();
  12656. }
  12657. Object.defineProperty(Duplex.prototype, 'destroyed', {
  12658. get: function () {
  12659. if (this._readableState === undefined || this._writableState === undefined) {
  12660. return false;
  12661. }
  12662. return this._readableState.destroyed && this._writableState.destroyed;
  12663. },
  12664. set: function (value) {
  12665. // we ignore the value if the stream
  12666. // has not been initialized yet
  12667. if (this._readableState === undefined || this._writableState === undefined) {
  12668. return;
  12669. }
  12670. // backward compatibility, the user is explicitly
  12671. // managing destroyed
  12672. this._readableState.destroyed = value;
  12673. this._writableState.destroyed = value;
  12674. }
  12675. });
  12676. Duplex.prototype._destroy = function (err, cb) {
  12677. this.push(null);
  12678. this.end();
  12679. pna.nextTick(cb, err);
  12680. };
  12681. }, { "./_stream_readable": 68, "./_stream_writable": 70, "core-util-is": 4, "inherits": 8, "process-nextick-args": 63 }], 67: [function (require, module, exports) {
  12682. // Copyright Joyent, Inc. and other Node contributors.
  12683. //
  12684. // Permission is hereby granted, free of charge, to any person obtaining a
  12685. // copy of this software and associated documentation files (the
  12686. // "Software"), to deal in the Software without restriction, including
  12687. // without limitation the rights to use, copy, modify, merge, publish,
  12688. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12689. // persons to whom the Software is furnished to do so, subject to the
  12690. // following conditions:
  12691. //
  12692. // The above copyright notice and this permission notice shall be included
  12693. // in all copies or substantial portions of the Software.
  12694. //
  12695. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12696. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12697. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12698. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12699. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12700. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12701. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12702. // a passthrough stream.
  12703. // basically just the most minimal sort of Transform stream.
  12704. // Every written chunk gets output as-is.
  12705. 'use strict';
  12706. module.exports = PassThrough;
  12707. var Transform = require('./_stream_transform');
  12708. /*<replacement>*/
  12709. var util = Object.create(require('core-util-is'));
  12710. util.inherits = require('inherits');
  12711. /*</replacement>*/
  12712. util.inherits(PassThrough, Transform);
  12713. function PassThrough(options) {
  12714. if (!(this instanceof PassThrough)) return new PassThrough(options);
  12715. Transform.call(this, options);
  12716. }
  12717. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  12718. cb(null, chunk);
  12719. };
  12720. }, { "./_stream_transform": 69, "core-util-is": 4, "inherits": 8 }], 68: [function (require, module, exports) {
  12721. (function (process, global) {
  12722. // Copyright Joyent, Inc. and other Node contributors.
  12723. //
  12724. // Permission is hereby granted, free of charge, to any person obtaining a
  12725. // copy of this software and associated documentation files (the
  12726. // "Software"), to deal in the Software without restriction, including
  12727. // without limitation the rights to use, copy, modify, merge, publish,
  12728. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12729. // persons to whom the Software is furnished to do so, subject to the
  12730. // following conditions:
  12731. //
  12732. // The above copyright notice and this permission notice shall be included
  12733. // in all copies or substantial portions of the Software.
  12734. //
  12735. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12736. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12737. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12738. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12739. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12740. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12741. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12742. 'use strict';
  12743. /*<replacement>*/
  12744. var pna = require('process-nextick-args');
  12745. /*</replacement>*/
  12746. module.exports = Readable;
  12747. /*<replacement>*/
  12748. var isArray = require('isarray');
  12749. /*</replacement>*/
  12750. /*<replacement>*/
  12751. var Duplex;
  12752. /*</replacement>*/
  12753. Readable.ReadableState = ReadableState;
  12754. /*<replacement>*/
  12755. var EE = require('events').EventEmitter;
  12756. var EElistenerCount = function (emitter, type) {
  12757. return emitter.listeners(type).length;
  12758. };
  12759. /*</replacement>*/
  12760. /*<replacement>*/
  12761. var Stream = require('./internal/streams/stream');
  12762. /*</replacement>*/
  12763. /*<replacement>*/
  12764. var Buffer = require('safe-buffer').Buffer;
  12765. var OurUint8Array = global.Uint8Array || function () { };
  12766. function _uint8ArrayToBuffer(chunk) {
  12767. return Buffer.from(chunk);
  12768. }
  12769. function _isUint8Array(obj) {
  12770. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12771. }
  12772. /*</replacement>*/
  12773. /*<replacement>*/
  12774. var util = Object.create(require('core-util-is'));
  12775. util.inherits = require('inherits');
  12776. /*</replacement>*/
  12777. /*<replacement>*/
  12778. var debugUtil = require('util');
  12779. var debug = void 0;
  12780. if (debugUtil && debugUtil.debuglog) {
  12781. debug = debugUtil.debuglog('stream');
  12782. } else {
  12783. debug = function () { };
  12784. }
  12785. /*</replacement>*/
  12786. var BufferList = require('./internal/streams/BufferList');
  12787. var destroyImpl = require('./internal/streams/destroy');
  12788. var StringDecoder;
  12789. util.inherits(Readable, Stream);
  12790. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  12791. function prependListener(emitter, event, fn) {
  12792. // Sadly this is not cacheable as some libraries bundle their own
  12793. // event emitter implementation with them.
  12794. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  12795. // This is a hack to make sure that our error handler is attached before any
  12796. // userland ones. NEVER DO THIS. This is here only because this code needs
  12797. // to continue to work with older versions of Node.js that do not include
  12798. // the prependListener() method. The goal is to eventually remove this hack.
  12799. 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]];
  12800. }
  12801. function ReadableState(options, stream) {
  12802. Duplex = Duplex || require('./_stream_duplex');
  12803. options = options || {};
  12804. // Duplex streams are both readable and writable, but share
  12805. // the same options object.
  12806. // However, some cases require setting options to different
  12807. // values for the readable and the writable sides of the duplex stream.
  12808. // These options can be provided separately as readableXXX and writableXXX.
  12809. var isDuplex = stream instanceof Duplex;
  12810. // object stream flag. Used to make read(n) ignore n and to
  12811. // make all the buffer merging and length checks go away
  12812. this.objectMode = !!options.objectMode;
  12813. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  12814. // the point at which it stops calling _read() to fill the buffer
  12815. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  12816. var hwm = options.highWaterMark;
  12817. var readableHwm = options.readableHighWaterMark;
  12818. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  12819. if (hwm || hwm === 0) this.highWaterMark = hwm; else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm; else this.highWaterMark = defaultHwm;
  12820. // cast to ints.
  12821. this.highWaterMark = Math.floor(this.highWaterMark);
  12822. // A linked list is used to store data chunks instead of an array because the
  12823. // linked list can remove elements from the beginning faster than
  12824. // array.shift()
  12825. this.buffer = new BufferList();
  12826. this.length = 0;
  12827. this.pipes = null;
  12828. this.pipesCount = 0;
  12829. this.flowing = null;
  12830. this.ended = false;
  12831. this.endEmitted = false;
  12832. this.reading = false;
  12833. // a flag to be able to tell if the event 'readable'/'data' is emitted
  12834. // immediately, or on a later tick. We set this to true at first, because
  12835. // any actions that shouldn't happen until "later" should generally also
  12836. // not happen before the first read call.
  12837. this.sync = true;
  12838. // whenever we return null, then we set a flag to say
  12839. // that we're awaiting a 'readable' event emission.
  12840. this.needReadable = false;
  12841. this.emittedReadable = false;
  12842. this.readableListening = false;
  12843. this.resumeScheduled = false;
  12844. // has it been destroyed
  12845. this.destroyed = false;
  12846. // Crypto is kind of old and crusty. Historically, its default string
  12847. // encoding is 'binary' so we have to make this configurable.
  12848. // Everything else in the universe uses 'utf8', though.
  12849. this.defaultEncoding = options.defaultEncoding || 'utf8';
  12850. // the number of writers that are awaiting a drain event in .pipe()s
  12851. this.awaitDrain = 0;
  12852. // if true, a maybeReadMore has been scheduled
  12853. this.readingMore = false;
  12854. this.decoder = null;
  12855. this.encoding = null;
  12856. if (options.encoding) {
  12857. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12858. this.decoder = new StringDecoder(options.encoding);
  12859. this.encoding = options.encoding;
  12860. }
  12861. }
  12862. function Readable(options) {
  12863. Duplex = Duplex || require('./_stream_duplex');
  12864. if (!(this instanceof Readable)) return new Readable(options);
  12865. this._readableState = new ReadableState(options, this);
  12866. // legacy
  12867. this.readable = true;
  12868. if (options) {
  12869. if (typeof options.read === 'function') this._read = options.read;
  12870. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12871. }
  12872. Stream.call(this);
  12873. }
  12874. Object.defineProperty(Readable.prototype, 'destroyed', {
  12875. get: function () {
  12876. if (this._readableState === undefined) {
  12877. return false;
  12878. }
  12879. return this._readableState.destroyed;
  12880. },
  12881. set: function (value) {
  12882. // we ignore the value if the stream
  12883. // has not been initialized yet
  12884. if (!this._readableState) {
  12885. return;
  12886. }
  12887. // backward compatibility, the user is explicitly
  12888. // managing destroyed
  12889. this._readableState.destroyed = value;
  12890. }
  12891. });
  12892. Readable.prototype.destroy = destroyImpl.destroy;
  12893. Readable.prototype._undestroy = destroyImpl.undestroy;
  12894. Readable.prototype._destroy = function (err, cb) {
  12895. this.push(null);
  12896. cb(err);
  12897. };
  12898. // Manually shove something into the read() buffer.
  12899. // This returns true if the highWaterMark has not been hit yet,
  12900. // similar to how Writable.write() returns true if you should
  12901. // write() some more.
  12902. Readable.prototype.push = function (chunk, encoding) {
  12903. var state = this._readableState;
  12904. var skipChunkCheck;
  12905. if (!state.objectMode) {
  12906. if (typeof chunk === 'string') {
  12907. encoding = encoding || state.defaultEncoding;
  12908. if (encoding !== state.encoding) {
  12909. chunk = Buffer.from(chunk, encoding);
  12910. encoding = '';
  12911. }
  12912. skipChunkCheck = true;
  12913. }
  12914. } else {
  12915. skipChunkCheck = true;
  12916. }
  12917. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  12918. };
  12919. // Unshift should *always* be something directly out of read()
  12920. Readable.prototype.unshift = function (chunk) {
  12921. return readableAddChunk(this, chunk, null, true, false);
  12922. };
  12923. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  12924. var state = stream._readableState;
  12925. if (chunk === null) {
  12926. state.reading = false;
  12927. onEofChunk(stream, state);
  12928. } else {
  12929. var er;
  12930. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  12931. if (er) {
  12932. stream.emit('error', er);
  12933. } else if (state.objectMode || chunk && chunk.length > 0) {
  12934. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  12935. chunk = _uint8ArrayToBuffer(chunk);
  12936. }
  12937. if (addToFront) {
  12938. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event')); else addChunk(stream, state, chunk, true);
  12939. } else if (state.ended) {
  12940. stream.emit('error', new Error('stream.push() after EOF'));
  12941. } else {
  12942. state.reading = false;
  12943. if (state.decoder && !encoding) {
  12944. chunk = state.decoder.write(chunk);
  12945. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); else maybeReadMore(stream, state);
  12946. } else {
  12947. addChunk(stream, state, chunk, false);
  12948. }
  12949. }
  12950. } else if (!addToFront) {
  12951. state.reading = false;
  12952. }
  12953. }
  12954. return needMoreData(state);
  12955. }
  12956. function addChunk(stream, state, chunk, addToFront) {
  12957. if (state.flowing && state.length === 0 && !state.sync) {
  12958. stream.emit('data', chunk);
  12959. stream.read(0);
  12960. } else {
  12961. // update the buffer info.
  12962. state.length += state.objectMode ? 1 : chunk.length;
  12963. if (addToFront) state.buffer.unshift(chunk); else state.buffer.push(chunk);
  12964. if (state.needReadable) emitReadable(stream);
  12965. }
  12966. maybeReadMore(stream, state);
  12967. }
  12968. function chunkInvalid(state, chunk) {
  12969. var er;
  12970. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12971. er = new TypeError('Invalid non-string/buffer chunk');
  12972. }
  12973. return er;
  12974. }
  12975. // if it's past the high water mark, we can push in some more.
  12976. // Also, if we have no data yet, we can stand some
  12977. // more bytes. This is to work around cases where hwm=0,
  12978. // such as the repl. Also, if the push() triggered a
  12979. // readable event, and the user called read(largeNumber) such that
  12980. // needReadable was set, then we ought to push more, so that another
  12981. // 'readable' event will be triggered.
  12982. function needMoreData(state) {
  12983. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  12984. }
  12985. Readable.prototype.isPaused = function () {
  12986. return this._readableState.flowing === false;
  12987. };
  12988. // backwards compatibility.
  12989. Readable.prototype.setEncoding = function (enc) {
  12990. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12991. this._readableState.decoder = new StringDecoder(enc);
  12992. this._readableState.encoding = enc;
  12993. return this;
  12994. };
  12995. // Don't raise the hwm > 8MB
  12996. var MAX_HWM = 0x800000;
  12997. function computeNewHighWaterMark(n) {
  12998. if (n >= MAX_HWM) {
  12999. n = MAX_HWM;
  13000. } else {
  13001. // Get the next highest power of 2 to prevent increasing hwm excessively in
  13002. // tiny amounts
  13003. n--;
  13004. n |= n >>> 1;
  13005. n |= n >>> 2;
  13006. n |= n >>> 4;
  13007. n |= n >>> 8;
  13008. n |= n >>> 16;
  13009. n++;
  13010. }
  13011. return n;
  13012. }
  13013. // This function is designed to be inlinable, so please take care when making
  13014. // changes to the function body.
  13015. function howMuchToRead(n, state) {
  13016. if (n <= 0 || state.length === 0 && state.ended) return 0;
  13017. if (state.objectMode) return 1;
  13018. if (n !== n) {
  13019. // Only flow one buffer at a time
  13020. if (state.flowing && state.length) return state.buffer.head.data.length; else return state.length;
  13021. }
  13022. // If we're asking for more than the current hwm, then raise the hwm.
  13023. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  13024. if (n <= state.length) return n;
  13025. // Don't have enough
  13026. if (!state.ended) {
  13027. state.needReadable = true;
  13028. return 0;
  13029. }
  13030. return state.length;
  13031. }
  13032. // you can override either this method, or the async _read(n) below.
  13033. Readable.prototype.read = function (n) {
  13034. debug('read', n);
  13035. n = parseInt(n, 10);
  13036. var state = this._readableState;
  13037. var nOrig = n;
  13038. if (n !== 0) state.emittedReadable = false;
  13039. // if we're doing read(0) to trigger a readable event, but we
  13040. // already have a bunch of data in the buffer, then just trigger
  13041. // the 'readable' event and move on.
  13042. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  13043. debug('read: emitReadable', state.length, state.ended);
  13044. if (state.length === 0 && state.ended) endReadable(this); else emitReadable(this);
  13045. return null;
  13046. }
  13047. n = howMuchToRead(n, state);
  13048. // if we've ended, and we're now clear, then finish it up.
  13049. if (n === 0 && state.ended) {
  13050. if (state.length === 0) endReadable(this);
  13051. return null;
  13052. }
  13053. // All the actual chunk generation logic needs to be
  13054. // *below* the call to _read. The reason is that in certain
  13055. // synthetic stream cases, such as passthrough streams, _read
  13056. // may be a completely synchronous operation which may change
  13057. // the state of the read buffer, providing enough data when
  13058. // before there was *not* enough.
  13059. //
  13060. // So, the steps are:
  13061. // 1. Figure out what the state of things will be after we do
  13062. // a read from the buffer.
  13063. //
  13064. // 2. If that resulting state will trigger a _read, then call _read.
  13065. // Note that this may be asynchronous, or synchronous. Yes, it is
  13066. // deeply ugly to write APIs this way, but that still doesn't mean
  13067. // that the Readable class should behave improperly, as streams are
  13068. // designed to be sync/async agnostic.
  13069. // Take note if the _read call is sync or async (ie, if the read call
  13070. // has returned yet), so that we know whether or not it's safe to emit
  13071. // 'readable' etc.
  13072. //
  13073. // 3. Actually pull the requested chunks out of the buffer and return.
  13074. // if we need a readable event, then we need to do some reading.
  13075. var doRead = state.needReadable;
  13076. debug('need readable', doRead);
  13077. // if we currently have less than the highWaterMark, then also read some
  13078. if (state.length === 0 || state.length - n < state.highWaterMark) {
  13079. doRead = true;
  13080. debug('length less than watermark', doRead);
  13081. }
  13082. // however, if we've ended, then there's no point, and if we're already
  13083. // reading, then it's unnecessary.
  13084. if (state.ended || state.reading) {
  13085. doRead = false;
  13086. debug('reading or ended', doRead);
  13087. } else if (doRead) {
  13088. debug('do read');
  13089. state.reading = true;
  13090. state.sync = true;
  13091. // if the length is currently zero, then we *need* a readable event.
  13092. if (state.length === 0) state.needReadable = true;
  13093. // call internal read method
  13094. this._read(state.highWaterMark);
  13095. state.sync = false;
  13096. // If _read pushed data synchronously, then `reading` will be false,
  13097. // and we need to re-evaluate how much data we can return to the user.
  13098. if (!state.reading) n = howMuchToRead(nOrig, state);
  13099. }
  13100. var ret;
  13101. if (n > 0) ret = fromList(n, state); else ret = null;
  13102. if (ret === null) {
  13103. state.needReadable = true;
  13104. n = 0;
  13105. } else {
  13106. state.length -= n;
  13107. }
  13108. if (state.length === 0) {
  13109. // If we have nothing in the buffer, then we want to know
  13110. // as soon as we *do* get something into the buffer.
  13111. if (!state.ended) state.needReadable = true;
  13112. // If we tried to read() past the EOF, then emit end on the next tick.
  13113. if (nOrig !== n && state.ended) endReadable(this);
  13114. }
  13115. if (ret !== null) this.emit('data', ret);
  13116. return ret;
  13117. };
  13118. function onEofChunk(stream, state) {
  13119. if (state.ended) return;
  13120. if (state.decoder) {
  13121. var chunk = state.decoder.end();
  13122. if (chunk && chunk.length) {
  13123. state.buffer.push(chunk);
  13124. state.length += state.objectMode ? 1 : chunk.length;
  13125. }
  13126. }
  13127. state.ended = true;
  13128. // emit 'readable' now to make sure it gets picked up.
  13129. emitReadable(stream);
  13130. }
  13131. // Don't emit readable right away in sync mode, because this can trigger
  13132. // another read() call => stack overflow. This way, it might trigger
  13133. // a nextTick recursion warning, but that's not so bad.
  13134. function emitReadable(stream) {
  13135. var state = stream._readableState;
  13136. state.needReadable = false;
  13137. if (!state.emittedReadable) {
  13138. debug('emitReadable', state.flowing);
  13139. state.emittedReadable = true;
  13140. if (state.sync) pna.nextTick(emitReadable_, stream); else emitReadable_(stream);
  13141. }
  13142. }
  13143. function emitReadable_(stream) {
  13144. debug('emit readable');
  13145. stream.emit('readable');
  13146. flow(stream);
  13147. }
  13148. // at this point, the user has presumably seen the 'readable' event,
  13149. // and called read() to consume some data. that may have triggered
  13150. // in turn another _read(n) call, in which case reading = true if
  13151. // it's in progress.
  13152. // However, if we're not ended, or reading, and the length < hwm,
  13153. // then go ahead and try to read some more preemptively.
  13154. function maybeReadMore(stream, state) {
  13155. if (!state.readingMore) {
  13156. state.readingMore = true;
  13157. pna.nextTick(maybeReadMore_, stream, state);
  13158. }
  13159. }
  13160. function maybeReadMore_(stream, state) {
  13161. var len = state.length;
  13162. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  13163. debug('maybeReadMore read 0');
  13164. stream.read(0);
  13165. if (len === state.length)
  13166. // didn't get any data, stop spinning.
  13167. break; else len = state.length;
  13168. }
  13169. state.readingMore = false;
  13170. }
  13171. // abstract method. to be overridden in specific implementation classes.
  13172. // call cb(er, data) where data is <= n in length.
  13173. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  13174. // arbitrary, and perhaps not very meaningful.
  13175. Readable.prototype._read = function (n) {
  13176. this.emit('error', new Error('_read() is not implemented'));
  13177. };
  13178. Readable.prototype.pipe = function (dest, pipeOpts) {
  13179. var src = this;
  13180. var state = this._readableState;
  13181. switch (state.pipesCount) {
  13182. case 0:
  13183. state.pipes = dest;
  13184. break;
  13185. case 1:
  13186. state.pipes = [state.pipes, dest];
  13187. break;
  13188. default:
  13189. state.pipes.push(dest);
  13190. break;
  13191. }
  13192. state.pipesCount += 1;
  13193. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  13194. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  13195. var endFn = doEnd ? onend : unpipe;
  13196. if (state.endEmitted) pna.nextTick(endFn); else src.once('end', endFn);
  13197. dest.on('unpipe', onunpipe);
  13198. function onunpipe(readable, unpipeInfo) {
  13199. debug('onunpipe');
  13200. if (readable === src) {
  13201. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  13202. unpipeInfo.hasUnpiped = true;
  13203. cleanup();
  13204. }
  13205. }
  13206. }
  13207. function onend() {
  13208. debug('onend');
  13209. dest.end();
  13210. }
  13211. // when the dest drains, it reduces the awaitDrain counter
  13212. // on the source. This would be more elegant with a .once()
  13213. // handler in flow(), but adding and removing repeatedly is
  13214. // too slow.
  13215. var ondrain = pipeOnDrain(src);
  13216. dest.on('drain', ondrain);
  13217. var cleanedUp = false;
  13218. function cleanup() {
  13219. debug('cleanup');
  13220. // cleanup event handlers once the pipe is broken
  13221. dest.removeListener('close', onclose);
  13222. dest.removeListener('finish', onfinish);
  13223. dest.removeListener('drain', ondrain);
  13224. dest.removeListener('error', onerror);
  13225. dest.removeListener('unpipe', onunpipe);
  13226. src.removeListener('end', onend);
  13227. src.removeListener('end', unpipe);
  13228. src.removeListener('data', ondata);
  13229. cleanedUp = true;
  13230. // if the reader is waiting for a drain event from this
  13231. // specific writer, then it would cause it to never start
  13232. // flowing again.
  13233. // So, if this is awaiting a drain, then we just call it now.
  13234. // If we don't know, then assume that we are waiting for one.
  13235. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  13236. }
  13237. // If the user pushes more data while we're writing to dest then we'll end up
  13238. // in ondata again. However, we only want to increase awaitDrain once because
  13239. // dest will only emit one 'drain' event for the multiple writes.
  13240. // => Introduce a guard on increasing awaitDrain.
  13241. var increasedAwaitDrain = false;
  13242. src.on('data', ondata);
  13243. function ondata(chunk) {
  13244. debug('ondata');
  13245. increasedAwaitDrain = false;
  13246. var ret = dest.write(chunk);
  13247. if (false === ret && !increasedAwaitDrain) {
  13248. // If the user unpiped during `dest.write()`, it is possible
  13249. // to get stuck in a permanently paused state if that write
  13250. // also returned false.
  13251. // => Check whether `dest` is still a piping destination.
  13252. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  13253. debug('false write response, pause', src._readableState.awaitDrain);
  13254. src._readableState.awaitDrain++;
  13255. increasedAwaitDrain = true;
  13256. }
  13257. src.pause();
  13258. }
  13259. }
  13260. // if the dest has an error, then stop piping into it.
  13261. // however, don't suppress the throwing behavior for this.
  13262. function onerror(er) {
  13263. debug('onerror', er);
  13264. unpipe();
  13265. dest.removeListener('error', onerror);
  13266. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  13267. }
  13268. // Make sure our error handler is attached before userland ones.
  13269. prependListener(dest, 'error', onerror);
  13270. // Both close and finish should trigger unpipe, but only once.
  13271. function onclose() {
  13272. dest.removeListener('finish', onfinish);
  13273. unpipe();
  13274. }
  13275. dest.once('close', onclose);
  13276. function onfinish() {
  13277. debug('onfinish');
  13278. dest.removeListener('close', onclose);
  13279. unpipe();
  13280. }
  13281. dest.once('finish', onfinish);
  13282. function unpipe() {
  13283. debug('unpipe');
  13284. src.unpipe(dest);
  13285. }
  13286. // tell the dest that it's being piped to
  13287. dest.emit('pipe', src);
  13288. // start the flow if it hasn't been started already.
  13289. if (!state.flowing) {
  13290. debug('pipe resume');
  13291. src.resume();
  13292. }
  13293. return dest;
  13294. };
  13295. function pipeOnDrain(src) {
  13296. return function () {
  13297. var state = src._readableState;
  13298. debug('pipeOnDrain', state.awaitDrain);
  13299. if (state.awaitDrain) state.awaitDrain--;
  13300. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  13301. state.flowing = true;
  13302. flow(src);
  13303. }
  13304. };
  13305. }
  13306. Readable.prototype.unpipe = function (dest) {
  13307. var state = this._readableState;
  13308. var unpipeInfo = { hasUnpiped: false };
  13309. // if we're not piping anywhere, then do nothing.
  13310. if (state.pipesCount === 0) return this;
  13311. // just one destination. most common case.
  13312. if (state.pipesCount === 1) {
  13313. // passed in one, but it's not the right one.
  13314. if (dest && dest !== state.pipes) return this;
  13315. if (!dest) dest = state.pipes;
  13316. // got a match.
  13317. state.pipes = null;
  13318. state.pipesCount = 0;
  13319. state.flowing = false;
  13320. if (dest) dest.emit('unpipe', this, unpipeInfo);
  13321. return this;
  13322. }
  13323. // slow case. multiple pipe destinations.
  13324. if (!dest) {
  13325. // remove all.
  13326. var dests = state.pipes;
  13327. var len = state.pipesCount;
  13328. state.pipes = null;
  13329. state.pipesCount = 0;
  13330. state.flowing = false;
  13331. for (var i = 0; i < len; i++) {
  13332. dests[i].emit('unpipe', this, unpipeInfo);
  13333. } return this;
  13334. }
  13335. // try to find the right one.
  13336. var index = indexOf(state.pipes, dest);
  13337. if (index === -1) return this;
  13338. state.pipes.splice(index, 1);
  13339. state.pipesCount -= 1;
  13340. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  13341. dest.emit('unpipe', this, unpipeInfo);
  13342. return this;
  13343. };
  13344. // set up data events if they are asked for
  13345. // Ensure readable listeners eventually get something
  13346. Readable.prototype.on = function (ev, fn) {
  13347. var res = Stream.prototype.on.call(this, ev, fn);
  13348. if (ev === 'data') {
  13349. // Start flowing on next tick if stream isn't explicitly paused
  13350. if (this._readableState.flowing !== false) this.resume();
  13351. } else if (ev === 'readable') {
  13352. var state = this._readableState;
  13353. if (!state.endEmitted && !state.readableListening) {
  13354. state.readableListening = state.needReadable = true;
  13355. state.emittedReadable = false;
  13356. if (!state.reading) {
  13357. pna.nextTick(nReadingNextTick, this);
  13358. } else if (state.length) {
  13359. emitReadable(this);
  13360. }
  13361. }
  13362. }
  13363. return res;
  13364. };
  13365. Readable.prototype.addListener = Readable.prototype.on;
  13366. function nReadingNextTick(self) {
  13367. debug('readable nexttick read 0');
  13368. self.read(0);
  13369. }
  13370. // pause() and resume() are remnants of the legacy readable stream API
  13371. // If the user uses them, then switch into old mode.
  13372. Readable.prototype.resume = function () {
  13373. var state = this._readableState;
  13374. if (!state.flowing) {
  13375. debug('resume');
  13376. state.flowing = true;
  13377. resume(this, state);
  13378. }
  13379. return this;
  13380. };
  13381. function resume(stream, state) {
  13382. if (!state.resumeScheduled) {
  13383. state.resumeScheduled = true;
  13384. pna.nextTick(resume_, stream, state);
  13385. }
  13386. }
  13387. function resume_(stream, state) {
  13388. if (!state.reading) {
  13389. debug('resume read 0');
  13390. stream.read(0);
  13391. }
  13392. state.resumeScheduled = false;
  13393. state.awaitDrain = 0;
  13394. stream.emit('resume');
  13395. flow(stream);
  13396. if (state.flowing && !state.reading) stream.read(0);
  13397. }
  13398. Readable.prototype.pause = function () {
  13399. debug('call pause flowing=%j', this._readableState.flowing);
  13400. if (false !== this._readableState.flowing) {
  13401. debug('pause');
  13402. this._readableState.flowing = false;
  13403. this.emit('pause');
  13404. }
  13405. return this;
  13406. };
  13407. function flow(stream) {
  13408. var state = stream._readableState;
  13409. debug('flow', state.flowing);
  13410. while (state.flowing && stream.read() !== null) { }
  13411. }
  13412. // wrap an old-style stream as the async data source.
  13413. // This is *not* part of the readable stream interface.
  13414. // It is an ugly unfortunate mess of history.
  13415. Readable.prototype.wrap = function (stream) {
  13416. var _this = this;
  13417. var state = this._readableState;
  13418. var paused = false;
  13419. stream.on('end', function () {
  13420. debug('wrapped end');
  13421. if (state.decoder && !state.ended) {
  13422. var chunk = state.decoder.end();
  13423. if (chunk && chunk.length) _this.push(chunk);
  13424. }
  13425. _this.push(null);
  13426. });
  13427. stream.on('data', function (chunk) {
  13428. debug('wrapped data');
  13429. if (state.decoder) chunk = state.decoder.write(chunk);
  13430. // don't skip over falsy values in objectMode
  13431. if (state.objectMode && (chunk === null || chunk === undefined)) return; else if (!state.objectMode && (!chunk || !chunk.length)) return;
  13432. var ret = _this.push(chunk);
  13433. if (!ret) {
  13434. paused = true;
  13435. stream.pause();
  13436. }
  13437. });
  13438. // proxy all the other methods.
  13439. // important when wrapping filters and duplexes.
  13440. for (var i in stream) {
  13441. if (this[i] === undefined && typeof stream[i] === 'function') {
  13442. this[i] = function (method) {
  13443. return function () {
  13444. return stream[method].apply(stream, arguments);
  13445. };
  13446. }(i);
  13447. }
  13448. }
  13449. // proxy certain important events.
  13450. for (var n = 0; n < kProxyEvents.length; n++) {
  13451. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  13452. }
  13453. // when we try to consume some more bytes, simply unpause the
  13454. // underlying stream.
  13455. this._read = function (n) {
  13456. debug('wrapped _read', n);
  13457. if (paused) {
  13458. paused = false;
  13459. stream.resume();
  13460. }
  13461. };
  13462. return this;
  13463. };
  13464. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  13465. // making it explicit this property is not enumerable
  13466. // because otherwise some prototype manipulation in
  13467. // userland will fail
  13468. enumerable: false,
  13469. get: function () {
  13470. return this._readableState.highWaterMark;
  13471. }
  13472. });
  13473. // exposed for testing purposes only.
  13474. Readable._fromList = fromList;
  13475. // Pluck off n bytes from an array of buffers.
  13476. // Length is the combined lengths of all the buffers in the list.
  13477. // This function is designed to be inlinable, so please take care when making
  13478. // changes to the function body.
  13479. function fromList(n, state) {
  13480. // nothing buffered
  13481. if (state.length === 0) return null;
  13482. var ret;
  13483. if (state.objectMode) ret = state.buffer.shift(); else if (!n || n >= state.length) {
  13484. // read it all, truncate the list
  13485. 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);
  13486. state.buffer.clear();
  13487. } else {
  13488. // read part of list
  13489. ret = fromListPartial(n, state.buffer, state.decoder);
  13490. }
  13491. return ret;
  13492. }
  13493. // Extracts only enough buffered data to satisfy the amount requested.
  13494. // This function is designed to be inlinable, so please take care when making
  13495. // changes to the function body.
  13496. function fromListPartial(n, list, hasStrings) {
  13497. var ret;
  13498. if (n < list.head.data.length) {
  13499. // slice is the same for buffers and strings
  13500. ret = list.head.data.slice(0, n);
  13501. list.head.data = list.head.data.slice(n);
  13502. } else if (n === list.head.data.length) {
  13503. // first chunk is a perfect match
  13504. ret = list.shift();
  13505. } else {
  13506. // result spans more than one buffer
  13507. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  13508. }
  13509. return ret;
  13510. }
  13511. // Copies a specified amount of characters from the list of buffered data
  13512. // chunks.
  13513. // This function is designed to be inlinable, so please take care when making
  13514. // changes to the function body.
  13515. function copyFromBufferString(n, list) {
  13516. var p = list.head;
  13517. var c = 1;
  13518. var ret = p.data;
  13519. n -= ret.length;
  13520. while (p = p.next) {
  13521. var str = p.data;
  13522. var nb = n > str.length ? str.length : n;
  13523. if (nb === str.length) ret += str; else ret += str.slice(0, n);
  13524. n -= nb;
  13525. if (n === 0) {
  13526. if (nb === str.length) {
  13527. ++c;
  13528. if (p.next) list.head = p.next; else list.head = list.tail = null;
  13529. } else {
  13530. list.head = p;
  13531. p.data = str.slice(nb);
  13532. }
  13533. break;
  13534. }
  13535. ++c;
  13536. }
  13537. list.length -= c;
  13538. return ret;
  13539. }
  13540. // Copies a specified amount of bytes from the list of buffered data chunks.
  13541. // This function is designed to be inlinable, so please take care when making
  13542. // changes to the function body.
  13543. function copyFromBuffer(n, list) {
  13544. var ret = Buffer.allocUnsafe(n);
  13545. var p = list.head;
  13546. var c = 1;
  13547. p.data.copy(ret);
  13548. n -= p.data.length;
  13549. while (p = p.next) {
  13550. var buf = p.data;
  13551. var nb = n > buf.length ? buf.length : n;
  13552. buf.copy(ret, ret.length - n, 0, nb);
  13553. n -= nb;
  13554. if (n === 0) {
  13555. if (nb === buf.length) {
  13556. ++c;
  13557. if (p.next) list.head = p.next; else list.head = list.tail = null;
  13558. } else {
  13559. list.head = p;
  13560. p.data = buf.slice(nb);
  13561. }
  13562. break;
  13563. }
  13564. ++c;
  13565. }
  13566. list.length -= c;
  13567. return ret;
  13568. }
  13569. function endReadable(stream) {
  13570. var state = stream._readableState;
  13571. // If we get here before consuming all the bytes, then that is a
  13572. // bug in node. Should never happen.
  13573. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  13574. if (!state.endEmitted) {
  13575. state.ended = true;
  13576. pna.nextTick(endReadableNT, state, stream);
  13577. }
  13578. }
  13579. function endReadableNT(state, stream) {
  13580. // Check that we didn't get one last unshift.
  13581. if (!state.endEmitted && state.length === 0) {
  13582. state.endEmitted = true;
  13583. stream.readable = false;
  13584. stream.emit('end');
  13585. }
  13586. }
  13587. function indexOf(xs, x) {
  13588. for (var i = 0, l = xs.length; i < l; i++) {
  13589. if (xs[i] === x) return i;
  13590. }
  13591. return -1;
  13592. }
  13593. }).call(this, require('_process'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13594. }, { "./_stream_duplex": 66, "./internal/streams/BufferList": 71, "./internal/streams/destroy": 72, "./internal/streams/stream": 73, "_process": 64, "core-util-is": 4, "events": 5, "inherits": 8, "isarray": 10, "process-nextick-args": 63, "safe-buffer": 78, "string_decoder/": 81, "util": 2 }], 69: [function (require, module, exports) {
  13595. // Copyright Joyent, Inc. and other Node contributors.
  13596. //
  13597. // Permission is hereby granted, free of charge, to any person obtaining a
  13598. // copy of this software and associated documentation files (the
  13599. // "Software"), to deal in the Software without restriction, including
  13600. // without limitation the rights to use, copy, modify, merge, publish,
  13601. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13602. // persons to whom the Software is furnished to do so, subject to the
  13603. // following conditions:
  13604. //
  13605. // The above copyright notice and this permission notice shall be included
  13606. // in all copies or substantial portions of the Software.
  13607. //
  13608. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13609. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13610. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13611. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13612. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13613. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13614. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13615. // a transform stream is a readable/writable stream where you do
  13616. // something with the data. Sometimes it's called a "filter",
  13617. // but that's not a great name for it, since that implies a thing where
  13618. // some bits pass through, and others are simply ignored. (That would
  13619. // be a valid example of a transform, of course.)
  13620. //
  13621. // While the output is causally related to the input, it's not a
  13622. // necessarily symmetric or synchronous transformation. For example,
  13623. // a zlib stream might take multiple plain-text writes(), and then
  13624. // emit a single compressed chunk some time in the future.
  13625. //
  13626. // Here's how this works:
  13627. //
  13628. // The Transform stream has all the aspects of the readable and writable
  13629. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  13630. // internally, and returns false if there's a lot of pending writes
  13631. // buffered up. When you call read(), that calls _read(n) until
  13632. // there's enough pending readable data buffered up.
  13633. //
  13634. // In a transform stream, the written data is placed in a buffer. When
  13635. // _read(n) is called, it transforms the queued up data, calling the
  13636. // buffered _write cb's as it consumes chunks. If consuming a single
  13637. // written chunk would result in multiple output chunks, then the first
  13638. // outputted bit calls the readcb, and subsequent chunks just go into
  13639. // the read buffer, and will cause it to emit 'readable' if necessary.
  13640. //
  13641. // This way, back-pressure is actually determined by the reading side,
  13642. // since _read has to be called to start processing a new chunk. However,
  13643. // a pathological inflate type of transform can cause excessive buffering
  13644. // here. For example, imagine a stream where every byte of input is
  13645. // interpreted as an integer from 0-255, and then results in that many
  13646. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  13647. // 1kb of data being output. In this case, you could write a very small
  13648. // amount of input, and end up with a very large amount of output. In
  13649. // such a pathological inflating mechanism, there'd be no way to tell
  13650. // the system to stop doing the transform. A single 4MB write could
  13651. // cause the system to run out of memory.
  13652. //
  13653. // However, even in such a pathological case, only a single written chunk
  13654. // would be consumed, and then the rest would wait (un-transformed) until
  13655. // the results of the previous transformed chunk were consumed.
  13656. 'use strict';
  13657. module.exports = Transform;
  13658. var Duplex = require('./_stream_duplex');
  13659. /*<replacement>*/
  13660. var util = Object.create(require('core-util-is'));
  13661. util.inherits = require('inherits');
  13662. /*</replacement>*/
  13663. util.inherits(Transform, Duplex);
  13664. function afterTransform(er, data) {
  13665. var ts = this._transformState;
  13666. ts.transforming = false;
  13667. var cb = ts.writecb;
  13668. if (!cb) {
  13669. return this.emit('error', new Error('write callback called multiple times'));
  13670. }
  13671. ts.writechunk = null;
  13672. ts.writecb = null;
  13673. if (data != null) // single equals check for both `null` and `undefined`
  13674. this.push(data);
  13675. cb(er);
  13676. var rs = this._readableState;
  13677. rs.reading = false;
  13678. if (rs.needReadable || rs.length < rs.highWaterMark) {
  13679. this._read(rs.highWaterMark);
  13680. }
  13681. }
  13682. function Transform(options) {
  13683. if (!(this instanceof Transform)) return new Transform(options);
  13684. Duplex.call(this, options);
  13685. this._transformState = {
  13686. afterTransform: afterTransform.bind(this),
  13687. needTransform: false,
  13688. transforming: false,
  13689. writecb: null,
  13690. writechunk: null,
  13691. writeencoding: null
  13692. };
  13693. // start out asking for a readable event once data is transformed.
  13694. this._readableState.needReadable = true;
  13695. // we have implemented the _read method, and done the other things
  13696. // that Readable wants before the first _read call, so unset the
  13697. // sync guard flag.
  13698. this._readableState.sync = false;
  13699. if (options) {
  13700. if (typeof options.transform === 'function') this._transform = options.transform;
  13701. if (typeof options.flush === 'function') this._flush = options.flush;
  13702. }
  13703. // When the writable side finishes, then flush out anything remaining.
  13704. this.on('prefinish', prefinish);
  13705. }
  13706. function prefinish() {
  13707. var _this = this;
  13708. if (typeof this._flush === 'function') {
  13709. this._flush(function (er, data) {
  13710. done(_this, er, data);
  13711. });
  13712. } else {
  13713. done(this, null, null);
  13714. }
  13715. }
  13716. Transform.prototype.push = function (chunk, encoding) {
  13717. this._transformState.needTransform = false;
  13718. return Duplex.prototype.push.call(this, chunk, encoding);
  13719. };
  13720. // This is the part where you do stuff!
  13721. // override this function in implementation classes.
  13722. // 'chunk' is an input chunk.
  13723. //
  13724. // Call `push(newChunk)` to pass along transformed output
  13725. // to the readable side. You may call 'push' zero or more times.
  13726. //
  13727. // Call `cb(err)` when you are done with this chunk. If you pass
  13728. // an error, then that'll put the hurt on the whole operation. If you
  13729. // never call cb(), then you'll never get another chunk.
  13730. Transform.prototype._transform = function (chunk, encoding, cb) {
  13731. throw new Error('_transform() is not implemented');
  13732. };
  13733. Transform.prototype._write = function (chunk, encoding, cb) {
  13734. var ts = this._transformState;
  13735. ts.writecb = cb;
  13736. ts.writechunk = chunk;
  13737. ts.writeencoding = encoding;
  13738. if (!ts.transforming) {
  13739. var rs = this._readableState;
  13740. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  13741. }
  13742. };
  13743. // Doesn't matter what the args are here.
  13744. // _transform does all the work.
  13745. // That we got here means that the readable side wants more data.
  13746. Transform.prototype._read = function (n) {
  13747. var ts = this._transformState;
  13748. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  13749. ts.transforming = true;
  13750. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  13751. } else {
  13752. // mark that we need a transform, so that any data that comes in
  13753. // will get processed, now that we've asked for it.
  13754. ts.needTransform = true;
  13755. }
  13756. };
  13757. Transform.prototype._destroy = function (err, cb) {
  13758. var _this2 = this;
  13759. Duplex.prototype._destroy.call(this, err, function (err2) {
  13760. cb(err2);
  13761. _this2.emit('close');
  13762. });
  13763. };
  13764. function done(stream, er, data) {
  13765. if (er) return stream.emit('error', er);
  13766. if (data != null) // single equals check for both `null` and `undefined`
  13767. stream.push(data);
  13768. // if there's nothing in the write buffer, then that means
  13769. // that nothing more will ever be provided
  13770. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  13771. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  13772. return stream.push(null);
  13773. }
  13774. }, { "./_stream_duplex": 66, "core-util-is": 4, "inherits": 8 }], 70: [function (require, module, exports) {
  13775. (function (process, global, setImmediate) {
  13776. // Copyright Joyent, Inc. and other Node contributors.
  13777. //
  13778. // Permission is hereby granted, free of charge, to any person obtaining a
  13779. // copy of this software and associated documentation files (the
  13780. // "Software"), to deal in the Software without restriction, including
  13781. // without limitation the rights to use, copy, modify, merge, publish,
  13782. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13783. // persons to whom the Software is furnished to do so, subject to the
  13784. // following conditions:
  13785. //
  13786. // The above copyright notice and this permission notice shall be included
  13787. // in all copies or substantial portions of the Software.
  13788. //
  13789. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13790. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13791. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13792. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13793. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13794. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13795. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13796. // A bit simpler than readable streams.
  13797. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  13798. // the drain event emission and buffering.
  13799. 'use strict';
  13800. /*<replacement>*/
  13801. var pna = require('process-nextick-args');
  13802. /*</replacement>*/
  13803. module.exports = Writable;
  13804. /* <replacement> */
  13805. function WriteReq(chunk, encoding, cb) {
  13806. this.chunk = chunk;
  13807. this.encoding = encoding;
  13808. this.callback = cb;
  13809. this.next = null;
  13810. }
  13811. // It seems a linked list but it is not
  13812. // there will be only 2 of these for each stream
  13813. function CorkedRequest(state) {
  13814. var _this = this;
  13815. this.next = null;
  13816. this.entry = null;
  13817. this.finish = function () {
  13818. onCorkedFinish(_this, state);
  13819. };
  13820. }
  13821. /* </replacement> */
  13822. /*<replacement>*/
  13823. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  13824. /*</replacement>*/
  13825. /*<replacement>*/
  13826. var Duplex;
  13827. /*</replacement>*/
  13828. Writable.WritableState = WritableState;
  13829. /*<replacement>*/
  13830. var util = Object.create(require('core-util-is'));
  13831. util.inherits = require('inherits');
  13832. /*</replacement>*/
  13833. /*<replacement>*/
  13834. var internalUtil = {
  13835. deprecate: require('util-deprecate')
  13836. };
  13837. /*</replacement>*/
  13838. /*<replacement>*/
  13839. var Stream = require('./internal/streams/stream');
  13840. /*</replacement>*/
  13841. /*<replacement>*/
  13842. var Buffer = require('safe-buffer').Buffer;
  13843. var OurUint8Array = global.Uint8Array || function () { };
  13844. function _uint8ArrayToBuffer(chunk) {
  13845. return Buffer.from(chunk);
  13846. }
  13847. function _isUint8Array(obj) {
  13848. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  13849. }
  13850. /*</replacement>*/
  13851. var destroyImpl = require('./internal/streams/destroy');
  13852. util.inherits(Writable, Stream);
  13853. function nop() { }
  13854. function WritableState(options, stream) {
  13855. Duplex = Duplex || require('./_stream_duplex');
  13856. options = options || {};
  13857. // Duplex streams are both readable and writable, but share
  13858. // the same options object.
  13859. // However, some cases require setting options to different
  13860. // values for the readable and the writable sides of the duplex stream.
  13861. // These options can be provided separately as readableXXX and writableXXX.
  13862. var isDuplex = stream instanceof Duplex;
  13863. // object stream flag to indicate whether or not this stream
  13864. // contains buffers or objects.
  13865. this.objectMode = !!options.objectMode;
  13866. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  13867. // the point at which write() starts returning false
  13868. // Note: 0 is a valid value, means that we always return false if
  13869. // the entire buffer is not flushed immediately on write()
  13870. var hwm = options.highWaterMark;
  13871. var writableHwm = options.writableHighWaterMark;
  13872. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  13873. if (hwm || hwm === 0) this.highWaterMark = hwm; else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm; else this.highWaterMark = defaultHwm;
  13874. // cast to ints.
  13875. this.highWaterMark = Math.floor(this.highWaterMark);
  13876. // if _final has been called
  13877. this.finalCalled = false;
  13878. // drain event flag.
  13879. this.needDrain = false;
  13880. // at the start of calling end()
  13881. this.ending = false;
  13882. // when end() has been called, and returned
  13883. this.ended = false;
  13884. // when 'finish' is emitted
  13885. this.finished = false;
  13886. // has it been destroyed
  13887. this.destroyed = false;
  13888. // should we decode strings into buffers before passing to _write?
  13889. // this is here so that some node-core streams can optimize string
  13890. // handling at a lower level.
  13891. var noDecode = options.decodeStrings === false;
  13892. this.decodeStrings = !noDecode;
  13893. // Crypto is kind of old and crusty. Historically, its default string
  13894. // encoding is 'binary' so we have to make this configurable.
  13895. // Everything else in the universe uses 'utf8', though.
  13896. this.defaultEncoding = options.defaultEncoding || 'utf8';
  13897. // not an actual buffer we keep track of, but a measurement
  13898. // of how much we're waiting to get pushed to some underlying
  13899. // socket or file.
  13900. this.length = 0;
  13901. // a flag to see when we're in the middle of a write.
  13902. this.writing = false;
  13903. // when true all writes will be buffered until .uncork() call
  13904. this.corked = 0;
  13905. // a flag to be able to tell if the onwrite cb is called immediately,
  13906. // or on a later tick. We set this to true at first, because any
  13907. // actions that shouldn't happen until "later" should generally also
  13908. // not happen before the first write call.
  13909. this.sync = true;
  13910. // a flag to know if we're processing previously buffered items, which
  13911. // may call the _write() callback in the same tick, so that we don't
  13912. // end up in an overlapped onwrite situation.
  13913. this.bufferProcessing = false;
  13914. // the callback that's passed to _write(chunk,cb)
  13915. this.onwrite = function (er) {
  13916. onwrite(stream, er);
  13917. };
  13918. // the callback that the user supplies to write(chunk,encoding,cb)
  13919. this.writecb = null;
  13920. // the amount that is being written when _write is called.
  13921. this.writelen = 0;
  13922. this.bufferedRequest = null;
  13923. this.lastBufferedRequest = null;
  13924. // number of pending user-supplied write callbacks
  13925. // this must be 0 before 'finish' can be emitted
  13926. this.pendingcb = 0;
  13927. // emit prefinish if the only thing we're waiting for is _write cbs
  13928. // This is relevant for synchronous Transform streams
  13929. this.prefinished = false;
  13930. // True if the error was already emitted and should not be thrown again
  13931. this.errorEmitted = false;
  13932. // count buffered requests
  13933. this.bufferedRequestCount = 0;
  13934. // allocate the first CorkedRequest, there is always
  13935. // one allocated and free to use, and we maintain at most two
  13936. this.corkedRequestsFree = new CorkedRequest(this);
  13937. }
  13938. WritableState.prototype.getBuffer = function getBuffer() {
  13939. var current = this.bufferedRequest;
  13940. var out = [];
  13941. while (current) {
  13942. out.push(current);
  13943. current = current.next;
  13944. }
  13945. return out;
  13946. };
  13947. (function () {
  13948. try {
  13949. Object.defineProperty(WritableState.prototype, 'buffer', {
  13950. get: internalUtil.deprecate(function () {
  13951. return this.getBuffer();
  13952. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  13953. });
  13954. } catch (_) { }
  13955. })();
  13956. // Test _writableState for inheritance to account for Duplex streams,
  13957. // whose prototype chain only points to Readable.
  13958. var realHasInstance;
  13959. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  13960. realHasInstance = Function.prototype[Symbol.hasInstance];
  13961. Object.defineProperty(Writable, Symbol.hasInstance, {
  13962. value: function (object) {
  13963. if (realHasInstance.call(this, object)) return true;
  13964. if (this !== Writable) return false;
  13965. return object && object._writableState instanceof WritableState;
  13966. }
  13967. });
  13968. } else {
  13969. realHasInstance = function (object) {
  13970. return object instanceof this;
  13971. };
  13972. }
  13973. function Writable(options) {
  13974. Duplex = Duplex || require('./_stream_duplex');
  13975. // Writable ctor is applied to Duplexes, too.
  13976. // `realHasInstance` is necessary because using plain `instanceof`
  13977. // would return false, as no `_writableState` property is attached.
  13978. // Trying to use the custom `instanceof` for Writable here will also break the
  13979. // Node.js LazyTransform implementation, which has a non-trivial getter for
  13980. // `_writableState` that would lead to infinite recursion.
  13981. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  13982. return new Writable(options);
  13983. }
  13984. this._writableState = new WritableState(options, this);
  13985. // legacy.
  13986. this.writable = true;
  13987. if (options) {
  13988. if (typeof options.write === 'function') this._write = options.write;
  13989. if (typeof options.writev === 'function') this._writev = options.writev;
  13990. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  13991. if (typeof options.final === 'function') this._final = options.final;
  13992. }
  13993. Stream.call(this);
  13994. }
  13995. // Otherwise people can pipe Writable streams, which is just wrong.
  13996. Writable.prototype.pipe = function () {
  13997. this.emit('error', new Error('Cannot pipe, not readable'));
  13998. };
  13999. function writeAfterEnd(stream, cb) {
  14000. var er = new Error('write after end');
  14001. // TODO: defer error events consistently everywhere, not just the cb
  14002. stream.emit('error', er);
  14003. pna.nextTick(cb, er);
  14004. }
  14005. // Checks that a user-supplied chunk is valid, especially for the particular
  14006. // mode the stream is in. Currently this means that `null` is never accepted
  14007. // and undefined/non-string values are only allowed in object mode.
  14008. function validChunk(stream, state, chunk, cb) {
  14009. var valid = true;
  14010. var er = false;
  14011. if (chunk === null) {
  14012. er = new TypeError('May not write null values to stream');
  14013. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  14014. er = new TypeError('Invalid non-string/buffer chunk');
  14015. }
  14016. if (er) {
  14017. stream.emit('error', er);
  14018. pna.nextTick(cb, er);
  14019. valid = false;
  14020. }
  14021. return valid;
  14022. }
  14023. Writable.prototype.write = function (chunk, encoding, cb) {
  14024. var state = this._writableState;
  14025. var ret = false;
  14026. var isBuf = !state.objectMode && _isUint8Array(chunk);
  14027. if (isBuf && !Buffer.isBuffer(chunk)) {
  14028. chunk = _uint8ArrayToBuffer(chunk);
  14029. }
  14030. if (typeof encoding === 'function') {
  14031. cb = encoding;
  14032. encoding = null;
  14033. }
  14034. if (isBuf) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding;
  14035. if (typeof cb !== 'function') cb = nop;
  14036. if (state.ended) writeAfterEnd(this, cb); else if (isBuf || validChunk(this, state, chunk, cb)) {
  14037. state.pendingcb++;
  14038. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  14039. }
  14040. return ret;
  14041. };
  14042. Writable.prototype.cork = function () {
  14043. var state = this._writableState;
  14044. state.corked++;
  14045. };
  14046. Writable.prototype.uncork = function () {
  14047. var state = this._writableState;
  14048. if (state.corked) {
  14049. state.corked--;
  14050. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  14051. }
  14052. };
  14053. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  14054. // node::ParseEncoding() requires lower case.
  14055. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  14056. 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);
  14057. this._writableState.defaultEncoding = encoding;
  14058. return this;
  14059. };
  14060. function decodeChunk(state, chunk, encoding) {
  14061. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  14062. chunk = Buffer.from(chunk, encoding);
  14063. }
  14064. return chunk;
  14065. }
  14066. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  14067. // making it explicit this property is not enumerable
  14068. // because otherwise some prototype manipulation in
  14069. // userland will fail
  14070. enumerable: false,
  14071. get: function () {
  14072. return this._writableState.highWaterMark;
  14073. }
  14074. });
  14075. // if we're already writing something, then just put this
  14076. // in the queue, and wait our turn. Otherwise, call _write
  14077. // If we return false, then we need a drain event, so set that flag.
  14078. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  14079. if (!isBuf) {
  14080. var newChunk = decodeChunk(state, chunk, encoding);
  14081. if (chunk !== newChunk) {
  14082. isBuf = true;
  14083. encoding = 'buffer';
  14084. chunk = newChunk;
  14085. }
  14086. }
  14087. var len = state.objectMode ? 1 : chunk.length;
  14088. state.length += len;
  14089. var ret = state.length < state.highWaterMark;
  14090. // we must ensure that previous needDrain will not be reset to false.
  14091. if (!ret) state.needDrain = true;
  14092. if (state.writing || state.corked) {
  14093. var last = state.lastBufferedRequest;
  14094. state.lastBufferedRequest = {
  14095. chunk: chunk,
  14096. encoding: encoding,
  14097. isBuf: isBuf,
  14098. callback: cb,
  14099. next: null
  14100. };
  14101. if (last) {
  14102. last.next = state.lastBufferedRequest;
  14103. } else {
  14104. state.bufferedRequest = state.lastBufferedRequest;
  14105. }
  14106. state.bufferedRequestCount += 1;
  14107. } else {
  14108. doWrite(stream, state, false, len, chunk, encoding, cb);
  14109. }
  14110. return ret;
  14111. }
  14112. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  14113. state.writelen = len;
  14114. state.writecb = cb;
  14115. state.writing = true;
  14116. state.sync = true;
  14117. if (writev) stream._writev(chunk, state.onwrite); else stream._write(chunk, encoding, state.onwrite);
  14118. state.sync = false;
  14119. }
  14120. function onwriteError(stream, state, sync, er, cb) {
  14121. --state.pendingcb;
  14122. if (sync) {
  14123. // defer the callback if we are being called synchronously
  14124. // to avoid piling up things on the stack
  14125. pna.nextTick(cb, er);
  14126. // this can emit finish, and it will always happen
  14127. // after error
  14128. pna.nextTick(finishMaybe, stream, state);
  14129. stream._writableState.errorEmitted = true;
  14130. stream.emit('error', er);
  14131. } else {
  14132. // the caller expect this to happen before if
  14133. // it is async
  14134. cb(er);
  14135. stream._writableState.errorEmitted = true;
  14136. stream.emit('error', er);
  14137. // this can emit finish, but finish must
  14138. // always follow error
  14139. finishMaybe(stream, state);
  14140. }
  14141. }
  14142. function onwriteStateUpdate(state) {
  14143. state.writing = false;
  14144. state.writecb = null;
  14145. state.length -= state.writelen;
  14146. state.writelen = 0;
  14147. }
  14148. function onwrite(stream, er) {
  14149. var state = stream._writableState;
  14150. var sync = state.sync;
  14151. var cb = state.writecb;
  14152. onwriteStateUpdate(state);
  14153. if (er) onwriteError(stream, state, sync, er, cb); else {
  14154. // Check if we're actually ready to finish, but don't emit yet
  14155. var finished = needFinish(state);
  14156. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  14157. clearBuffer(stream, state);
  14158. }
  14159. if (sync) {
  14160. /*<replacement>*/
  14161. asyncWrite(afterWrite, stream, state, finished, cb);
  14162. /*</replacement>*/
  14163. } else {
  14164. afterWrite(stream, state, finished, cb);
  14165. }
  14166. }
  14167. }
  14168. function afterWrite(stream, state, finished, cb) {
  14169. if (!finished) onwriteDrain(stream, state);
  14170. state.pendingcb--;
  14171. cb();
  14172. finishMaybe(stream, state);
  14173. }
  14174. // Must force callback to be called on nextTick, so that we don't
  14175. // emit 'drain' before the write() consumer gets the 'false' return
  14176. // value, and has a chance to attach a 'drain' listener.
  14177. function onwriteDrain(stream, state) {
  14178. if (state.length === 0 && state.needDrain) {
  14179. state.needDrain = false;
  14180. stream.emit('drain');
  14181. }
  14182. }
  14183. // if there's something in the buffer waiting, then process it
  14184. function clearBuffer(stream, state) {
  14185. state.bufferProcessing = true;
  14186. var entry = state.bufferedRequest;
  14187. if (stream._writev && entry && entry.next) {
  14188. // Fast case, write everything using _writev()
  14189. var l = state.bufferedRequestCount;
  14190. var buffer = new Array(l);
  14191. var holder = state.corkedRequestsFree;
  14192. holder.entry = entry;
  14193. var count = 0;
  14194. var allBuffers = true;
  14195. while (entry) {
  14196. buffer[count] = entry;
  14197. if (!entry.isBuf) allBuffers = false;
  14198. entry = entry.next;
  14199. count += 1;
  14200. }
  14201. buffer.allBuffers = allBuffers;
  14202. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  14203. // doWrite is almost always async, defer these to save a bit of time
  14204. // as the hot path ends with doWrite
  14205. state.pendingcb++;
  14206. state.lastBufferedRequest = null;
  14207. if (holder.next) {
  14208. state.corkedRequestsFree = holder.next;
  14209. holder.next = null;
  14210. } else {
  14211. state.corkedRequestsFree = new CorkedRequest(state);
  14212. }
  14213. state.bufferedRequestCount = 0;
  14214. } else {
  14215. // Slow case, write chunks one-by-one
  14216. while (entry) {
  14217. var chunk = entry.chunk;
  14218. var encoding = entry.encoding;
  14219. var cb = entry.callback;
  14220. var len = state.objectMode ? 1 : chunk.length;
  14221. doWrite(stream, state, false, len, chunk, encoding, cb);
  14222. entry = entry.next;
  14223. state.bufferedRequestCount--;
  14224. // if we didn't call the onwrite immediately, then
  14225. // it means that we need to wait until it does.
  14226. // also, that means that the chunk and cb are currently
  14227. // being processed, so move the buffer counter past them.
  14228. if (state.writing) {
  14229. break;
  14230. }
  14231. }
  14232. if (entry === null) state.lastBufferedRequest = null;
  14233. }
  14234. state.bufferedRequest = entry;
  14235. state.bufferProcessing = false;
  14236. }
  14237. Writable.prototype._write = function (chunk, encoding, cb) {
  14238. cb(new Error('_write() is not implemented'));
  14239. };
  14240. Writable.prototype._writev = null;
  14241. Writable.prototype.end = function (chunk, encoding, cb) {
  14242. var state = this._writableState;
  14243. if (typeof chunk === 'function') {
  14244. cb = chunk;
  14245. chunk = null;
  14246. encoding = null;
  14247. } else if (typeof encoding === 'function') {
  14248. cb = encoding;
  14249. encoding = null;
  14250. }
  14251. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  14252. // .end() fully uncorks
  14253. if (state.corked) {
  14254. state.corked = 1;
  14255. this.uncork();
  14256. }
  14257. // ignore unnecessary end() calls.
  14258. if (!state.ending && !state.finished) endWritable(this, state, cb);
  14259. };
  14260. function needFinish(state) {
  14261. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  14262. }
  14263. function callFinal(stream, state) {
  14264. stream._final(function (err) {
  14265. state.pendingcb--;
  14266. if (err) {
  14267. stream.emit('error', err);
  14268. }
  14269. state.prefinished = true;
  14270. stream.emit('prefinish');
  14271. finishMaybe(stream, state);
  14272. });
  14273. }
  14274. function prefinish(stream, state) {
  14275. if (!state.prefinished && !state.finalCalled) {
  14276. if (typeof stream._final === 'function') {
  14277. state.pendingcb++;
  14278. state.finalCalled = true;
  14279. pna.nextTick(callFinal, stream, state);
  14280. } else {
  14281. state.prefinished = true;
  14282. stream.emit('prefinish');
  14283. }
  14284. }
  14285. }
  14286. function finishMaybe(stream, state) {
  14287. var need = needFinish(state);
  14288. if (need) {
  14289. prefinish(stream, state);
  14290. if (state.pendingcb === 0) {
  14291. state.finished = true;
  14292. stream.emit('finish');
  14293. }
  14294. }
  14295. return need;
  14296. }
  14297. function endWritable(stream, state, cb) {
  14298. state.ending = true;
  14299. finishMaybe(stream, state);
  14300. if (cb) {
  14301. if (state.finished) pna.nextTick(cb); else stream.once('finish', cb);
  14302. }
  14303. state.ended = true;
  14304. stream.writable = false;
  14305. }
  14306. function onCorkedFinish(corkReq, state, err) {
  14307. var entry = corkReq.entry;
  14308. corkReq.entry = null;
  14309. while (entry) {
  14310. var cb = entry.callback;
  14311. state.pendingcb--;
  14312. cb(err);
  14313. entry = entry.next;
  14314. }
  14315. if (state.corkedRequestsFree) {
  14316. state.corkedRequestsFree.next = corkReq;
  14317. } else {
  14318. state.corkedRequestsFree = corkReq;
  14319. }
  14320. }
  14321. Object.defineProperty(Writable.prototype, 'destroyed', {
  14322. get: function () {
  14323. if (this._writableState === undefined) {
  14324. return false;
  14325. }
  14326. return this._writableState.destroyed;
  14327. },
  14328. set: function (value) {
  14329. // we ignore the value if the stream
  14330. // has not been initialized yet
  14331. if (!this._writableState) {
  14332. return;
  14333. }
  14334. // backward compatibility, the user is explicitly
  14335. // managing destroyed
  14336. this._writableState.destroyed = value;
  14337. }
  14338. });
  14339. Writable.prototype.destroy = destroyImpl.destroy;
  14340. Writable.prototype._undestroy = destroyImpl.undestroy;
  14341. Writable.prototype._destroy = function (err, cb) {
  14342. this.end();
  14343. cb(err);
  14344. };
  14345. }).call(this, require('_process'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}, require("timers").setImmediate)
  14346. }, { "./_stream_duplex": 66, "./internal/streams/destroy": 72, "./internal/streams/stream": 73, "_process": 64, "core-util-is": 4, "inherits": 8, "process-nextick-args": 63, "safe-buffer": 78, "timers": 82, "util-deprecate": 83 }], 71: [function (require, module, exports) {
  14347. 'use strict';
  14348. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14349. var Buffer = require('safe-buffer').Buffer;
  14350. var util = require('util');
  14351. function copyBuffer(src, target, offset) {
  14352. src.copy(target, offset);
  14353. }
  14354. module.exports = function () {
  14355. function BufferList() {
  14356. _classCallCheck(this, BufferList);
  14357. this.head = null;
  14358. this.tail = null;
  14359. this.length = 0;
  14360. }
  14361. BufferList.prototype.push = function push(v) {
  14362. var entry = { data: v, next: null };
  14363. if (this.length > 0) this.tail.next = entry; else this.head = entry;
  14364. this.tail = entry;
  14365. ++this.length;
  14366. };
  14367. BufferList.prototype.unshift = function unshift(v) {
  14368. var entry = { data: v, next: this.head };
  14369. if (this.length === 0) this.tail = entry;
  14370. this.head = entry;
  14371. ++this.length;
  14372. };
  14373. BufferList.prototype.shift = function shift() {
  14374. if (this.length === 0) return;
  14375. var ret = this.head.data;
  14376. if (this.length === 1) this.head = this.tail = null; else this.head = this.head.next;
  14377. --this.length;
  14378. return ret;
  14379. };
  14380. BufferList.prototype.clear = function clear() {
  14381. this.head = this.tail = null;
  14382. this.length = 0;
  14383. };
  14384. BufferList.prototype.join = function join(s) {
  14385. if (this.length === 0) return '';
  14386. var p = this.head;
  14387. var ret = '' + p.data;
  14388. while (p = p.next) {
  14389. ret += s + p.data;
  14390. } return ret;
  14391. };
  14392. BufferList.prototype.concat = function concat(n) {
  14393. if (this.length === 0) return Buffer.alloc(0);
  14394. if (this.length === 1) return this.head.data;
  14395. var ret = Buffer.allocUnsafe(n >>> 0);
  14396. var p = this.head;
  14397. var i = 0;
  14398. while (p) {
  14399. copyBuffer(p.data, ret, i);
  14400. i += p.data.length;
  14401. p = p.next;
  14402. }
  14403. return ret;
  14404. };
  14405. return BufferList;
  14406. }();
  14407. if (util && util.inspect && util.inspect.custom) {
  14408. module.exports.prototype[util.inspect.custom] = function () {
  14409. var obj = util.inspect({ length: this.length });
  14410. return this.constructor.name + ' ' + obj;
  14411. };
  14412. }
  14413. }, { "safe-buffer": 78, "util": 2 }], 72: [function (require, module, exports) {
  14414. 'use strict';
  14415. /*<replacement>*/
  14416. var pna = require('process-nextick-args');
  14417. /*</replacement>*/
  14418. // undocumented cb() API, needed for core, not for public API
  14419. function destroy(err, cb) {
  14420. var _this = this;
  14421. var readableDestroyed = this._readableState && this._readableState.destroyed;
  14422. var writableDestroyed = this._writableState && this._writableState.destroyed;
  14423. if (readableDestroyed || writableDestroyed) {
  14424. if (cb) {
  14425. cb(err);
  14426. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  14427. pna.nextTick(emitErrorNT, this, err);
  14428. }
  14429. return this;
  14430. }
  14431. // we set destroyed to true before firing error callbacks in order
  14432. // to make it re-entrance safe in case destroy() is called within callbacks
  14433. if (this._readableState) {
  14434. this._readableState.destroyed = true;
  14435. }
  14436. // if this is a duplex stream mark the writable part as destroyed as well
  14437. if (this._writableState) {
  14438. this._writableState.destroyed = true;
  14439. }
  14440. this._destroy(err || null, function (err) {
  14441. if (!cb && err) {
  14442. pna.nextTick(emitErrorNT, _this, err);
  14443. if (_this._writableState) {
  14444. _this._writableState.errorEmitted = true;
  14445. }
  14446. } else if (cb) {
  14447. cb(err);
  14448. }
  14449. });
  14450. return this;
  14451. }
  14452. function undestroy() {
  14453. if (this._readableState) {
  14454. this._readableState.destroyed = false;
  14455. this._readableState.reading = false;
  14456. this._readableState.ended = false;
  14457. this._readableState.endEmitted = false;
  14458. }
  14459. if (this._writableState) {
  14460. this._writableState.destroyed = false;
  14461. this._writableState.ended = false;
  14462. this._writableState.ending = false;
  14463. this._writableState.finished = false;
  14464. this._writableState.errorEmitted = false;
  14465. }
  14466. }
  14467. function emitErrorNT(self, err) {
  14468. self.emit('error', err);
  14469. }
  14470. module.exports = {
  14471. destroy: destroy,
  14472. undestroy: undestroy
  14473. };
  14474. }, { "process-nextick-args": 63 }], 73: [function (require, module, exports) {
  14475. module.exports = require('events').EventEmitter;
  14476. }, { "events": 5 }], 74: [function (require, module, exports) {
  14477. module.exports = require('./readable').PassThrough
  14478. }, { "./readable": 75 }], 75: [function (require, module, exports) {
  14479. exports = module.exports = require('./lib/_stream_readable.js');
  14480. exports.Stream = exports;
  14481. exports.Readable = exports;
  14482. exports.Writable = require('./lib/_stream_writable.js');
  14483. exports.Duplex = require('./lib/_stream_duplex.js');
  14484. exports.Transform = require('./lib/_stream_transform.js');
  14485. exports.PassThrough = require('./lib/_stream_passthrough.js');
  14486. }, { "./lib/_stream_duplex.js": 66, "./lib/_stream_passthrough.js": 67, "./lib/_stream_readable.js": 68, "./lib/_stream_transform.js": 69, "./lib/_stream_writable.js": 70 }], 76: [function (require, module, exports) {
  14487. module.exports = require('./readable').Transform
  14488. }, { "./readable": 75 }], 77: [function (require, module, exports) {
  14489. module.exports = require('./lib/_stream_writable.js');
  14490. }, { "./lib/_stream_writable.js": 70 }], 78: [function (require, module, exports) {
  14491. /* eslint-disable node/no-deprecated-api */
  14492. var buffer = require('buffer')
  14493. var Buffer = buffer.Buffer
  14494. // alternative to using Object.keys for old browsers
  14495. function copyProps(src, dst) {
  14496. for (var key in src) {
  14497. dst[key] = src[key]
  14498. }
  14499. }
  14500. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  14501. module.exports = buffer
  14502. } else {
  14503. // Copy properties from require('buffer')
  14504. copyProps(buffer, exports)
  14505. exports.Buffer = SafeBuffer
  14506. }
  14507. function SafeBuffer(arg, encodingOrOffset, length) {
  14508. return Buffer(arg, encodingOrOffset, length)
  14509. }
  14510. // Copy static methods from Buffer
  14511. copyProps(Buffer, SafeBuffer)
  14512. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  14513. if (typeof arg === 'number') {
  14514. throw new TypeError('Argument must not be a number')
  14515. }
  14516. return Buffer(arg, encodingOrOffset, length)
  14517. }
  14518. SafeBuffer.alloc = function (size, fill, encoding) {
  14519. if (typeof size !== 'number') {
  14520. throw new TypeError('Argument must be a number')
  14521. }
  14522. var buf = Buffer(size)
  14523. if (fill !== undefined) {
  14524. if (typeof encoding === 'string') {
  14525. buf.fill(fill, encoding)
  14526. } else {
  14527. buf.fill(fill)
  14528. }
  14529. } else {
  14530. buf.fill(0)
  14531. }
  14532. return buf
  14533. }
  14534. SafeBuffer.allocUnsafe = function (size) {
  14535. if (typeof size !== 'number') {
  14536. throw new TypeError('Argument must be a number')
  14537. }
  14538. return Buffer(size)
  14539. }
  14540. SafeBuffer.allocUnsafeSlow = function (size) {
  14541. if (typeof size !== 'number') {
  14542. throw new TypeError('Argument must be a number')
  14543. }
  14544. return buffer.SlowBuffer(size)
  14545. }
  14546. }, { "buffer": 3 }], 79: [function (require, module, exports) {
  14547. (function (setImmediate) {
  14548. 'use strict';
  14549. module.exports = typeof setImmediate === 'function' ? setImmediate :
  14550. function setImmediate() {
  14551. var args = [].slice.apply(arguments);
  14552. args.splice(1, 0, 0);
  14553. setTimeout.apply(null, args);
  14554. };
  14555. }).call(this, require("timers").setImmediate)
  14556. }, { "timers": 82 }], 80: [function (require, module, exports) {
  14557. // Copyright Joyent, Inc. and other Node contributors.
  14558. //
  14559. // Permission is hereby granted, free of charge, to any person obtaining a
  14560. // copy of this software and associated documentation files (the
  14561. // "Software"), to deal in the Software without restriction, including
  14562. // without limitation the rights to use, copy, modify, merge, publish,
  14563. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14564. // persons to whom the Software is furnished to do so, subject to the
  14565. // following conditions:
  14566. //
  14567. // The above copyright notice and this permission notice shall be included
  14568. // in all copies or substantial portions of the Software.
  14569. //
  14570. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14571. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14572. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14573. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14574. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14575. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14576. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14577. module.exports = Stream;
  14578. var EE = require('events').EventEmitter;
  14579. var inherits = require('inherits');
  14580. inherits(Stream, EE);
  14581. Stream.Readable = require('readable-stream/readable.js');
  14582. Stream.Writable = require('readable-stream/writable.js');
  14583. Stream.Duplex = require('readable-stream/duplex.js');
  14584. Stream.Transform = require('readable-stream/transform.js');
  14585. Stream.PassThrough = require('readable-stream/passthrough.js');
  14586. // Backwards-compat with node 0.4.x
  14587. Stream.Stream = Stream;
  14588. // old-style streams. Note that the pipe method (the only relevant
  14589. // part of this class) is overridden in the Readable class.
  14590. function Stream() {
  14591. EE.call(this);
  14592. }
  14593. Stream.prototype.pipe = function (dest, options) {
  14594. var source = this;
  14595. function ondata(chunk) {
  14596. if (dest.writable) {
  14597. if (false === dest.write(chunk) && source.pause) {
  14598. source.pause();
  14599. }
  14600. }
  14601. }
  14602. source.on('data', ondata);
  14603. function ondrain() {
  14604. if (source.readable && source.resume) {
  14605. source.resume();
  14606. }
  14607. }
  14608. dest.on('drain', ondrain);
  14609. // If the 'end' option is not supplied, dest.end() will be called when
  14610. // source gets the 'end' or 'close' events. Only dest.end() once.
  14611. if (!dest._isStdio && (!options || options.end !== false)) {
  14612. source.on('end', onend);
  14613. source.on('close', onclose);
  14614. }
  14615. var didOnEnd = false;
  14616. function onend() {
  14617. if (didOnEnd) return;
  14618. didOnEnd = true;
  14619. dest.end();
  14620. }
  14621. function onclose() {
  14622. if (didOnEnd) return;
  14623. didOnEnd = true;
  14624. if (typeof dest.destroy === 'function') dest.destroy();
  14625. }
  14626. // don't leave dangling pipes when there are errors.
  14627. function onerror(er) {
  14628. cleanup();
  14629. if (EE.listenerCount(this, 'error') === 0) {
  14630. throw er; // Unhandled stream error in pipe.
  14631. }
  14632. }
  14633. source.on('error', onerror);
  14634. dest.on('error', onerror);
  14635. // remove all the event listeners that were added.
  14636. function cleanup() {
  14637. source.removeListener('data', ondata);
  14638. dest.removeListener('drain', ondrain);
  14639. source.removeListener('end', onend);
  14640. source.removeListener('close', onclose);
  14641. source.removeListener('error', onerror);
  14642. dest.removeListener('error', onerror);
  14643. source.removeListener('end', cleanup);
  14644. source.removeListener('close', cleanup);
  14645. dest.removeListener('close', cleanup);
  14646. }
  14647. source.on('end', cleanup);
  14648. source.on('close', cleanup);
  14649. dest.on('close', cleanup);
  14650. dest.emit('pipe', source);
  14651. // Allow for unix-like usage: A.pipe(B).pipe(C)
  14652. return dest;
  14653. };
  14654. }, { "events": 5, "inherits": 8, "readable-stream/duplex.js": 65, "readable-stream/passthrough.js": 74, "readable-stream/readable.js": 75, "readable-stream/transform.js": 76, "readable-stream/writable.js": 77 }], 81: [function (require, module, exports) {
  14655. // Copyright Joyent, Inc. and other Node contributors.
  14656. //
  14657. // Permission is hereby granted, free of charge, to any person obtaining a
  14658. // copy of this software and associated documentation files (the
  14659. // "Software"), to deal in the Software without restriction, including
  14660. // without limitation the rights to use, copy, modify, merge, publish,
  14661. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14662. // persons to whom the Software is furnished to do so, subject to the
  14663. // following conditions:
  14664. //
  14665. // The above copyright notice and this permission notice shall be included
  14666. // in all copies or substantial portions of the Software.
  14667. //
  14668. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14669. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14670. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14671. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14672. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14673. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14674. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14675. 'use strict';
  14676. /*<replacement>*/
  14677. var Buffer = require('safe-buffer').Buffer;
  14678. /*</replacement>*/
  14679. var isEncoding = Buffer.isEncoding || function (encoding) {
  14680. encoding = '' + encoding;
  14681. switch (encoding && encoding.toLowerCase()) {
  14682. 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':
  14683. return true;
  14684. default:
  14685. return false;
  14686. }
  14687. };
  14688. function _normalizeEncoding(enc) {
  14689. if (!enc) return 'utf8';
  14690. var retried;
  14691. while (true) {
  14692. switch (enc) {
  14693. case 'utf8':
  14694. case 'utf-8':
  14695. return 'utf8';
  14696. case 'ucs2':
  14697. case 'ucs-2':
  14698. case 'utf16le':
  14699. case 'utf-16le':
  14700. return 'utf16le';
  14701. case 'latin1':
  14702. case 'binary':
  14703. return 'latin1';
  14704. case 'base64':
  14705. case 'ascii':
  14706. case 'hex':
  14707. return enc;
  14708. default:
  14709. if (retried) return; // undefined
  14710. enc = ('' + enc).toLowerCase();
  14711. retried = true;
  14712. }
  14713. }
  14714. };
  14715. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  14716. // modules monkey-patch it to support additional encodings
  14717. function normalizeEncoding(enc) {
  14718. var nenc = _normalizeEncoding(enc);
  14719. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  14720. return nenc || enc;
  14721. }
  14722. // StringDecoder provides an interface for efficiently splitting a series of
  14723. // buffers into a series of JS strings without breaking apart multi-byte
  14724. // characters.
  14725. exports.StringDecoder = StringDecoder;
  14726. function StringDecoder(encoding) {
  14727. this.encoding = normalizeEncoding(encoding);
  14728. var nb;
  14729. switch (this.encoding) {
  14730. case 'utf16le':
  14731. this.text = utf16Text;
  14732. this.end = utf16End;
  14733. nb = 4;
  14734. break;
  14735. case 'utf8':
  14736. this.fillLast = utf8FillLast;
  14737. nb = 4;
  14738. break;
  14739. case 'base64':
  14740. this.text = base64Text;
  14741. this.end = base64End;
  14742. nb = 3;
  14743. break;
  14744. default:
  14745. this.write = simpleWrite;
  14746. this.end = simpleEnd;
  14747. return;
  14748. }
  14749. this.lastNeed = 0;
  14750. this.lastTotal = 0;
  14751. this.lastChar = Buffer.allocUnsafe(nb);
  14752. }
  14753. StringDecoder.prototype.write = function (buf) {
  14754. if (buf.length === 0) return '';
  14755. var r;
  14756. var i;
  14757. if (this.lastNeed) {
  14758. r = this.fillLast(buf);
  14759. if (r === undefined) return '';
  14760. i = this.lastNeed;
  14761. this.lastNeed = 0;
  14762. } else {
  14763. i = 0;
  14764. }
  14765. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  14766. return r || '';
  14767. };
  14768. StringDecoder.prototype.end = utf8End;
  14769. // Returns only complete characters in a Buffer
  14770. StringDecoder.prototype.text = utf8Text;
  14771. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  14772. StringDecoder.prototype.fillLast = function (buf) {
  14773. if (this.lastNeed <= buf.length) {
  14774. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  14775. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  14776. }
  14777. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  14778. this.lastNeed -= buf.length;
  14779. };
  14780. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  14781. // continuation byte. If an invalid byte is detected, -2 is returned.
  14782. function utf8CheckByte(byte) {
  14783. 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;
  14784. return byte >> 6 === 0x02 ? -1 : -2;
  14785. }
  14786. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  14787. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  14788. // needed to complete the UTF-8 character (if applicable) are returned.
  14789. function utf8CheckIncomplete(self, buf, i) {
  14790. var j = buf.length - 1;
  14791. if (j < i) return 0;
  14792. var nb = utf8CheckByte(buf[j]);
  14793. if (nb >= 0) {
  14794. if (nb > 0) self.lastNeed = nb - 1;
  14795. return nb;
  14796. }
  14797. if (--j < i || nb === -2) return 0;
  14798. nb = utf8CheckByte(buf[j]);
  14799. if (nb >= 0) {
  14800. if (nb > 0) self.lastNeed = nb - 2;
  14801. return nb;
  14802. }
  14803. if (--j < i || nb === -2) return 0;
  14804. nb = utf8CheckByte(buf[j]);
  14805. if (nb >= 0) {
  14806. if (nb > 0) {
  14807. if (nb === 2) nb = 0; else self.lastNeed = nb - 3;
  14808. }
  14809. return nb;
  14810. }
  14811. return 0;
  14812. }
  14813. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  14814. // needed or are available. If we see a non-continuation byte where we expect
  14815. // one, we "replace" the validated continuation bytes we've seen so far with
  14816. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  14817. // behavior. The continuation byte check is included three times in the case
  14818. // where all of the continuation bytes for a character exist in the same buffer.
  14819. // It is also done this way as a slight performance increase instead of using a
  14820. // loop.
  14821. function utf8CheckExtraBytes(self, buf, p) {
  14822. if ((buf[0] & 0xC0) !== 0x80) {
  14823. self.lastNeed = 0;
  14824. return '\ufffd';
  14825. }
  14826. if (self.lastNeed > 1 && buf.length > 1) {
  14827. if ((buf[1] & 0xC0) !== 0x80) {
  14828. self.lastNeed = 1;
  14829. return '\ufffd';
  14830. }
  14831. if (self.lastNeed > 2 && buf.length > 2) {
  14832. if ((buf[2] & 0xC0) !== 0x80) {
  14833. self.lastNeed = 2;
  14834. return '\ufffd';
  14835. }
  14836. }
  14837. }
  14838. }
  14839. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  14840. function utf8FillLast(buf) {
  14841. var p = this.lastTotal - this.lastNeed;
  14842. var r = utf8CheckExtraBytes(this, buf, p);
  14843. if (r !== undefined) return r;
  14844. if (this.lastNeed <= buf.length) {
  14845. buf.copy(this.lastChar, p, 0, this.lastNeed);
  14846. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  14847. }
  14848. buf.copy(this.lastChar, p, 0, buf.length);
  14849. this.lastNeed -= buf.length;
  14850. }
  14851. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  14852. // partial character, the character's bytes are buffered until the required
  14853. // number of bytes are available.
  14854. function utf8Text(buf, i) {
  14855. var total = utf8CheckIncomplete(this, buf, i);
  14856. if (!this.lastNeed) return buf.toString('utf8', i);
  14857. this.lastTotal = total;
  14858. var end = buf.length - (total - this.lastNeed);
  14859. buf.copy(this.lastChar, 0, end);
  14860. return buf.toString('utf8', i, end);
  14861. }
  14862. // For UTF-8, a replacement character is added when ending on a partial
  14863. // character.
  14864. function utf8End(buf) {
  14865. var r = buf && buf.length ? this.write(buf) : '';
  14866. if (this.lastNeed) return r + '\ufffd';
  14867. return r;
  14868. }
  14869. // UTF-16LE typically needs two bytes per character, but even if we have an even
  14870. // number of bytes available, we need to check if we end on a leading/high
  14871. // surrogate. In that case, we need to wait for the next two bytes in order to
  14872. // decode the last character properly.
  14873. function utf16Text(buf, i) {
  14874. if ((buf.length - i) % 2 === 0) {
  14875. var r = buf.toString('utf16le', i);
  14876. if (r) {
  14877. var c = r.charCodeAt(r.length - 1);
  14878. if (c >= 0xD800 && c <= 0xDBFF) {
  14879. this.lastNeed = 2;
  14880. this.lastTotal = 4;
  14881. this.lastChar[0] = buf[buf.length - 2];
  14882. this.lastChar[1] = buf[buf.length - 1];
  14883. return r.slice(0, -1);
  14884. }
  14885. }
  14886. return r;
  14887. }
  14888. this.lastNeed = 1;
  14889. this.lastTotal = 2;
  14890. this.lastChar[0] = buf[buf.length - 1];
  14891. return buf.toString('utf16le', i, buf.length - 1);
  14892. }
  14893. // For UTF-16LE we do not explicitly append special replacement characters if we
  14894. // end on a partial character, we simply let v8 handle that.
  14895. function utf16End(buf) {
  14896. var r = buf && buf.length ? this.write(buf) : '';
  14897. if (this.lastNeed) {
  14898. var end = this.lastTotal - this.lastNeed;
  14899. return r + this.lastChar.toString('utf16le', 0, end);
  14900. }
  14901. return r;
  14902. }
  14903. function base64Text(buf, i) {
  14904. var n = (buf.length - i) % 3;
  14905. if (n === 0) return buf.toString('base64', i);
  14906. this.lastNeed = 3 - n;
  14907. this.lastTotal = 3;
  14908. if (n === 1) {
  14909. this.lastChar[0] = buf[buf.length - 1];
  14910. } else {
  14911. this.lastChar[0] = buf[buf.length - 2];
  14912. this.lastChar[1] = buf[buf.length - 1];
  14913. }
  14914. return buf.toString('base64', i, buf.length - n);
  14915. }
  14916. function base64End(buf) {
  14917. var r = buf && buf.length ? this.write(buf) : '';
  14918. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  14919. return r;
  14920. }
  14921. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  14922. function simpleWrite(buf) {
  14923. return buf.toString(this.encoding);
  14924. }
  14925. function simpleEnd(buf) {
  14926. return buf && buf.length ? this.write(buf) : '';
  14927. }
  14928. }, { "safe-buffer": 78 }], 82: [function (require, module, exports) {
  14929. (function (setImmediate, clearImmediate) {
  14930. var nextTick = require('process/browser.js').nextTick;
  14931. var apply = Function.prototype.apply;
  14932. var slice = Array.prototype.slice;
  14933. var immediateIds = {};
  14934. var nextImmediateId = 0;
  14935. // DOM APIs, for completeness
  14936. exports.setTimeout = function () {
  14937. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  14938. };
  14939. exports.setInterval = function () {
  14940. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  14941. };
  14942. exports.clearTimeout =
  14943. exports.clearInterval = function (timeout) { timeout.close(); };
  14944. function Timeout(id, clearFn) {
  14945. this._id = id;
  14946. this._clearFn = clearFn;
  14947. }
  14948. Timeout.prototype.unref = Timeout.prototype.ref = function () { };
  14949. Timeout.prototype.close = function () {
  14950. this._clearFn.call(window, this._id);
  14951. };
  14952. // Does not start the time, just sets up the members needed.
  14953. exports.enroll = function (item, msecs) {
  14954. clearTimeout(item._idleTimeoutId);
  14955. item._idleTimeout = msecs;
  14956. };
  14957. exports.unenroll = function (item) {
  14958. clearTimeout(item._idleTimeoutId);
  14959. item._idleTimeout = -1;
  14960. };
  14961. exports._unrefActive = exports.active = function (item) {
  14962. clearTimeout(item._idleTimeoutId);
  14963. var msecs = item._idleTimeout;
  14964. if (msecs >= 0) {
  14965. item._idleTimeoutId = setTimeout(function onTimeout() {
  14966. if (item._onTimeout)
  14967. item._onTimeout();
  14968. }, msecs);
  14969. }
  14970. };
  14971. // That's not how node.js implements it but the exposed api is the same.
  14972. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function (fn) {
  14973. var id = nextImmediateId++;
  14974. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  14975. immediateIds[id] = true;
  14976. nextTick(function onNextTick() {
  14977. if (immediateIds[id]) {
  14978. // fn.call() is faster so we optimize for the common use-case
  14979. // @see http://jsperf.com/call-apply-segu
  14980. if (args) {
  14981. fn.apply(null, args);
  14982. } else {
  14983. fn.call(null);
  14984. }
  14985. // Prevent ids from leaking
  14986. exports.clearImmediate(id);
  14987. }
  14988. });
  14989. return id;
  14990. };
  14991. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function (id) {
  14992. delete immediateIds[id];
  14993. };
  14994. }).call(this, require("timers").setImmediate, require("timers").clearImmediate)
  14995. }, { "process/browser.js": 64, "timers": 82 }], 83: [function (require, module, exports) {
  14996. (function (global) {
  14997. /**
  14998. * Module exports.
  14999. */
  15000. module.exports = deprecate;
  15001. /**
  15002. * Mark that a method should not be used.
  15003. * Returns a modified function which warns once by default.
  15004. *
  15005. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  15006. *
  15007. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  15008. * will throw an Error when invoked.
  15009. *
  15010. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  15011. * will invoke `console.trace()` instead of `console.error()`.
  15012. *
  15013. * @param {Function} fn - the function to deprecate
  15014. * @param {String} msg - the string to print to the console when `fn` is invoked
  15015. * @returns {Function} a new "deprecated" version of `fn`
  15016. * @api public
  15017. */
  15018. function deprecate(fn, msg) {
  15019. if (config('noDeprecation')) {
  15020. return fn;
  15021. }
  15022. var warned = false;
  15023. function deprecated() {
  15024. if (!warned) {
  15025. if (config('throwDeprecation')) {
  15026. throw new Error(msg);
  15027. } else if (config('traceDeprecation')) {
  15028. console.trace(msg);
  15029. } else {
  15030. console.warn(msg);
  15031. }
  15032. warned = true;
  15033. }
  15034. return fn.apply(this, arguments);
  15035. }
  15036. return deprecated;
  15037. }
  15038. /**
  15039. * Checks `localStorage` for boolean values for the given `name`.
  15040. *
  15041. * @param {String} name
  15042. * @returns {Boolean}
  15043. * @api private
  15044. */
  15045. function config(name) {
  15046. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  15047. try {
  15048. if (!global.localStorage) return false;
  15049. } catch (_) {
  15050. return false;
  15051. }
  15052. var val = global.localStorage[name];
  15053. if (null == val) return false;
  15054. return String(val).toLowerCase() === 'true';
  15055. }
  15056. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  15057. }, {}], 84: [function (require, module, exports) {
  15058. "use strict";
  15059. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  15060. return mod && mod.__esModule ? mod : {
  15061. "default": mod
  15062. };
  15063. };
  15064. Object.defineProperty(exports, "__esModule", {
  15065. value: true
  15066. });
  15067. exports.HandleZip = void 0;
  15068. var jszip_1 = __importDefault(require("jszip"));
  15069. var method_1 = require("./common/method");
  15070. var HandleZip =
  15071. /** @class */
  15072. function () {
  15073. function HandleZip(file) {
  15074. // Support nodejs fs to read files
  15075. // if(file instanceof File){
  15076. this.uploadFile = file; // }
  15077. }
  15078. HandleZip.prototype.unzipFile = function (successFunc, errorFunc) {
  15079. // var new_zip:JSZip = new JSZip();
  15080. jszip_1["default"].loadAsync(this.uploadFile) // 1) read the Blob
  15081. .then(function (zip) {
  15082. var fileList = {},
  15083. lastIndex = Object.keys(zip.files).length,
  15084. index = 0;
  15085. zip.forEach(function (relativePath, zipEntry) {
  15086. var fileName = zipEntry.name;
  15087. var fileNameArr = fileName.split(".");
  15088. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  15089. var fileType = "string";
  15090. if (suffix in {
  15091. "png": 1,
  15092. "jpeg": 1,
  15093. "jpg": 1,
  15094. "gif": 1,
  15095. "bmp": 1,
  15096. "tif": 1,
  15097. "webp": 1
  15098. }) {
  15099. fileType = "base64";
  15100. } else if (suffix == "emf") {
  15101. fileType = "arraybuffer";
  15102. }
  15103. zipEntry.async(fileType).then(function (data) {
  15104. if (fileType == "base64") {
  15105. data = "data:image/" + suffix + ";base64," + data;
  15106. }
  15107. fileList[zipEntry.name] = data; // console.log(lastIndex, index);
  15108. if (lastIndex == index + 1) {
  15109. successFunc(fileList);
  15110. }
  15111. index++;
  15112. });
  15113. });
  15114. }, function (e) {
  15115. errorFunc(e);
  15116. });
  15117. };
  15118. HandleZip.prototype.unzipFileByUrl = function (url, successFunc, errorFunc) {
  15119. var new_zip = new jszip_1["default"]();
  15120. method_1.getBinaryContent(url, function (err, data) {
  15121. if (err) {
  15122. throw err; // or handle err
  15123. }
  15124. jszip_1["default"].loadAsync(data).then(function (zip) {
  15125. var fileList = {},
  15126. lastIndex = Object.keys(zip.files).length,
  15127. index = 0;
  15128. zip.forEach(function (relativePath, zipEntry) {
  15129. var fileName = zipEntry.name;
  15130. var fileNameArr = fileName.split(".");
  15131. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  15132. var fileType = "string";
  15133. if (suffix in {
  15134. "png": 1,
  15135. "jpeg": 1,
  15136. "jpg": 1,
  15137. "gif": 1,
  15138. "bmp": 1,
  15139. "tif": 1,
  15140. "webp": 1
  15141. }) {
  15142. fileType = "base64";
  15143. } else if (suffix == "emf") {
  15144. fileType = "arraybuffer";
  15145. }
  15146. zipEntry.async(fileType).then(function (data) {
  15147. if (fileType == "base64") {
  15148. data = "data:image/" + suffix + ";base64," + data;
  15149. }
  15150. fileList[zipEntry.name] = data; // console.log(lastIndex, index);
  15151. if (lastIndex == index + 1) {
  15152. successFunc(fileList);
  15153. }
  15154. index++;
  15155. });
  15156. });
  15157. }, function (e) {
  15158. errorFunc(e);
  15159. });
  15160. });
  15161. };
  15162. HandleZip.prototype.newZipFile = function () {
  15163. var zip = new jszip_1["default"]();
  15164. this.workBook = zip;
  15165. }; //title:"nested/hello.txt", content:"Hello Worldasdfasfasdfasfasfasfasfasdfas"
  15166. HandleZip.prototype.addToZipFile = function (title, content) {
  15167. if (this.workBook == null) {
  15168. var zip = new jszip_1["default"]();
  15169. this.workBook = zip;
  15170. }
  15171. this.workBook.file(title, content);
  15172. };
  15173. return HandleZip;
  15174. }();
  15175. exports.HandleZip = HandleZip;
  15176. }, { "./common/method": 93, "jszip": 20 }], 85: [function (require, module, exports) {
  15177. "use strict";
  15178. Object.defineProperty(exports, "__esModule", {
  15179. value: true
  15180. });
  15181. 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;
  15182. var LuckyFileBase =
  15183. /** @class */
  15184. function () {
  15185. function LuckyFileBase() { }
  15186. return LuckyFileBase;
  15187. }();
  15188. exports.LuckyFileBase = LuckyFileBase;
  15189. var LuckySheetBase =
  15190. /** @class */
  15191. function () {
  15192. function LuckySheetBase() { }
  15193. return LuckySheetBase;
  15194. }();
  15195. exports.LuckySheetBase = LuckySheetBase;
  15196. var LuckyFileInfo =
  15197. /** @class */
  15198. function () {
  15199. function LuckyFileInfo() { }
  15200. return LuckyFileInfo;
  15201. }();
  15202. exports.LuckyFileInfo = LuckyFileInfo;
  15203. var LuckySheetCelldataBase =
  15204. /** @class */
  15205. function () {
  15206. function LuckySheetCelldataBase() { }
  15207. return LuckySheetCelldataBase;
  15208. }();
  15209. exports.LuckySheetCelldataBase = LuckySheetCelldataBase;
  15210. var LuckySheetCelldataValue =
  15211. /** @class */
  15212. function () {
  15213. function LuckySheetCelldataValue() { }
  15214. return LuckySheetCelldataValue;
  15215. }();
  15216. exports.LuckySheetCelldataValue = LuckySheetCelldataValue;
  15217. var LuckySheetCellFormat =
  15218. /** @class */
  15219. function () {
  15220. function LuckySheetCellFormat() { }
  15221. return LuckySheetCellFormat;
  15222. }();
  15223. exports.LuckySheetCellFormat = LuckySheetCellFormat;
  15224. var LuckyInlineString =
  15225. /** @class */
  15226. function () {
  15227. function LuckyInlineString() { }
  15228. return LuckyInlineString;
  15229. }();
  15230. exports.LuckyInlineString = LuckyInlineString;
  15231. var LuckyConfig =
  15232. /** @class */
  15233. function () {
  15234. function LuckyConfig() { }
  15235. return LuckyConfig;
  15236. }();
  15237. exports.LuckyConfig = LuckyConfig;
  15238. var LuckySheetborderInfoCellForImp =
  15239. /** @class */
  15240. function () {
  15241. function LuckySheetborderInfoCellForImp() { }
  15242. return LuckySheetborderInfoCellForImp;
  15243. }();
  15244. exports.LuckySheetborderInfoCellForImp = LuckySheetborderInfoCellForImp;
  15245. var LuckySheetborderInfoCellValue =
  15246. /** @class */
  15247. function () {
  15248. function LuckySheetborderInfoCellValue() { }
  15249. return LuckySheetborderInfoCellValue;
  15250. }();
  15251. exports.LuckySheetborderInfoCellValue = LuckySheetborderInfoCellValue;
  15252. var LuckySheetborderInfoCellValueStyle =
  15253. /** @class */
  15254. function () {
  15255. function LuckySheetborderInfoCellValueStyle() { }
  15256. return LuckySheetborderInfoCellValueStyle;
  15257. }();
  15258. exports.LuckySheetborderInfoCellValueStyle = LuckySheetborderInfoCellValueStyle;
  15259. var LuckySheetConfigMerge =
  15260. /** @class */
  15261. function () {
  15262. function LuckySheetConfigMerge() { }
  15263. return LuckySheetConfigMerge;
  15264. }();
  15265. exports.LuckySheetConfigMerge = LuckySheetConfigMerge;
  15266. var LuckysheetCalcChain =
  15267. /** @class */
  15268. function () {
  15269. function LuckysheetCalcChain() { }
  15270. return LuckysheetCalcChain;
  15271. }();
  15272. exports.LuckysheetCalcChain = LuckysheetCalcChain;
  15273. var LuckyImageBase =
  15274. /** @class */
  15275. function () {
  15276. function LuckyImageBase() { }
  15277. return LuckyImageBase;
  15278. }();
  15279. exports.LuckyImageBase = LuckyImageBase;
  15280. }, {}], 86: [function (require, module, exports) {
  15281. "use strict";
  15282. var __extends = void 0 && (void 0).__extends || function () {
  15283. var _extendStatics = function extendStatics(d, b) {
  15284. _extendStatics = Object.setPrototypeOf || {
  15285. __proto__: []
  15286. } instanceof Array && function (d, b) {
  15287. d.__proto__ = b;
  15288. } || function (d, b) {
  15289. for (var p in b) {
  15290. if (b.hasOwnProperty(p)) d[p] = b[p];
  15291. }
  15292. };
  15293. return _extendStatics(d, b);
  15294. };
  15295. return function (d, b) {
  15296. _extendStatics(d, b);
  15297. function __() {
  15298. this.constructor = d;
  15299. }
  15300. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15301. };
  15302. }();
  15303. Object.defineProperty(exports, "__esModule", {
  15304. value: true
  15305. });
  15306. exports.LuckySheetCelldata = void 0;
  15307. var ReadXml_1 = require("./ReadXml");
  15308. var method_1 = require("../common/method");
  15309. var constant_1 = require("../common/constant");
  15310. var LuckyBase_1 = require("./LuckyBase");
  15311. var LuckySheetCelldata =
  15312. /** @class */
  15313. function (_super) {
  15314. __extends(LuckySheetCelldata, _super);
  15315. function LuckySheetCelldata(cell, styles, sharedStrings, mergeCells, sheetFile, ReadXml) {
  15316. var _this = //Private
  15317. _super.call(this) || this;
  15318. _this.cell = cell;
  15319. _this.sheetFile = sheetFile;
  15320. _this.styles = styles;
  15321. _this.sharedStrings = sharedStrings;
  15322. _this.readXml = ReadXml;
  15323. _this.mergeCells = mergeCells;
  15324. var attrList = cell.attributeList;
  15325. var r = attrList.r,
  15326. s = attrList.s,
  15327. t = attrList.t;
  15328. var range = method_1.getcellrange(r);
  15329. _this.r = range.row[0];
  15330. _this.c = range.column[0];
  15331. _this.v = _this.generateValue(s, t);
  15332. return _this;
  15333. }
  15334. /**
  15335. * @param s Style index ,start 1
  15336. * @param t Cell type, Optional value is ST_CellType, it's found at constat.ts
  15337. */
  15338. LuckySheetCelldata.prototype.generateValue = function (s, t) {
  15339. var _this = this;
  15340. var v = this.cell.getInnerElements("v");
  15341. var f = this.cell.getInnerElements("f");
  15342. if (v == null) {
  15343. v = this.cell.getInnerElements("t");
  15344. }
  15345. var cellXfs = this.styles["cellXfs"];
  15346. var cellStyleXfs = this.styles["cellStyleXfs"];
  15347. var cellStyles = this.styles["cellStyles"];
  15348. var fonts = this.styles["fonts"];
  15349. var fills = this.styles["fills"];
  15350. var borders = this.styles["borders"];
  15351. var numfmts = this.styles["numfmts"];
  15352. var clrScheme = this.styles["clrScheme"];
  15353. var sharedStrings = this.sharedStrings;
  15354. var cellValue = new LuckyBase_1.LuckySheetCelldataValue();
  15355. if (f != null) {
  15356. var formula = f[0],
  15357. attrList = formula.attributeList;
  15358. var t_1 = attrList.t,
  15359. ref = attrList.ref,
  15360. si = attrList.si;
  15361. var formulaValue = f[0].value;
  15362. if (t_1 == "shared") {
  15363. this._fomulaRef = ref;
  15364. this._formulaType = t_1;
  15365. this._formulaSi = si;
  15366. } // console.log(ref, t, si);
  15367. if (ref != null || formulaValue != null && formulaValue.length > 0) {
  15368. formulaValue = method_1.escapeCharacter(formulaValue);
  15369. cellValue.f = "=" + formulaValue;
  15370. }
  15371. }
  15372. var familyFont = null;
  15373. var quotePrefix;
  15374. if (s != null) {
  15375. var sNum = parseInt(s);
  15376. var cellXf = cellXfs[sNum];
  15377. var xfId = cellXf.attributeList.xfId;
  15378. var numFmtId = void 0,
  15379. fontId = void 0,
  15380. fillId = void 0,
  15381. borderId = void 0;
  15382. var horizontal = void 0,
  15383. vertical = void 0,
  15384. wrapText = void 0,
  15385. textRotation = void 0,
  15386. shrinkToFit = void 0,
  15387. indent = void 0,
  15388. applyProtection = void 0;
  15389. if (xfId != null) {
  15390. var cellStyleXf = cellStyleXfs[parseInt(xfId)];
  15391. var attrList = cellStyleXf.attributeList;
  15392. var applyNumberFormat_1 = attrList.applyNumberFormat;
  15393. var applyFont_1 = attrList.applyFont;
  15394. var applyFill_1 = attrList.applyFill;
  15395. var applyBorder_1 = attrList.applyBorder;
  15396. var applyAlignment_1 = attrList.applyAlignment; // let applyProtection = attrList.applyProtection;
  15397. applyProtection = attrList.applyProtection;
  15398. quotePrefix = attrList.quotePrefix;
  15399. if (applyNumberFormat_1 != "0" && attrList.numFmtId != null) {
  15400. // if(attrList.numFmtId!="0"){
  15401. numFmtId = attrList.numFmtId; // }
  15402. }
  15403. if (applyFont_1 != "0" && attrList.fontId != null) {
  15404. fontId = attrList.fontId;
  15405. }
  15406. if (applyFill_1 != "0" && attrList.fillId != null) {
  15407. fillId = attrList.fillId;
  15408. }
  15409. if (applyBorder_1 != "0" && attrList.borderId != null) {
  15410. borderId = attrList.borderId;
  15411. }
  15412. if (applyAlignment_1 != null && applyAlignment_1 != "0") {
  15413. var alignment = cellStyleXf.getInnerElements("alignment");
  15414. if (alignment != null) {
  15415. var attrList_1 = alignment[0].attributeList;
  15416. if (attrList_1.horizontal != null) {
  15417. horizontal = attrList_1.horizontal;
  15418. }
  15419. if (attrList_1.vertical != null) {
  15420. vertical = attrList_1.vertical;
  15421. }
  15422. if (attrList_1.wrapText != null) {
  15423. wrapText = attrList_1.wrapText;
  15424. }
  15425. if (attrList_1.textRotation != null) {
  15426. textRotation = attrList_1.textRotation;
  15427. }
  15428. if (attrList_1.shrinkToFit != null) {
  15429. shrinkToFit = attrList_1.shrinkToFit;
  15430. }
  15431. if (attrList_1.indent != null) {
  15432. indent = attrList_1.indent;
  15433. }
  15434. }
  15435. }
  15436. }
  15437. var applyNumberFormat = cellXf.attributeList.applyNumberFormat;
  15438. var applyFont = cellXf.attributeList.applyFont;
  15439. var applyFill = cellXf.attributeList.applyFill;
  15440. var applyBorder = cellXf.attributeList.applyBorder;
  15441. var applyAlignment = cellXf.attributeList.applyAlignment;
  15442. if (cellXf.attributeList.applyProtection != null) {
  15443. applyProtection = cellXf.attributeList.applyProtection;
  15444. }
  15445. if (cellXf.attributeList.quotePrefix != null) {
  15446. quotePrefix = cellXf.attributeList.quotePrefix;
  15447. }
  15448. if (applyNumberFormat != "0" && cellXf.attributeList.numFmtId != null) {
  15449. numFmtId = cellXf.attributeList.numFmtId;
  15450. }
  15451. if (applyFont != "0") {
  15452. fontId = cellXf.attributeList.fontId;
  15453. }
  15454. if (applyFill != "0") {
  15455. fillId = cellXf.attributeList.fillId;
  15456. }
  15457. if (applyBorder != "0") {
  15458. borderId = cellXf.attributeList.borderId;
  15459. }
  15460. if (applyAlignment != "0") {
  15461. var alignment = cellXf.getInnerElements("alignment");
  15462. if (alignment != null && alignment.length > 0) {
  15463. var attrList = alignment[0].attributeList;
  15464. if (attrList.horizontal != null) {
  15465. horizontal = attrList.horizontal;
  15466. }
  15467. if (attrList.vertical != null) {
  15468. vertical = attrList.vertical;
  15469. }
  15470. if (attrList.wrapText != null) {
  15471. wrapText = attrList.wrapText;
  15472. }
  15473. if (attrList.textRotation != null) {
  15474. textRotation = attrList.textRotation;
  15475. }
  15476. if (attrList.shrinkToFit != null) {
  15477. shrinkToFit = attrList.shrinkToFit;
  15478. }
  15479. if (attrList.indent != null) {
  15480. indent = attrList.indent;
  15481. }
  15482. }
  15483. }
  15484. if (numFmtId != undefined) {
  15485. var numf = numfmts[parseInt(numFmtId)];
  15486. var cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15487. cellFormat.fa = method_1.escapeCharacter(numf); // console.log(numf, numFmtId, this.v);
  15488. cellFormat.t = t;
  15489. cellValue.ct = cellFormat;
  15490. }
  15491. if (fillId != undefined) {
  15492. var fillIdNum = parseInt(fillId);
  15493. var fill = fills[fillIdNum]; // console.log(cellValue.v);
  15494. var bg = this.getBackgroundByFill(fill, clrScheme);
  15495. if (bg != null) {
  15496. cellValue.bg = bg;
  15497. }
  15498. }
  15499. if (fontId != undefined) {
  15500. var fontIdNum = parseInt(fontId);
  15501. var font = fonts[fontIdNum];
  15502. if (font != null) {
  15503. var sz = font.getInnerElements("sz"); //font size
  15504. var colors = font.getInnerElements("color"); //font color
  15505. var family = font.getInnerElements("name"); //font family
  15506. var familyOverrides = font.getInnerElements("family"); //font family will be overrided by name
  15507. var charset = font.getInnerElements("charset"); //font charset
  15508. var bolds = font.getInnerElements("b"); //font bold
  15509. var italics = font.getInnerElements("i"); //font italic
  15510. var strikes = font.getInnerElements("strike"); //font italic
  15511. var underlines = font.getInnerElements("u"); //font italic
  15512. if (sz != null && sz.length > 0) {
  15513. var fs = sz[0].attributeList.val;
  15514. if (fs != null) {
  15515. cellValue.fs = parseInt(fs);
  15516. }
  15517. }
  15518. if (colors != null && colors.length > 0) {
  15519. var color = colors[0];
  15520. var fc = ReadXml_1.getColor(color, this.styles, "t");
  15521. if (fc != null) {
  15522. cellValue.fc = fc;
  15523. }
  15524. }
  15525. if (familyOverrides != null && familyOverrides.length > 0) {
  15526. var val = familyOverrides[0].attributeList.val;
  15527. if (val != null) {
  15528. familyFont = constant_1.fontFamilys[val];
  15529. }
  15530. }
  15531. if (family != null && family.length > 0) {
  15532. var val = family[0].attributeList.val;
  15533. if (val != null) {
  15534. cellValue.ff = val;
  15535. }
  15536. }
  15537. if (bolds != null && bolds.length > 0) {
  15538. var bold = bolds[0].attributeList.val;
  15539. if (bold == "0") {
  15540. cellValue.bl = 0;
  15541. } else {
  15542. cellValue.bl = 1;
  15543. }
  15544. }
  15545. if (italics != null && italics.length > 0) {
  15546. var italic = italics[0].attributeList.val;
  15547. if (italic == "0") {
  15548. cellValue.it = 0;
  15549. } else {
  15550. cellValue.it = 1;
  15551. }
  15552. }
  15553. if (strikes != null && strikes.length > 0) {
  15554. var strike = strikes[0].attributeList.val;
  15555. if (strike == "0") {
  15556. cellValue.cl = 0;
  15557. } else {
  15558. cellValue.cl = 1;
  15559. }
  15560. }
  15561. if (underlines != null && underlines.length > 0) {
  15562. var underline = underlines[0].attributeList.val;
  15563. if (underline == "single") {
  15564. cellValue.un = 1;
  15565. } else if (underline == "double") {
  15566. cellValue.un = 2;
  15567. } else if (underline == "singleAccounting") {
  15568. cellValue.un = 3;
  15569. } else if (underline == "doubleAccounting") {
  15570. cellValue.un = 4;
  15571. } else {
  15572. cellValue.un = 0;
  15573. }
  15574. }
  15575. }
  15576. } // vt: number | undefined//Vertical alignment, 0 middle, 1 up, 2 down, alignment
  15577. // ht: number | undefined//Horizontal alignment,0 center, 1 left, 2 right, alignment
  15578. // tr: number | undefined //Text rotation,0: 0、1: 45 、2: -45、3 Vertical text、4: 90 、5: -90, alignment
  15579. // tb: number | undefined //Text wrap,0 truncation, 1 overflow, 2 word wrap, alignment
  15580. if (horizontal != undefined) {
  15581. //Horizontal alignment
  15582. if (horizontal == "center") {
  15583. cellValue.ht = 0;
  15584. } else if (horizontal == "centerContinuous") {
  15585. cellValue.ht = 0; //luckysheet unsupport
  15586. } else if (horizontal == "left") {
  15587. cellValue.ht = 1;
  15588. } else if (horizontal == "right") {
  15589. cellValue.ht = 2;
  15590. } else if (horizontal == "distributed") {
  15591. cellValue.ht = 0; //luckysheet unsupport
  15592. } else if (horizontal == "fill") {
  15593. cellValue.ht = 1; //luckysheet unsupport
  15594. } else if (horizontal == "general") {
  15595. cellValue.ht = 1; //luckysheet unsupport
  15596. } else if (horizontal == "justify") {
  15597. cellValue.ht = 0; //luckysheet unsupport
  15598. } else {
  15599. cellValue.ht = 1;
  15600. }
  15601. }
  15602. if (vertical != undefined) {
  15603. //Vertical alignment
  15604. if (vertical == "bottom") {
  15605. cellValue.vt = 2;
  15606. } else if (vertical == "center") {
  15607. cellValue.vt = 0;
  15608. } else if (vertical == "distributed") {
  15609. cellValue.vt = 0; //luckysheet unsupport
  15610. } else if (vertical == "justify") {
  15611. cellValue.vt = 0; //luckysheet unsupport
  15612. } else if (vertical == "top") {
  15613. cellValue.vt = 1;
  15614. } else {
  15615. cellValue.vt = 1;
  15616. }
  15617. }
  15618. if (wrapText != undefined) {
  15619. if (wrapText == "1") {
  15620. cellValue.tb = 2;
  15621. } else {
  15622. cellValue.tb = 1;
  15623. }
  15624. } else {
  15625. cellValue.tb = 1;
  15626. }
  15627. if (textRotation != undefined) {
  15628. // tr: number | undefined //Text rotation,0: 0、1: 45 、2: -45、3 Vertical text、4: 90 、5: -90, alignment
  15629. if (textRotation == "255") {
  15630. cellValue.tr = 3;
  15631. } // else if(textRotation=="45"){
  15632. // cellValue.tr = 1;
  15633. // }
  15634. // else if(textRotation=="90"){
  15635. // cellValue.tr = 4;
  15636. // }
  15637. // else if(textRotation=="135"){
  15638. // cellValue.tr = 2;
  15639. // }
  15640. // else if(textRotation=="180"){
  15641. // cellValue.tr = 5;
  15642. // }
  15643. else {
  15644. cellValue.tr = 0;
  15645. cellValue.rt = parseInt(textRotation);
  15646. }
  15647. }
  15648. if (shrinkToFit != undefined) {//luckysheet unsupport
  15649. }
  15650. if (indent != undefined) {//luckysheet unsupport
  15651. }
  15652. if (borderId != undefined) {
  15653. var borderIdNum = parseInt(borderId);
  15654. var border = borders[borderIdNum]; // this._borderId = borderIdNum;
  15655. var borderObject = new LuckyBase_1.LuckySheetborderInfoCellForImp();
  15656. borderObject.rangeType = "cell"; // borderObject.cells = [];
  15657. var borderCellValue = new LuckyBase_1.LuckySheetborderInfoCellValue();
  15658. borderCellValue.row_index = this.r;
  15659. borderCellValue.col_index = this.c;
  15660. var lefts = border.getInnerElements("left");
  15661. var rights = border.getInnerElements("right");
  15662. var tops = border.getInnerElements("top");
  15663. var bottoms = border.getInnerElements("bottom");
  15664. var diagonals = border.getInnerElements("diagonal");
  15665. var starts = border.getInnerElements("start");
  15666. var ends = border.getInnerElements("end");
  15667. var left = this.getBorderInfo(lefts);
  15668. var right = this.getBorderInfo(rights);
  15669. var top_1 = this.getBorderInfo(tops);
  15670. var bottom = this.getBorderInfo(bottoms);
  15671. var diagonal = this.getBorderInfo(diagonals);
  15672. var start = this.getBorderInfo(starts);
  15673. var end = this.getBorderInfo(ends);
  15674. var isAdd = false;
  15675. if (start != null && start.color != null) {
  15676. borderCellValue.l = start;
  15677. isAdd = true;
  15678. }
  15679. if (end != null && end.color != null) {
  15680. borderCellValue.r = end;
  15681. isAdd = true;
  15682. }
  15683. if (left != null && left.color != null) {
  15684. borderCellValue.l = left;
  15685. isAdd = true;
  15686. }
  15687. if (right != null && right.color != null) {
  15688. borderCellValue.r = right;
  15689. isAdd = true;
  15690. }
  15691. if (top_1 != null && top_1.color != null) {
  15692. borderCellValue.t = top_1;
  15693. isAdd = true;
  15694. }
  15695. if (bottom != null && bottom.color != null) {
  15696. borderCellValue.b = bottom;
  15697. isAdd = true;
  15698. }
  15699. if (isAdd) {
  15700. borderObject.value = borderCellValue; // this.config._borderInfo[borderId] = borderObject;
  15701. this._borderObject = borderObject;
  15702. }
  15703. }
  15704. } else {
  15705. cellValue.tb = 1;
  15706. }
  15707. if (v != null) {
  15708. var value = v[0].value;
  15709. if (/&#\d+;/.test(value)) {
  15710. value = this.htmlDecode(value);
  15711. }
  15712. if (t == constant_1.ST_CellType["SharedString"]) {
  15713. var siIndex = parseInt(v[0].value);
  15714. var sharedSI = sharedStrings[siIndex];
  15715. var rFlag = sharedSI.getInnerElements("r");
  15716. if (rFlag == null) {
  15717. var tFlag = sharedSI.getInnerElements("t");
  15718. if (tFlag != null) {
  15719. var text_1 = "";
  15720. tFlag.forEach(function (t) {
  15721. text_1 += t.value;
  15722. });
  15723. text_1 = method_1.escapeCharacter(text_1); //isContainMultiType(text) &&
  15724. if (familyFont == "Roman" && text_1.length > 0) {
  15725. var textArray = text_1.split("");
  15726. var preWordType = null,
  15727. wordText = "",
  15728. preWholef = null;
  15729. var wholef = "Times New Roman";
  15730. if (cellValue.ff != null) {
  15731. wholef = cellValue.ff;
  15732. }
  15733. var cellFormat = cellValue.ct;
  15734. if (cellFormat == null) {
  15735. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15736. }
  15737. if (cellFormat.s == null) {
  15738. cellFormat.s = [];
  15739. }
  15740. for (var i = 0; i < textArray.length; i++) {
  15741. var w = textArray[i];
  15742. var type = null,
  15743. ff = wholef;
  15744. if (method_1.isChinese(w)) {
  15745. type = "c";
  15746. ff = "宋体";
  15747. } else if (method_1.isJapanese(w)) {
  15748. type = "j";
  15749. ff = "Yu Gothic";
  15750. } else if (method_1.isKoera(w)) {
  15751. type = "k";
  15752. ff = "Malgun Gothic";
  15753. } else {
  15754. type = "e";
  15755. }
  15756. if (type != preWordType && preWordType != null || i == textArray.length - 1) {
  15757. var InlineString = new LuckyBase_1.LuckyInlineString();
  15758. InlineString.ff = preWholef;
  15759. if (cellValue.fc != null) {
  15760. InlineString.fc = cellValue.fc;
  15761. }
  15762. if (cellValue.fs != null) {
  15763. InlineString.fs = cellValue.fs;
  15764. }
  15765. if (cellValue.cl != null) {
  15766. InlineString.cl = cellValue.cl;
  15767. }
  15768. if (cellValue.un != null) {
  15769. InlineString.un = cellValue.un;
  15770. }
  15771. if (cellValue.bl != null) {
  15772. InlineString.bl = cellValue.bl;
  15773. }
  15774. if (cellValue.it != null) {
  15775. InlineString.it = cellValue.it;
  15776. }
  15777. if (i == textArray.length - 1) {
  15778. if (type == preWordType) {
  15779. InlineString.ff = ff;
  15780. InlineString.v = wordText + w;
  15781. } else {
  15782. InlineString.ff = preWholef;
  15783. InlineString.v = wordText;
  15784. cellFormat.s.push(InlineString);
  15785. var InlineStringLast = new LuckyBase_1.LuckyInlineString();
  15786. InlineStringLast.ff = ff;
  15787. InlineStringLast.v = w;
  15788. if (cellValue.fc != null) {
  15789. InlineStringLast.fc = cellValue.fc;
  15790. }
  15791. if (cellValue.fs != null) {
  15792. InlineStringLast.fs = cellValue.fs;
  15793. }
  15794. if (cellValue.cl != null) {
  15795. InlineStringLast.cl = cellValue.cl;
  15796. }
  15797. if (cellValue.un != null) {
  15798. InlineStringLast.un = cellValue.un;
  15799. }
  15800. if (cellValue.bl != null) {
  15801. InlineStringLast.bl = cellValue.bl;
  15802. }
  15803. if (cellValue.it != null) {
  15804. InlineStringLast.it = cellValue.it;
  15805. }
  15806. cellFormat.s.push(InlineStringLast);
  15807. break;
  15808. }
  15809. } else {
  15810. InlineString.v = wordText;
  15811. }
  15812. cellFormat.s.push(InlineString);
  15813. wordText = w;
  15814. } else {
  15815. wordText += w;
  15816. }
  15817. preWordType = type;
  15818. preWholef = ff;
  15819. }
  15820. cellFormat.t = "inlineStr"; // cellFormat.s = [InlineString];
  15821. cellValue.ct = cellFormat; // console.log(cellValue);
  15822. } else {
  15823. text_1 = this.replaceSpecialWrap(text_1);
  15824. if (text_1.indexOf("\r\n") > -1 || text_1.indexOf("\n") > -1) {
  15825. var InlineString = new LuckyBase_1.LuckyInlineString();
  15826. InlineString.v = text_1;
  15827. var cellFormat = cellValue.ct;
  15828. if (cellFormat == null) {
  15829. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15830. }
  15831. if (cellValue.ff != null) {
  15832. InlineString.ff = cellValue.ff;
  15833. }
  15834. if (cellValue.fc != null) {
  15835. InlineString.fc = cellValue.fc;
  15836. }
  15837. if (cellValue.fs != null) {
  15838. InlineString.fs = cellValue.fs;
  15839. }
  15840. if (cellValue.cl != null) {
  15841. InlineString.cl = cellValue.cl;
  15842. }
  15843. if (cellValue.un != null) {
  15844. InlineString.un = cellValue.un;
  15845. }
  15846. if (cellValue.bl != null) {
  15847. InlineString.bl = cellValue.bl;
  15848. }
  15849. if (cellValue.it != null) {
  15850. InlineString.it = cellValue.it;
  15851. }
  15852. cellFormat.t = "inlineStr";
  15853. cellFormat.s = [InlineString];
  15854. cellValue.ct = cellFormat;
  15855. } else {
  15856. cellValue.v = text_1;
  15857. quotePrefix = "1";
  15858. }
  15859. }
  15860. }
  15861. } else {
  15862. var styles_1 = [];
  15863. rFlag.forEach(function (r) {
  15864. var tFlag = r.getInnerElements("t");
  15865. var rPr = r.getInnerElements("rPr");
  15866. var InlineString = new LuckyBase_1.LuckyInlineString();
  15867. if (tFlag != null && tFlag.length > 0) {
  15868. var text = tFlag[0].value;
  15869. text = _this.replaceSpecialWrap(text);
  15870. text = method_1.escapeCharacter(text);
  15871. InlineString.v = text;
  15872. }
  15873. if (rPr != null && rPr.length > 0) {
  15874. var frpr = rPr[0];
  15875. var sz = ReadXml_1.getlineStringAttr(frpr, "sz"),
  15876. rFont = ReadXml_1.getlineStringAttr(frpr, "rFont"),
  15877. family = ReadXml_1.getlineStringAttr(frpr, "family"),
  15878. charset = ReadXml_1.getlineStringAttr(frpr, "charset"),
  15879. scheme = ReadXml_1.getlineStringAttr(frpr, "scheme"),
  15880. b = ReadXml_1.getlineStringAttr(frpr, "b"),
  15881. i = ReadXml_1.getlineStringAttr(frpr, "i"),
  15882. u = ReadXml_1.getlineStringAttr(frpr, "u"),
  15883. strike = ReadXml_1.getlineStringAttr(frpr, "strike"),
  15884. vertAlign = ReadXml_1.getlineStringAttr(frpr, "vertAlign"),
  15885. color = void 0;
  15886. var cEle = frpr.getInnerElements("color");
  15887. if (cEle != null && cEle.length > 0) {
  15888. color = ReadXml_1.getColor(cEle[0], _this.styles, "t");
  15889. }
  15890. var ff = void 0; // if(family!=null){
  15891. // ff = fontFamilys[family];
  15892. // }
  15893. if (rFont != null) {
  15894. ff = rFont;
  15895. }
  15896. if (ff != null) {
  15897. InlineString.ff = ff;
  15898. } else if (cellValue.ff != null) {
  15899. InlineString.ff = cellValue.ff;
  15900. }
  15901. if (color != null) {
  15902. InlineString.fc = color;
  15903. } else if (cellValue.fc != null) {
  15904. InlineString.fc = cellValue.fc;
  15905. }
  15906. if (sz != null) {
  15907. InlineString.fs = parseInt(sz);
  15908. } else if (cellValue.fs != null) {
  15909. InlineString.fs = cellValue.fs;
  15910. }
  15911. if (strike != null) {
  15912. InlineString.cl = parseInt(strike);
  15913. } else if (cellValue.cl != null) {
  15914. InlineString.cl = cellValue.cl;
  15915. }
  15916. if (u != null) {
  15917. InlineString.un = parseInt(u);
  15918. } else if (cellValue.un != null) {
  15919. InlineString.un = cellValue.un;
  15920. }
  15921. if (b != null) {
  15922. InlineString.bl = parseInt(b);
  15923. } else if (cellValue.bl != null) {
  15924. InlineString.bl = cellValue.bl;
  15925. }
  15926. if (i != null) {
  15927. InlineString.it = parseInt(i);
  15928. } else if (cellValue.it != null) {
  15929. InlineString.it = cellValue.it;
  15930. }
  15931. if (vertAlign != null) {
  15932. InlineString.va = parseInt(vertAlign);
  15933. } // ff:string | undefined //font family
  15934. // fc:string | undefined//font color
  15935. // fs:number | undefined//font size
  15936. // cl:number | undefined//strike
  15937. // un:number | undefined//underline
  15938. // bl:number | undefined//blod
  15939. // it:number | undefined//italic
  15940. // v:string | undefined
  15941. } else {
  15942. if (InlineString.ff == null && cellValue.ff != null) {
  15943. InlineString.ff = cellValue.ff;
  15944. }
  15945. if (InlineString.fc == null && cellValue.fc != null) {
  15946. InlineString.fc = cellValue.fc;
  15947. }
  15948. if (InlineString.fs == null && cellValue.fs != null) {
  15949. InlineString.fs = cellValue.fs;
  15950. }
  15951. if (InlineString.cl == null && cellValue.cl != null) {
  15952. InlineString.cl = cellValue.cl;
  15953. }
  15954. if (InlineString.un == null && cellValue.un != null) {
  15955. InlineString.un = cellValue.un;
  15956. }
  15957. if (InlineString.bl == null && cellValue.bl != null) {
  15958. InlineString.bl = cellValue.bl;
  15959. }
  15960. if (InlineString.it == null && cellValue.it != null) {
  15961. InlineString.it = cellValue.it;
  15962. }
  15963. }
  15964. styles_1.push(InlineString);
  15965. });
  15966. var cellFormat = cellValue.ct;
  15967. if (cellFormat == null) {
  15968. cellFormat = new LuckyBase_1.LuckySheetCellFormat();
  15969. }
  15970. cellFormat.t = "inlineStr";
  15971. cellFormat.s = styles_1;
  15972. cellValue.ct = cellFormat;
  15973. }
  15974. } // else if(t==ST_CellType["InlineString"] && v!=null){
  15975. // }
  15976. else {
  15977. value = method_1.escapeCharacter(value);
  15978. cellValue.v = value;
  15979. }
  15980. }
  15981. if (quotePrefix != null) {
  15982. cellValue.qp = parseInt(quotePrefix);
  15983. }
  15984. return cellValue;
  15985. };
  15986. LuckySheetCelldata.prototype.replaceSpecialWrap = function (text) {
  15987. text = text.replace(/_x000D_/g, "").replace(/&#13;&#10;/g, "\r\n").replace(/&#13;/g, "\r").replace(/&#10;/g, "\n");
  15988. return text;
  15989. };
  15990. LuckySheetCelldata.prototype.getBackgroundByFill = function (fill, clrScheme) {
  15991. var patternFills = fill.getInnerElements("patternFill");
  15992. if (patternFills != null) {
  15993. var patternFill = patternFills[0];
  15994. var fgColors = patternFill.getInnerElements("fgColor");
  15995. var bgColors = patternFill.getInnerElements("bgColor");
  15996. var fg = void 0,
  15997. bg = void 0;
  15998. if (fgColors != null) {
  15999. var fgColor = fgColors[0];
  16000. fg = ReadXml_1.getColor(fgColor, this.styles);
  16001. }
  16002. if (bgColors != null) {
  16003. var bgColor = bgColors[0];
  16004. bg = ReadXml_1.getColor(bgColor, this.styles);
  16005. } // console.log(fgColors,bgColors,clrScheme);
  16006. if (fg != null) {
  16007. return fg;
  16008. } else if (bg != null) {
  16009. return bg;
  16010. }
  16011. } else {
  16012. var gradientfills = fill.getInnerElements("gradientFill");
  16013. if (gradientfills != null) {
  16014. //graient color fill handler
  16015. return null;
  16016. }
  16017. }
  16018. };
  16019. LuckySheetCelldata.prototype.getBorderInfo = function (borders) {
  16020. if (borders == null) {
  16021. return null;
  16022. }
  16023. var border = borders[0],
  16024. attrList = border.attributeList;
  16025. var clrScheme = this.styles["clrScheme"];
  16026. var style = attrList.style;
  16027. if (style == null || style == "none") {
  16028. return null;
  16029. }
  16030. var colors = border.getInnerElements("color");
  16031. var colorRet = "#000000";
  16032. if (colors != null) {
  16033. var color = colors[0];
  16034. colorRet = ReadXml_1.getColor(color, this.styles, "b");
  16035. if (colorRet == null) {
  16036. colorRet = "#000000";
  16037. }
  16038. }
  16039. var ret = new LuckyBase_1.LuckySheetborderInfoCellValueStyle();
  16040. ret.style = constant_1.borderTypes[style];
  16041. ret.color = colorRet;
  16042. return ret;
  16043. };
  16044. LuckySheetCelldata.prototype.htmlDecode = function (str) {
  16045. return str.replace(/&#(x)?([^&]{1,5});?/g, function ($, $1, $2) {
  16046. return String.fromCharCode(parseInt($2, $1 ? 16 : 10));
  16047. });
  16048. };
  16049. ;
  16050. return LuckySheetCelldata;
  16051. }(LuckyBase_1.LuckySheetCelldataBase);
  16052. exports.LuckySheetCelldata = LuckySheetCelldata;
  16053. }, { "../common/constant": 91, "../common/method": 93, "./LuckyBase": 85, "./ReadXml": 90 }], 87: [function (require, module, exports) {
  16054. "use strict";
  16055. var __extends = void 0 && (void 0).__extends || function () {
  16056. var _extendStatics = function extendStatics(d, b) {
  16057. _extendStatics = Object.setPrototypeOf || {
  16058. __proto__: []
  16059. } instanceof Array && function (d, b) {
  16060. d.__proto__ = b;
  16061. } || function (d, b) {
  16062. for (var p in b) {
  16063. if (b.hasOwnProperty(p)) d[p] = b[p];
  16064. }
  16065. };
  16066. return _extendStatics(d, b);
  16067. };
  16068. return function (d, b) {
  16069. _extendStatics(d, b);
  16070. function __() {
  16071. this.constructor = d;
  16072. }
  16073. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16074. };
  16075. }();
  16076. Object.defineProperty(exports, "__esModule", {
  16077. value: true
  16078. });
  16079. exports.LuckyFile = void 0;
  16080. var LuckySheet_1 = require("./LuckySheet");
  16081. var constant_1 = require("../common/constant");
  16082. var ReadXml_1 = require("./ReadXml");
  16083. var method_1 = require("../common/method");
  16084. var LuckyBase_1 = require("./LuckyBase");
  16085. var LuckyImage_1 = require("./LuckyImage");
  16086. var LuckyFile =
  16087. /** @class */
  16088. function (_super) {
  16089. __extends(LuckyFile, _super);
  16090. function LuckyFile(files, fileName) {
  16091. var _this = _super.call(this) || this;
  16092. _this.columnWidthSet = [];
  16093. _this.rowHeightSet = [];
  16094. _this.files = files;
  16095. _this.fileName = fileName;
  16096. _this.readXml = new ReadXml_1.ReadXml(files);
  16097. _this.getSheetNameList();
  16098. _this.sharedStrings = _this.readXml.getElementsByTagName("sst/si", constant_1.sharedStringsFile);
  16099. _this.calcChain = _this.readXml.getElementsByTagName("calcChain/c", constant_1.calcChainFile);
  16100. _this.styles = {};
  16101. _this.styles["cellXfs"] = _this.readXml.getElementsByTagName("cellXfs/xf", constant_1.stylesFile);
  16102. _this.styles["cellStyleXfs"] = _this.readXml.getElementsByTagName("cellStyleXfs/xf", constant_1.stylesFile);
  16103. _this.styles["cellStyles"] = _this.readXml.getElementsByTagName("cellStyles/cellStyle", constant_1.stylesFile);
  16104. _this.styles["fonts"] = _this.readXml.getElementsByTagName("fonts/font", constant_1.stylesFile);
  16105. _this.styles["fills"] = _this.readXml.getElementsByTagName("fills/fill", constant_1.stylesFile);
  16106. _this.styles["borders"] = _this.readXml.getElementsByTagName("borders/border", constant_1.stylesFile);
  16107. _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);
  16108. _this.styles["indexedColors"] = _this.readXml.getElementsByTagName("colors/indexedColors/rgbColor", constant_1.stylesFile);
  16109. _this.styles["mruColors"] = _this.readXml.getElementsByTagName("colors/mruColors/color", constant_1.stylesFile);
  16110. _this.imageList = new LuckyImage_1.ImageList(files);
  16111. var numfmts = _this.readXml.getElementsByTagName("numFmt/numFmt", constant_1.stylesFile);
  16112. var numFmtDefaultC = JSON.parse(JSON.stringify(constant_1.numFmtDefault));
  16113. for (var i = 0; i < numfmts.length; i++) {
  16114. var attrList = numfmts[i].attributeList;
  16115. var numfmtid = method_1.getXmlAttibute(attrList, "numFmtId", "49");
  16116. var formatcode = method_1.getXmlAttibute(attrList, "formatCode", "@"); // console.log(numfmtid, formatcode);
  16117. if (!(numfmtid in constant_1.numFmtDefault)) {
  16118. numFmtDefaultC[numfmtid] = formatcode;
  16119. }
  16120. } // console.log(JSON.stringify(numFmtDefaultC), numfmts);
  16121. _this.styles["numfmts"] = numFmtDefaultC;
  16122. return _this;
  16123. }
  16124. /**
  16125. * @return All sheet name of workbook
  16126. */
  16127. LuckyFile.prototype.getSheetNameList = function () {
  16128. var workbookRelList = this.readXml.getElementsByTagName("Relationships/Relationship", constant_1.workbookRels);
  16129. if (workbookRelList == null) {
  16130. return;
  16131. }
  16132. var regex = new RegExp("worksheets/[^/]*?.xml");
  16133. var sheetNames = {};
  16134. for (var i = 0; i < workbookRelList.length; i++) {
  16135. var rel = workbookRelList[i],
  16136. attrList = rel.attributeList;
  16137. var id = attrList["Id"],
  16138. target = attrList["Target"];
  16139. if (regex.test(target)) {
  16140. if (target.startsWith('/xl')) {
  16141. sheetNames[id] = target.substr(1);
  16142. } else {
  16143. sheetNames[id] = "xl/" + target;
  16144. }
  16145. }
  16146. }
  16147. this.sheetNameList = sheetNames;
  16148. };
  16149. /**
  16150. * @param sheetName WorkSheet'name
  16151. * @return sheet file name and path in zip
  16152. */
  16153. LuckyFile.prototype.getSheetFileBysheetId = function (sheetId) {
  16154. // for(let i=0;i<this.sheetNameList.length;i++){
  16155. // let sheetFileName = this.sheetNameList[i];
  16156. // if(sheetFileName.indexOf("sheet"+sheetId)>-1){
  16157. // return sheetFileName;
  16158. // }
  16159. // }
  16160. return this.sheetNameList[sheetId];
  16161. };
  16162. /**
  16163. * @return workBook information
  16164. */
  16165. LuckyFile.prototype.getWorkBookInfo = function () {
  16166. var Company = this.readXml.getElementsByTagName("Company", constant_1.appFile);
  16167. var AppVersion = this.readXml.getElementsByTagName("AppVersion", constant_1.appFile);
  16168. var creator = this.readXml.getElementsByTagName("dc:creator", constant_1.coreFile);
  16169. var lastModifiedBy = this.readXml.getElementsByTagName("cp:lastModifiedBy", constant_1.coreFile);
  16170. var created = this.readXml.getElementsByTagName("dcterms:created", constant_1.coreFile);
  16171. var modified = this.readXml.getElementsByTagName("dcterms:modified", constant_1.coreFile);
  16172. this.info = new LuckyBase_1.LuckyFileInfo();
  16173. this.info.name = this.fileName;
  16174. this.info.creator = creator.length > 0 ? creator[0].value : "";
  16175. this.info.lastmodifiedby = lastModifiedBy.length > 0 ? lastModifiedBy[0].value : "";
  16176. this.info.createdTime = created.length > 0 ? created[0].value : "";
  16177. this.info.modifiedTime = modified.length > 0 ? modified[0].value : "";
  16178. this.info.company = Company.length > 0 ? Company[0].value : "";
  16179. this.info.appversion = AppVersion.length > 0 ? AppVersion[0].value : "";
  16180. };
  16181. /**
  16182. * @return All sheet , include whole information
  16183. */
  16184. LuckyFile.prototype.getSheetsFull = function (isInitialCell) {
  16185. if (isInitialCell === void 0) {
  16186. isInitialCell = true;
  16187. }
  16188. var sheets = this.readXml.getElementsByTagName("sheets/sheet", constant_1.workBookFile);
  16189. var sheetList = {};
  16190. for (var key in sheets) {
  16191. var sheet = sheets[key];
  16192. sheetList[sheet.attributeList.name] = sheet.attributeList["sheetId"];
  16193. }
  16194. this.sheets = [];
  16195. var order = 0;
  16196. for (var key in sheets) {
  16197. var sheet = sheets[key];
  16198. var sheetName = sheet.attributeList.name;
  16199. var sheetId = sheet.attributeList["sheetId"];
  16200. var rid = sheet.attributeList["r:id"];
  16201. var sheetFile = this.getSheetFileBysheetId(rid);
  16202. var drawing = this.readXml.getElementsByTagName("worksheet/drawing", sheetFile),
  16203. drawingFile = void 0,
  16204. drawingRelsFile = void 0;
  16205. if (drawing != null && drawing.length > 0) {
  16206. var attrList = drawing[0].attributeList;
  16207. var rid_1 = method_1.getXmlAttibute(attrList, "r:id", null);
  16208. if (rid_1 != null) {
  16209. drawingFile = this.getDrawingFile(rid_1, sheetFile);
  16210. drawingRelsFile = this.getDrawingRelsFile(drawingFile);
  16211. }
  16212. }
  16213. if (sheetFile != null) {
  16214. var sheet_1 = new LuckySheet_1.LuckySheet(sheetName, sheetId, order, isInitialCell, {
  16215. sheetFile: sheetFile,
  16216. readXml: this.readXml,
  16217. sheetList: sheetList,
  16218. styles: this.styles,
  16219. sharedStrings: this.sharedStrings,
  16220. calcChain: this.calcChain,
  16221. imageList: this.imageList,
  16222. drawingFile: drawingFile,
  16223. drawingRelsFile: drawingRelsFile
  16224. });
  16225. this.columnWidthSet = [];
  16226. this.rowHeightSet = [];
  16227. this.imagePositionCaculation(sheet_1);
  16228. this.sheets.push(sheet_1);
  16229. order++;
  16230. }
  16231. }
  16232. };
  16233. LuckyFile.prototype.extendArray = function (index, sets, def, hidden, lens) {
  16234. if (index < sets.length) {
  16235. return;
  16236. }
  16237. var startIndex = sets.length,
  16238. endIndex = index;
  16239. var allGap = 0;
  16240. if (startIndex > 0) {
  16241. allGap = sets[startIndex - 1];
  16242. } // else{
  16243. // sets.push(0);
  16244. // }
  16245. for (var i = startIndex; i <= endIndex; i++) {
  16246. var gap = def,
  16247. istring = i.toString();
  16248. if (istring in hidden) {
  16249. gap = 0;
  16250. } else if (istring in lens) {
  16251. gap = lens[istring];
  16252. }
  16253. allGap += Math.round(gap + 1);
  16254. sets.push(allGap);
  16255. }
  16256. };
  16257. LuckyFile.prototype.imagePositionCaculation = function (sheet) {
  16258. var images = sheet.images,
  16259. defaultColWidth = sheet.defaultColWidth,
  16260. defaultRowHeight = sheet.defaultRowHeight;
  16261. var colhidden = {};
  16262. if (sheet.config.colhidden) {
  16263. colhidden = sheet.config.colhidden;
  16264. }
  16265. var columnlen = {};
  16266. if (sheet.config.columnlen) {
  16267. columnlen = sheet.config.columnlen;
  16268. }
  16269. var rowhidden = {};
  16270. if (sheet.config.rowhidden) {
  16271. rowhidden = sheet.config.rowhidden;
  16272. }
  16273. var rowlen = {};
  16274. if (sheet.config.rowlen) {
  16275. rowlen = sheet.config.rowlen;
  16276. }
  16277. for (var key in images) {
  16278. var imageObject = images[key]; //Image, luckyImage
  16279. var fromCol = imageObject.fromCol;
  16280. var fromColOff = imageObject.fromColOff;
  16281. var fromRow = imageObject.fromRow;
  16282. var fromRowOff = imageObject.fromRowOff;
  16283. var toCol = imageObject.toCol;
  16284. var toColOff = imageObject.toColOff;
  16285. var toRow = imageObject.toRow;
  16286. var toRowOff = imageObject.toRowOff;
  16287. var x_n = 0,
  16288. y_n = 0;
  16289. var cx_n = 0,
  16290. cy_n = 0;
  16291. if (fromCol >= this.columnWidthSet.length) {
  16292. this.extendArray(fromCol, this.columnWidthSet, defaultColWidth, colhidden, columnlen);
  16293. }
  16294. if (fromCol == 0) {
  16295. x_n = 0;
  16296. } else {
  16297. x_n = this.columnWidthSet[fromCol - 1];
  16298. }
  16299. x_n = x_n + fromColOff;
  16300. if (fromRow >= this.rowHeightSet.length) {
  16301. this.extendArray(fromRow, this.rowHeightSet, defaultRowHeight, rowhidden, rowlen);
  16302. }
  16303. if (fromRow == 0) {
  16304. y_n = 0;
  16305. } else {
  16306. y_n = this.rowHeightSet[fromRow - 1];
  16307. }
  16308. y_n = y_n + fromRowOff;
  16309. if (toCol >= this.columnWidthSet.length) {
  16310. this.extendArray(toCol, this.columnWidthSet, defaultColWidth, colhidden, columnlen);
  16311. }
  16312. if (toCol == 0) {
  16313. cx_n = 0;
  16314. } else {
  16315. cx_n = this.columnWidthSet[toCol - 1];
  16316. }
  16317. cx_n = cx_n + toColOff - x_n;
  16318. if (toRow >= this.rowHeightSet.length) {
  16319. this.extendArray(toRow, this.rowHeightSet, defaultRowHeight, rowhidden, rowlen);
  16320. }
  16321. if (toRow == 0) {
  16322. cy_n = 0;
  16323. } else {
  16324. cy_n = this.rowHeightSet[toRow - 1];
  16325. }
  16326. cy_n = cy_n + toRowOff - y_n;
  16327. console.log(defaultColWidth, colhidden, columnlen);
  16328. console.log(fromCol, this.columnWidthSet[fromCol], fromColOff);
  16329. console.log(toCol, this.columnWidthSet[toCol], toColOff, JSON.stringify(this.columnWidthSet));
  16330. imageObject.originWidth = cx_n;
  16331. imageObject.originHeight = cy_n;
  16332. imageObject.crop.height = cy_n;
  16333. imageObject.crop.width = cx_n;
  16334. imageObject["default"].height = cy_n;
  16335. imageObject["default"].left = x_n;
  16336. imageObject["default"].top = y_n;
  16337. imageObject["default"].width = cx_n;
  16338. }
  16339. };
  16340. /**
  16341. * @return drawing file string
  16342. */
  16343. LuckyFile.prototype.getDrawingFile = function (rid, sheetFile) {
  16344. var sheetRelsPath = "xl/worksheets/_rels/";
  16345. var sheetFileArr = sheetFile.split("/");
  16346. var sheetRelsName = sheetFileArr[sheetFileArr.length - 1];
  16347. var sheetRelsFile = sheetRelsPath + sheetRelsName + ".rels";
  16348. var drawing = this.readXml.getElementsByTagName("Relationships/Relationship", sheetRelsFile);
  16349. if (drawing.length > 0) {
  16350. for (var i = 0; i < drawing.length; i++) {
  16351. var relationship = drawing[i];
  16352. var attrList = relationship.attributeList;
  16353. var relationshipId = method_1.getXmlAttibute(attrList, "Id", null);
  16354. if (relationshipId == rid) {
  16355. var target = method_1.getXmlAttibute(attrList, "Target", null);
  16356. if (target != null) {
  16357. return target.replace(/\.\.\//g, "");
  16358. }
  16359. }
  16360. }
  16361. }
  16362. return null;
  16363. };
  16364. LuckyFile.prototype.getDrawingRelsFile = function (drawingFile) {
  16365. var drawingRelsPath = "xl/drawings/_rels/";
  16366. var drawingFileArr = drawingFile.split("/");
  16367. var drawingRelsName = drawingFileArr[drawingFileArr.length - 1];
  16368. var drawingRelsFile = drawingRelsPath + drawingRelsName + ".rels";
  16369. return drawingRelsFile;
  16370. };
  16371. /**
  16372. * @return All sheet base information widthout cell and config
  16373. */
  16374. LuckyFile.prototype.getSheetsWithoutCell = function () {
  16375. this.getSheetsFull(false);
  16376. };
  16377. /**
  16378. * @return LuckySheet file json
  16379. */
  16380. LuckyFile.prototype.Parse = function () {
  16381. // let xml = this.readXml;
  16382. // for(let key in this.sheetNameList){
  16383. // let sheetName=this.sheetNameList[key];
  16384. // let sheetColumns = xml.getElementsByTagName("row/c/f", sheetName);
  16385. // console.log(sheetColumns);
  16386. // }
  16387. // return "";
  16388. this.getWorkBookInfo();
  16389. this.getSheetsFull(); // for(let i=0;i<this.sheets.length;i++){
  16390. // let sheet = this.sheets[i];
  16391. // let _borderInfo = sheet.config._borderInfo;
  16392. // if(_borderInfo==null){
  16393. // continue;
  16394. // }
  16395. // let _borderInfoKeys = Object.keys(_borderInfo);
  16396. // _borderInfoKeys.sort();
  16397. // for(let a=0;a<_borderInfoKeys.length;a++){
  16398. // let key = parseInt(_borderInfoKeys[a]);
  16399. // let b = _borderInfo[key];
  16400. // if(b.cells.length==0){
  16401. // continue;
  16402. // }
  16403. // if(sheet.config.borderInfo==null){
  16404. // sheet.config.borderInfo = [];
  16405. // }
  16406. // sheet.config.borderInfo.push(b);
  16407. // }
  16408. // }
  16409. return this.toJsonString(this);
  16410. };
  16411. LuckyFile.prototype.toJsonString = function (file) {
  16412. var LuckyOutPutFile = new LuckyBase_1.LuckyFileBase();
  16413. LuckyOutPutFile.info = file.info;
  16414. LuckyOutPutFile.sheets = [];
  16415. file.sheets.forEach(function (sheet) {
  16416. 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"];
  16417. if (sheet.name != null) {
  16418. sheetout.name = sheet.name;
  16419. }
  16420. if (sheet.color != null) {
  16421. sheetout.color = sheet.color;
  16422. }
  16423. if (sheet.config != null) {
  16424. sheetout.config = sheet.config; // if(sheetout.config._borderInfo!=null){
  16425. // delete sheetout.config._borderInfo;
  16426. // }
  16427. }
  16428. if (sheet.index != null) {
  16429. sheetout.index = sheet.index;
  16430. }
  16431. if (sheet.status != null) {
  16432. sheetout.status = sheet.status;
  16433. }
  16434. if (sheet.order != null) {
  16435. sheetout.order = sheet.order;
  16436. }
  16437. if (sheet.row != null) {
  16438. sheetout.row = sheet.row;
  16439. }
  16440. if (sheet.column != null) {
  16441. sheetout.column = sheet.column;
  16442. }
  16443. if (sheet.luckysheet_select_save != null) {
  16444. sheetout.luckysheet_select_save = sheet.luckysheet_select_save;
  16445. }
  16446. if (sheet.scrollLeft != null) {
  16447. sheetout.scrollLeft = sheet.scrollLeft;
  16448. }
  16449. if (sheet.scrollTop != null) {
  16450. sheetout.scrollTop = sheet.scrollTop;
  16451. }
  16452. if (sheet.zoomRatio != null) {
  16453. sheetout.zoomRatio = sheet.zoomRatio;
  16454. }
  16455. if (sheet.showGridLines != null) {
  16456. sheetout.showGridLines = sheet.showGridLines;
  16457. }
  16458. if (sheet.defaultColWidth != null) {
  16459. sheetout.defaultColWidth = sheet.defaultColWidth;
  16460. }
  16461. if (sheet.defaultRowHeight != null) {
  16462. sheetout.defaultRowHeight = sheet.defaultRowHeight;
  16463. }
  16464. if (sheet.celldata != null) {
  16465. // sheetout.celldata = sheet.celldata;
  16466. sheetout.celldata = [];
  16467. sheet.celldata.forEach(function (cell) {
  16468. var cellout = new LuckyBase_1.LuckySheetCelldataBase();
  16469. cellout.r = cell.r;
  16470. cellout.c = cell.c;
  16471. cellout.v = cell.v;
  16472. sheetout.celldata.push(cellout);
  16473. });
  16474. }
  16475. if (sheet.chart != null) {
  16476. sheetout.chart = sheet.chart;
  16477. }
  16478. if (sheet.isPivotTable != null) {
  16479. sheetout.isPivotTable = sheet.isPivotTable;
  16480. }
  16481. if (sheet.pivotTable != null) {
  16482. sheetout.pivotTable = sheet.pivotTable;
  16483. }
  16484. if (sheet.luckysheet_conditionformat_save != null) {
  16485. sheetout.luckysheet_conditionformat_save = sheet.luckysheet_conditionformat_save;
  16486. }
  16487. if (sheet.freezen != null) {
  16488. sheetout.freezen = sheet.freezen;
  16489. }
  16490. if (sheet.calcChain != null) {
  16491. sheetout.calcChain = sheet.calcChain;
  16492. }
  16493. if (sheet.images != null) {
  16494. sheetout.images = sheet.images;
  16495. }
  16496. LuckyOutPutFile.sheets.push(sheetout);
  16497. });
  16498. return JSON.stringify(LuckyOutPutFile);
  16499. };
  16500. return LuckyFile;
  16501. }(LuckyBase_1.LuckyFileBase);
  16502. exports.LuckyFile = LuckyFile;
  16503. }, { "../common/constant": 91, "../common/method": 93, "./LuckyBase": 85, "./LuckyImage": 88, "./LuckySheet": 89, "./ReadXml": 90 }], 88: [function (require, module, exports) {
  16504. "use strict";
  16505. var __extends = void 0 && (void 0).__extends || function () {
  16506. var _extendStatics = function extendStatics(d, b) {
  16507. _extendStatics = Object.setPrototypeOf || {
  16508. __proto__: []
  16509. } instanceof Array && function (d, b) {
  16510. d.__proto__ = b;
  16511. } || function (d, b) {
  16512. for (var p in b) {
  16513. if (b.hasOwnProperty(p)) d[p] = b[p];
  16514. }
  16515. };
  16516. return _extendStatics(d, b);
  16517. };
  16518. return function (d, b) {
  16519. _extendStatics(d, b);
  16520. function __() {
  16521. this.constructor = d;
  16522. }
  16523. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16524. };
  16525. }();
  16526. Object.defineProperty(exports, "__esModule", {
  16527. value: true
  16528. });
  16529. exports.ImageList = void 0;
  16530. var LuckyBase_1 = require("./LuckyBase");
  16531. var emf_1 = require("../common/emf");
  16532. var ImageList =
  16533. /** @class */
  16534. function () {
  16535. function ImageList(files) {
  16536. if (files == null) {
  16537. return;
  16538. }
  16539. this.images = {};
  16540. for (var fileKey in files) {
  16541. // let reg = new RegExp("xl/media/image1.png", "g");
  16542. if (fileKey.indexOf("xl/media/") > -1) {
  16543. var fileNameArr = fileKey.split(".");
  16544. var suffix = fileNameArr[fileNameArr.length - 1].toLowerCase();
  16545. if (suffix in {
  16546. "png": 1,
  16547. "jpeg": 1,
  16548. "jpg": 1,
  16549. "gif": 1,
  16550. "bmp": 1,
  16551. "tif": 1,
  16552. "webp": 1,
  16553. "emf": 1
  16554. }) {
  16555. if (suffix == "emf") {
  16556. var pNum = 0; // number of the page, that you want to render
  16557. var scale = 1; // the scale of the document
  16558. var wrt = new emf_1.ToContext2D(pNum, scale);
  16559. var inp, out, stt;
  16560. emf_1.FromEMF.K = [];
  16561. inp = emf_1.FromEMF.C;
  16562. out = emf_1.FromEMF.K;
  16563. stt = 4;
  16564. for (var p in inp) {
  16565. out[inp[p]] = p.slice(stt);
  16566. }
  16567. emf_1.FromEMF.Parse(files[fileKey], wrt);
  16568. this.images[fileKey] = wrt.canvas.toDataURL("image/png");
  16569. } else {
  16570. this.images[fileKey] = files[fileKey];
  16571. }
  16572. }
  16573. }
  16574. }
  16575. }
  16576. ImageList.prototype.getImageByName = function (pathName) {
  16577. if (pathName in this.images) {
  16578. var base64 = this.images[pathName];
  16579. return new Image(pathName, base64);
  16580. }
  16581. return null;
  16582. };
  16583. return ImageList;
  16584. }();
  16585. exports.ImageList = ImageList;
  16586. var Image =
  16587. /** @class */
  16588. function (_super) {
  16589. __extends(Image, _super);
  16590. function Image(pathName, base64) {
  16591. var _this = _super.call(this) || this;
  16592. _this.src = base64;
  16593. return _this;
  16594. }
  16595. Image.prototype.setDefault = function () { };
  16596. return Image;
  16597. }(LuckyBase_1.LuckyImageBase);
  16598. }, { "../common/emf": 92, "./LuckyBase": 85 }], 89: [function (require, module, exports) {
  16599. "use strict";
  16600. var __extends = void 0 && (void 0).__extends || function () {
  16601. var _extendStatics = function extendStatics(d, b) {
  16602. _extendStatics = Object.setPrototypeOf || {
  16603. __proto__: []
  16604. } instanceof Array && function (d, b) {
  16605. d.__proto__ = b;
  16606. } || function (d, b) {
  16607. for (var p in b) {
  16608. if (b.hasOwnProperty(p)) d[p] = b[p];
  16609. }
  16610. };
  16611. return _extendStatics(d, b);
  16612. };
  16613. return function (d, b) {
  16614. _extendStatics(d, b);
  16615. function __() {
  16616. this.constructor = d;
  16617. }
  16618. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16619. };
  16620. }();
  16621. Object.defineProperty(exports, "__esModule", {
  16622. value: true
  16623. });
  16624. exports.LuckySheet = void 0;
  16625. var LuckyCell_1 = require("./LuckyCell");
  16626. var method_1 = require("../common/method");
  16627. var ReadXml_1 = require("./ReadXml");
  16628. var LuckyBase_1 = require("./LuckyBase");
  16629. var LuckySheet =
  16630. /** @class */
  16631. function (_super) {
  16632. __extends(LuckySheet, _super);
  16633. function LuckySheet(sheetName, sheetId, sheetOrder, isInitialCell, allFileOption) {
  16634. if (isInitialCell === void 0) {
  16635. isInitialCell = false;
  16636. }
  16637. var _this = //Private
  16638. _super.call(this) || this;
  16639. _this.isInitialCell = isInitialCell;
  16640. _this.readXml = allFileOption.readXml;
  16641. _this.sheetFile = allFileOption.sheetFile;
  16642. _this.styles = allFileOption.styles;
  16643. _this.sharedStrings = allFileOption.sharedStrings;
  16644. _this.calcChainEles = allFileOption.calcChain;
  16645. _this.sheetList = allFileOption.sheetList;
  16646. _this.imageList = allFileOption.imageList; //Output
  16647. _this.name = sheetName;
  16648. _this.index = sheetId;
  16649. _this.order = sheetOrder.toString();
  16650. _this.config = new LuckyBase_1.LuckyConfig();
  16651. _this.celldata = [];
  16652. _this.mergeCells = _this.readXml.getElementsByTagName("mergeCells/mergeCell", _this.sheetFile);
  16653. var clrScheme = _this.styles["clrScheme"];
  16654. var sheetView = _this.readXml.getElementsByTagName("sheetViews/sheetView", _this.sheetFile);
  16655. var showGridLines = "1",
  16656. tabSelected = "0",
  16657. zoomScale = "100",
  16658. activeCell = "A1";
  16659. if (sheetView.length > 0) {
  16660. var attrList = sheetView[0].attributeList;
  16661. showGridLines = method_1.getXmlAttibute(attrList, "showGridLines", "1");
  16662. tabSelected = method_1.getXmlAttibute(attrList, "tabSelected", "0");
  16663. zoomScale = method_1.getXmlAttibute(attrList, "zoomScale", "100"); // let colorId = getXmlAttibute(attrList, "colorId", "0");
  16664. var selections = sheetView[0].getInnerElements("selection");
  16665. if (selections != null && selections.length > 0) {
  16666. activeCell = method_1.getXmlAttibute(selections[0].attributeList, "activeCell", "A1");
  16667. var range = method_1.getcellrange(activeCell, _this.sheetList, sheetId);
  16668. _this.luckysheet_select_save = [];
  16669. _this.luckysheet_select_save.push(range);
  16670. }
  16671. }
  16672. _this.showGridLines = showGridLines;
  16673. _this.status = tabSelected;
  16674. _this.zoomRatio = parseInt(zoomScale) / 100;
  16675. var tabColors = _this.readXml.getElementsByTagName("sheetPr/tabColor", _this.sheetFile);
  16676. if (tabColors != null && tabColors.length > 0) {
  16677. var tabColor = tabColors[0],
  16678. attrList = tabColor.attributeList; // if(attrList.rgb!=null){
  16679. var tc = ReadXml_1.getColor(tabColor, _this.styles, "b");
  16680. _this.color = tc; // }
  16681. }
  16682. var sheetFormatPr = _this.readXml.getElementsByTagName("sheetFormatPr", _this.sheetFile);
  16683. var defaultColWidth, defaultRowHeight;
  16684. if (sheetFormatPr.length > 0) {
  16685. var attrList = sheetFormatPr[0].attributeList;
  16686. defaultColWidth = method_1.getXmlAttibute(attrList, "defaultColWidth", "9.21");
  16687. defaultRowHeight = method_1.getXmlAttibute(attrList, "defaultRowHeight", "19");
  16688. }
  16689. _this.defaultColWidth = method_1.getColumnWidthPixel(parseFloat(defaultColWidth));
  16690. _this.defaultRowHeight = method_1.getRowHeightPixel(parseFloat(defaultRowHeight));
  16691. _this.generateConfigColumnLenAndHidden();
  16692. var cellOtherInfo = _this.generateConfigRowLenAndHiddenAddCell();
  16693. if (_this.formulaRefList != null) {
  16694. for (var key in _this.formulaRefList) {
  16695. var funclist = _this.formulaRefList[key];
  16696. var mainFunc = funclist["mainRef"],
  16697. mainCellValue = mainFunc.cellValue;
  16698. var formulaTxt = mainFunc.fv;
  16699. var mainR = mainCellValue.r,
  16700. mainC = mainCellValue.c; // let refRange = getcellrange(ref);
  16701. for (var name_1 in funclist) {
  16702. if (name_1 == "mainRef") {
  16703. continue;
  16704. }
  16705. var funcValue = funclist[name_1],
  16706. cellValue = funcValue.cellValue;
  16707. if (cellValue == null) {
  16708. continue;
  16709. }
  16710. var r = cellValue.r,
  16711. c = cellValue.c;
  16712. var func = formulaTxt;
  16713. var offsetRow = r - mainR,
  16714. offsetCol = c - mainC;
  16715. if (offsetRow > 0) {
  16716. func = "=" + method_1.fromulaRef.functionCopy(func, "down", offsetRow);
  16717. } else if (offsetRow < 0) {
  16718. func = "=" + method_1.fromulaRef.functionCopy(func, "up", Math.abs(offsetRow));
  16719. }
  16720. if (offsetCol > 0) {
  16721. func = "=" + method_1.fromulaRef.functionCopy(func, "right", offsetCol);
  16722. } else if (offsetCol < 0) {
  16723. func = "=" + method_1.fromulaRef.functionCopy(func, "left", Math.abs(offsetCol));
  16724. } // console.log(offsetRow, offsetCol, func);
  16725. cellValue.v.f = func;
  16726. }
  16727. }
  16728. }
  16729. if (_this.calcChain == null) {
  16730. _this.calcChain = [];
  16731. }
  16732. var formulaListExist = {};
  16733. for (var c = 0; c < _this.calcChainEles.length; c++) {
  16734. var calcChainEle = _this.calcChainEles[c],
  16735. attrList = calcChainEle.attributeList;
  16736. if (attrList.i != sheetId) {
  16737. continue;
  16738. }
  16739. var r = attrList.r,
  16740. i = attrList.i,
  16741. l = attrList.l,
  16742. s = attrList.s,
  16743. a = attrList.a,
  16744. t = attrList.t;
  16745. var range = method_1.getcellrange(r);
  16746. var chain = new LuckyBase_1.LuckysheetCalcChain();
  16747. chain.r = range.row[0];
  16748. chain.c = range.column[0];
  16749. chain.index = _this.index;
  16750. _this.calcChain.push(chain);
  16751. formulaListExist["r" + r + "c" + c] = null;
  16752. } //There may be formulas that do not appear in calcChain
  16753. for (var key in cellOtherInfo.formulaList) {
  16754. if (!(key in formulaListExist)) {
  16755. var formulaListItem = cellOtherInfo.formulaList[key];
  16756. var chain = new LuckyBase_1.LuckysheetCalcChain();
  16757. chain.r = formulaListItem.r;
  16758. chain.c = formulaListItem.c;
  16759. chain.index = _this.index;
  16760. _this.calcChain.push(chain);
  16761. }
  16762. }
  16763. if (_this.mergeCells != null) {
  16764. for (var i = 0; i < _this.mergeCells.length; i++) {
  16765. var merge = _this.mergeCells[i],
  16766. attrList = merge.attributeList;
  16767. var ref = attrList.ref;
  16768. if (ref == null) {
  16769. continue;
  16770. }
  16771. var range = method_1.getcellrange(ref, _this.sheetList, sheetId);
  16772. var mergeValue = new LuckyBase_1.LuckySheetConfigMerge();
  16773. mergeValue.r = range.row[0];
  16774. mergeValue.c = range.column[0];
  16775. mergeValue.rs = range.row[1] - range.row[0] + 1;
  16776. mergeValue.cs = range.column[1] - range.column[0] + 1;
  16777. if (_this.config.merge == null) {
  16778. _this.config.merge = {};
  16779. }
  16780. _this.config.merge[range.row[0] + "_" + range.column[0]] = mergeValue;
  16781. }
  16782. }
  16783. var drawingFile = allFileOption.drawingFile,
  16784. drawingRelsFile = allFileOption.drawingRelsFile;
  16785. if (drawingFile != null && drawingRelsFile != null) {
  16786. var twoCellAnchors = _this.readXml.getElementsByTagName("xdr:twoCellAnchor", drawingFile);
  16787. if (twoCellAnchors != null && twoCellAnchors.length > 0) {
  16788. for (var i = 0; i < twoCellAnchors.length; i++) {
  16789. var twoCellAnchor = twoCellAnchors[i];
  16790. var editAs = method_1.getXmlAttibute(twoCellAnchor.attributeList, "editAs", "twoCell");
  16791. var xdrFroms = twoCellAnchor.getInnerElements("xdr:from"),
  16792. xdrTos = twoCellAnchor.getInnerElements("xdr:to");
  16793. var xdr_blipfills = twoCellAnchor.getInnerElements("a:blip");
  16794. if (xdrFroms != null && xdr_blipfills != null && xdrFroms.length > 0 && xdr_blipfills.length > 0) {
  16795. var xdrFrom = xdrFroms[0],
  16796. xdrTo = xdrTos[0],
  16797. xdr_blipfill = xdr_blipfills[0];
  16798. var rembed = method_1.getXmlAttibute(xdr_blipfill.attributeList, "r:embed", null);
  16799. var imageObject = _this.getBase64ByRid(rembed, drawingRelsFile); // let aoff = xdr_xfrm.getInnerElements("a:off"), aext = xdr_xfrm.getInnerElements("a:ext");
  16800. // if(aoff!=null && aext!=null && aoff.length>0 && aext.length>0){
  16801. // let aoffAttribute = aoff[0].attributeList, aextAttribute = aext[0].attributeList;
  16802. // let x = getXmlAttibute(aoffAttribute, "x", null);
  16803. // let y = getXmlAttibute(aoffAttribute, "y", null);
  16804. // let cx = getXmlAttibute(aextAttribute, "cx", null);
  16805. // let cy = getXmlAttibute(aextAttribute, "cy", null);
  16806. // if(x!=null && y!=null && cx!=null && cy!=null && imageObject !=null){
  16807. // let x_n = getPxByEMUs(parseInt(x), "c"),y_n = getPxByEMUs(parseInt(y));
  16808. // let cx_n = getPxByEMUs(parseInt(cx), "c"),cy_n = getPxByEMUs(parseInt(cy));
  16809. var x_n = 0,
  16810. y_n = 0;
  16811. var cx_n = 0,
  16812. cy_n = 0;
  16813. imageObject.fromCol = _this.getXdrValue(xdrFrom.getInnerElements("xdr:col"));
  16814. imageObject.fromColOff = method_1.getPxByEMUs(_this.getXdrValue(xdrFrom.getInnerElements("xdr:colOff")));
  16815. imageObject.fromRow = _this.getXdrValue(xdrFrom.getInnerElements("xdr:row"));
  16816. imageObject.fromRowOff = method_1.getPxByEMUs(_this.getXdrValue(xdrFrom.getInnerElements("xdr:rowOff")));
  16817. imageObject.toCol = _this.getXdrValue(xdrTo.getInnerElements("xdr:col"));
  16818. imageObject.toColOff = method_1.getPxByEMUs(_this.getXdrValue(xdrTo.getInnerElements("xdr:colOff")));
  16819. imageObject.toRow = _this.getXdrValue(xdrTo.getInnerElements("xdr:row"));
  16820. imageObject.toRowOff = method_1.getPxByEMUs(_this.getXdrValue(xdrTo.getInnerElements("xdr:rowOff")));
  16821. imageObject.originWidth = cx_n;
  16822. imageObject.originHeight = cy_n;
  16823. if (editAs == "absolute") {
  16824. imageObject.type = "3";
  16825. } else if (editAs == "oneCell") {
  16826. imageObject.type = "2";
  16827. } else {
  16828. imageObject.type = "1";
  16829. }
  16830. imageObject.isFixedPos = false;
  16831. imageObject.fixedLeft = 0;
  16832. imageObject.fixedTop = 0;
  16833. var imageBorder = {
  16834. color: "#000",
  16835. radius: 0,
  16836. style: "solid",
  16837. width: 0
  16838. };
  16839. imageObject.border = imageBorder;
  16840. var imageCrop = {
  16841. height: cy_n,
  16842. offsetLeft: 0,
  16843. offsetTop: 0,
  16844. width: cx_n
  16845. };
  16846. imageObject.crop = imageCrop;
  16847. var imageDefault = {
  16848. height: cy_n,
  16849. left: x_n,
  16850. top: y_n,
  16851. width: cx_n
  16852. };
  16853. imageObject["default"] = imageDefault;
  16854. if (_this.images == null) {
  16855. _this.images = {};
  16856. }
  16857. _this.images[method_1.generateRandomIndex("image")] = imageObject; // }
  16858. // }
  16859. }
  16860. }
  16861. }
  16862. }
  16863. return _this;
  16864. }
  16865. LuckySheet.prototype.getXdrValue = function (ele) {
  16866. if (ele == null || ele.length == 0) {
  16867. return null;
  16868. }
  16869. return parseInt(ele[0].value);
  16870. };
  16871. LuckySheet.prototype.getBase64ByRid = function (rid, drawingRelsFile) {
  16872. var Relationships = this.readXml.getElementsByTagName("Relationships/Relationship", drawingRelsFile);
  16873. if (Relationships != null && Relationships.length > 0) {
  16874. for (var i = 0; i < Relationships.length; i++) {
  16875. var Relationship = Relationships[i];
  16876. var attrList = Relationship.attributeList;
  16877. var Id = method_1.getXmlAttibute(attrList, "Id", null);
  16878. var src = method_1.getXmlAttibute(attrList, "Target", null);
  16879. if (Id == rid) {
  16880. src = src.replace(/\.\.\//g, "");
  16881. src = "xl/" + src;
  16882. var imgage = this.imageList.getImageByName(src);
  16883. return imgage;
  16884. }
  16885. }
  16886. }
  16887. return null;
  16888. };
  16889. /**
  16890. * @desc This will convert cols/col to luckysheet config of column'width
  16891. */
  16892. LuckySheet.prototype.generateConfigColumnLenAndHidden = function () {
  16893. var cols = this.readXml.getElementsByTagName("cols/col", this.sheetFile);
  16894. for (var i = 0; i < cols.length; i++) {
  16895. var col = cols[i],
  16896. attrList = col.attributeList;
  16897. var min = method_1.getXmlAttibute(attrList, "min", null);
  16898. var max = method_1.getXmlAttibute(attrList, "max", null);
  16899. var width = method_1.getXmlAttibute(attrList, "width", null);
  16900. var hidden = method_1.getXmlAttibute(attrList, "hidden", null);
  16901. var customWidth = method_1.getXmlAttibute(attrList, "customWidth", null);
  16902. if (min == null || max == null) {
  16903. continue;
  16904. }
  16905. var minNum = parseInt(min) - 1,
  16906. maxNum = parseInt(max) - 1,
  16907. widthNum = parseFloat(width);
  16908. for (var m = minNum; m <= maxNum; m++) {
  16909. if (width != null) {
  16910. if (this.config.columnlen == null) {
  16911. this.config.columnlen = {};
  16912. }
  16913. this.config.columnlen[m] = method_1.getColumnWidthPixel(widthNum);
  16914. }
  16915. if (hidden == "1") {
  16916. if (this.config.colhidden == null) {
  16917. this.config.colhidden = {};
  16918. }
  16919. this.config.colhidden[m] = 0;
  16920. if (this.config.columnlen) {
  16921. delete this.config.columnlen[m];
  16922. }
  16923. }
  16924. if (customWidth != null) {
  16925. if (this.config.customWidth == null) {
  16926. this.config.customWidth = {};
  16927. }
  16928. this.config.customWidth[m] = 1;
  16929. }
  16930. }
  16931. }
  16932. };
  16933. /**
  16934. * @desc This will convert cols/col to luckysheet config of column'width
  16935. */
  16936. LuckySheet.prototype.generateConfigRowLenAndHiddenAddCell = function () {
  16937. var rows = this.readXml.getElementsByTagName("sheetData/row", this.sheetFile);
  16938. var cellOtherInfo = {};
  16939. var formulaList = {};
  16940. cellOtherInfo.formulaList = formulaList;
  16941. for (var i = 0; i < rows.length; i++) {
  16942. var row = rows[i],
  16943. attrList = row.attributeList;
  16944. var rowNo = method_1.getXmlAttibute(attrList, "r", null);
  16945. var height = method_1.getXmlAttibute(attrList, "ht", null);
  16946. var hidden = method_1.getXmlAttibute(attrList, "hidden", null);
  16947. var customHeight = method_1.getXmlAttibute(attrList, "customHeight", null);
  16948. if (rowNo == null) {
  16949. continue;
  16950. }
  16951. var rowNoNum = parseInt(rowNo) - 1;
  16952. if (height != null) {
  16953. var heightNum = parseFloat(height);
  16954. if (this.config.rowlen == null) {
  16955. this.config.rowlen = {};
  16956. }
  16957. this.config.rowlen[rowNoNum] = method_1.getRowHeightPixel(heightNum);
  16958. }
  16959. if (hidden == "1") {
  16960. if (this.config.rowhidden == null) {
  16961. this.config.rowhidden = {};
  16962. }
  16963. this.config.rowhidden[rowNoNum] = 0;
  16964. if (this.config.rowlen) {
  16965. delete this.config.rowlen[rowNoNum];
  16966. }
  16967. }
  16968. if (customHeight != null) {
  16969. if (this.config.customHeight == null) {
  16970. this.config.customHeight = {};
  16971. }
  16972. this.config.customHeight[rowNoNum] = 1;
  16973. }
  16974. if (this.isInitialCell) {
  16975. var cells = row.getInnerElements("c");
  16976. for (var key in cells) {
  16977. var cell = cells[key];
  16978. var cellValue = new LuckyCell_1.LuckySheetCelldata(cell, this.styles, this.sharedStrings, this.mergeCells, this.sheetFile, this.readXml);
  16979. if (cellValue._borderObject != null) {
  16980. if (this.config.borderInfo == null) {
  16981. this.config.borderInfo = [];
  16982. }
  16983. this.config.borderInfo.push(cellValue._borderObject);
  16984. delete cellValue._borderObject;
  16985. } // let borderId = cellValue._borderId;
  16986. // if(borderId!=null){
  16987. // let borders = this.styles["borders"] as Element[];
  16988. // if(this.config._borderInfo==null){
  16989. // this.config._borderInfo = {};
  16990. // }
  16991. // if( borderId in this.config._borderInfo){
  16992. // this.config._borderInfo[borderId].cells.push(cellValue.r + "_" + cellValue.c);
  16993. // }
  16994. // else{
  16995. // let border = borders[borderId];
  16996. // let borderObject = new LuckySheetborderInfoCellForImp();
  16997. // borderObject.rangeType = "cellGroup";
  16998. // borderObject.cells = [];
  16999. // let borderCellValue = new LuckySheetborderInfoCellValue();
  17000. // let lefts = border.getInnerElements("left");
  17001. // let rights = border.getInnerElements("right");
  17002. // let tops = border.getInnerElements("top");
  17003. // let bottoms = border.getInnerElements("bottom");
  17004. // let diagonals = border.getInnerElements("diagonal");
  17005. // let left = this.getBorderInfo(lefts);
  17006. // let right = this.getBorderInfo(rights);
  17007. // let top = this.getBorderInfo(tops);
  17008. // let bottom = this.getBorderInfo(bottoms);
  17009. // let diagonal = this.getBorderInfo(diagonals);
  17010. // let isAdd = false;
  17011. // if(left!=null && left.color!=null){
  17012. // borderCellValue.l = left;
  17013. // isAdd = true;
  17014. // }
  17015. // if(right!=null && right.color!=null){
  17016. // borderCellValue.r = right;
  17017. // isAdd = true;
  17018. // }
  17019. // if(top!=null && top.color!=null){
  17020. // borderCellValue.t = top;
  17021. // isAdd = true;
  17022. // }
  17023. // if(bottom!=null && bottom.color!=null){
  17024. // borderCellValue.b = bottom;
  17025. // isAdd = true;
  17026. // }
  17027. // if(isAdd){
  17028. // borderObject.value = borderCellValue;
  17029. // this.config._borderInfo[borderId] = borderObject;
  17030. // }
  17031. // }
  17032. // }
  17033. if (cellValue._formulaType == "shared") {
  17034. if (this.formulaRefList == null) {
  17035. this.formulaRefList = {};
  17036. }
  17037. if (this.formulaRefList[cellValue._formulaSi] == null) {
  17038. this.formulaRefList[cellValue._formulaSi] = {};
  17039. }
  17040. var fv = void 0;
  17041. if (cellValue.v != null) {
  17042. fv = cellValue.v.f;
  17043. }
  17044. var refValue = {
  17045. t: cellValue._formulaType,
  17046. ref: cellValue._fomulaRef,
  17047. si: cellValue._formulaSi,
  17048. fv: fv,
  17049. cellValue: cellValue
  17050. };
  17051. if (cellValue._fomulaRef != null) {
  17052. this.formulaRefList[cellValue._formulaSi]["mainRef"] = refValue;
  17053. } else {
  17054. this.formulaRefList[cellValue._formulaSi][cellValue.r + "_" + cellValue.c] = refValue;
  17055. } // console.log(refValue, this.formulaRefList);
  17056. } //There may be formulas that do not appear in calcChain
  17057. if (cellValue.v != null && cellValue.v.f != null) {
  17058. var formulaCell = {
  17059. r: cellValue.r,
  17060. c: cellValue.c
  17061. };
  17062. cellOtherInfo.formulaList["r" + cellValue.r + "c" + cellValue.c] = formulaCell;
  17063. }
  17064. this.celldata.push(cellValue);
  17065. }
  17066. }
  17067. }
  17068. return cellOtherInfo;
  17069. };
  17070. return LuckySheet;
  17071. }(LuckyBase_1.LuckySheetBase);
  17072. exports.LuckySheet = LuckySheet;
  17073. }, { "../common/method": 93, "./LuckyBase": 85, "./LuckyCell": 86, "./ReadXml": 90 }], 90: [function (require, module, exports) {
  17074. "use strict";
  17075. var __extends = void 0 && (void 0).__extends || function () {
  17076. var _extendStatics = function extendStatics(d, b) {
  17077. _extendStatics = Object.setPrototypeOf || {
  17078. __proto__: []
  17079. } instanceof Array && function (d, b) {
  17080. d.__proto__ = b;
  17081. } || function (d, b) {
  17082. for (var p in b) {
  17083. if (b.hasOwnProperty(p)) d[p] = b[p];
  17084. }
  17085. };
  17086. return _extendStatics(d, b);
  17087. };
  17088. return function (d, b) {
  17089. _extendStatics(d, b);
  17090. function __() {
  17091. this.constructor = d;
  17092. }
  17093. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17094. };
  17095. }();
  17096. Object.defineProperty(exports, "__esModule", {
  17097. value: true
  17098. });
  17099. exports.getlineStringAttr = exports.getColor = exports.Element = exports.ReadXml = void 0;
  17100. var constant_1 = require("../common/constant");
  17101. var method_1 = require("../common/method");
  17102. var xmloperation =
  17103. /** @class */
  17104. function () {
  17105. function xmloperation() { }
  17106. /**
  17107. * @param tag Search xml tag name , div,title etc.
  17108. * @param file Xml string
  17109. * @return Xml element string
  17110. */
  17111. xmloperation.prototype.getElementsByOneTag = function (tag, file) {
  17112. //<a:[^/>: ]+?>.*?</a:[^/>: ]+?>
  17113. var readTagReg;
  17114. if (tag.indexOf("|") > -1) {
  17115. var tags = tag.split("|"),
  17116. tagsRegTxt = "";
  17117. for (var i = 0; i < tags.length; i++) {
  17118. var t = tags[i];
  17119. tagsRegTxt += "|<" + t + " [^>]+?[^/]>[\\s\\S]*?</" + t + ">|<" + t + " [^>]+?/>|<" + t + ">[\\s\\S]*?</" + t + ">|<" + t + "/>";
  17120. }
  17121. tagsRegTxt = tagsRegTxt.substr(1, tagsRegTxt.length);
  17122. readTagReg = new RegExp(tagsRegTxt, "g");
  17123. } else {
  17124. readTagReg = new RegExp("<" + tag + " [^>]+?[^/]>[\\s\\S]*?</" + tag + ">|<" + tag + " [^>]+?/>|<" + tag + ">[\\s\\S]*?</" + tag + ">|<" + tag + "/>", "g");
  17125. }
  17126. var ret = file.match(readTagReg);
  17127. if (ret == null) {
  17128. return [];
  17129. } else {
  17130. return ret;
  17131. }
  17132. };
  17133. return xmloperation;
  17134. }();
  17135. var ReadXml =
  17136. /** @class */
  17137. function (_super) {
  17138. __extends(ReadXml, _super);
  17139. function ReadXml(files) {
  17140. var _this = _super.call(this) || this;
  17141. _this.originFile = files;
  17142. return _this;
  17143. }
  17144. /**
  17145. * @param path Search xml tag group , div,title etc.
  17146. * @param fileName One of uploadfileList, uploadfileList is file group, {key:value}
  17147. * @return Xml element calss
  17148. */
  17149. ReadXml.prototype.getElementsByTagName = function (path, fileName) {
  17150. var file = this.getFileByName(fileName);
  17151. var pathArr = path.split("/"),
  17152. ret;
  17153. for (var key in pathArr) {
  17154. var path_1 = pathArr[key];
  17155. if (ret == undefined) {
  17156. ret = this.getElementsByOneTag(path_1, file);
  17157. } else {
  17158. if (ret instanceof Array) {
  17159. var items = [];
  17160. for (var key_1 in ret) {
  17161. var item = ret[key_1];
  17162. items = items.concat(this.getElementsByOneTag(path_1, item));
  17163. }
  17164. ret = items;
  17165. } else {
  17166. ret = this.getElementsByOneTag(path_1, ret);
  17167. }
  17168. }
  17169. }
  17170. var elements = [];
  17171. for (var i = 0; i < ret.length; i++) {
  17172. var ele = new Element(ret[i]);
  17173. elements.push(ele);
  17174. }
  17175. return elements;
  17176. };
  17177. /**
  17178. * @param name One of uploadfileList's name, search for file by this parameter
  17179. * @retrun Select a file from uploadfileList
  17180. */
  17181. ReadXml.prototype.getFileByName = function (name) {
  17182. for (var fileKey in this.originFile) {
  17183. if (fileKey.indexOf(name) > -1) {
  17184. return this.originFile[fileKey];
  17185. }
  17186. }
  17187. return "";
  17188. };
  17189. return ReadXml;
  17190. }(xmloperation);
  17191. exports.ReadXml = ReadXml;
  17192. var Element =
  17193. /** @class */
  17194. function (_super) {
  17195. __extends(Element, _super);
  17196. function Element(str) {
  17197. var _this = _super.call(this) || this;
  17198. _this.elementString = str;
  17199. _this.setValue();
  17200. var readAttrReg = new RegExp('[a-zA-Z0-9_:]*?=".*?"', "g");
  17201. var attrList = _this.container.match(readAttrReg);
  17202. _this.attributeList = {};
  17203. if (attrList != null) {
  17204. for (var key in attrList) {
  17205. var attrFull = attrList[key]; // let al= attrFull.split("=");
  17206. if (attrFull.length == 0) {
  17207. continue;
  17208. }
  17209. var attrKey = attrFull.substr(0, attrFull.indexOf('='));
  17210. var attrValue = attrFull.substr(attrFull.indexOf('=') + 1);
  17211. if (attrKey == null || attrValue == null || attrKey.length == 0 || attrValue.length == 0) {
  17212. continue;
  17213. }
  17214. _this.attributeList[attrKey] = attrValue.substr(1, attrValue.length - 2);
  17215. }
  17216. }
  17217. return _this;
  17218. }
  17219. /**
  17220. * @param name Get attribute by key in element
  17221. * @return Single attribute
  17222. */
  17223. Element.prototype.get = function (name) {
  17224. return this.attributeList[name];
  17225. };
  17226. /**
  17227. * @param tag Get elements by tag in elementString
  17228. * @return Element group
  17229. */
  17230. Element.prototype.getInnerElements = function (tag) {
  17231. var ret = this.getElementsByOneTag(tag, this.elementString);
  17232. var elements = [];
  17233. for (var i = 0; i < ret.length; i++) {
  17234. var ele = new Element(ret[i]);
  17235. elements.push(ele);
  17236. }
  17237. if (elements.length == 0) {
  17238. return null;
  17239. }
  17240. return elements;
  17241. };
  17242. /**
  17243. * @desc get xml dom value and container, <container>value</container>
  17244. */
  17245. Element.prototype.setValue = function () {
  17246. var str = this.elementString;
  17247. if (str.substr(str.length - 2, 2) == "/>") {
  17248. this.value = "";
  17249. this.container = str;
  17250. } else {
  17251. var firstTag = this.getFirstTag();
  17252. var firstTagReg = new RegExp("(<" + firstTag + " [^>]+?[^/]>)([\\s\\S]*?)</" + firstTag + ">|(<" + firstTag + ">)([\\s\\S]*?)</" + firstTag + ">", "g");
  17253. var result = firstTagReg.exec(str);
  17254. if (result != null) {
  17255. if (result[1] != null) {
  17256. this.container = result[1];
  17257. this.value = result[2];
  17258. } else {
  17259. this.container = result[3];
  17260. this.value = result[4];
  17261. }
  17262. }
  17263. }
  17264. };
  17265. /**
  17266. * @desc get xml dom first tag, <a><b></b></a>, get a
  17267. */
  17268. Element.prototype.getFirstTag = function () {
  17269. var str = this.elementString;
  17270. var firstTag = str.substr(0, str.indexOf(' '));
  17271. if (firstTag == "" || firstTag.indexOf(">") > -1) {
  17272. firstTag = str.substr(0, str.indexOf('>'));
  17273. }
  17274. firstTag = firstTag.substr(1, firstTag.length);
  17275. return firstTag;
  17276. };
  17277. return Element;
  17278. }(xmloperation);
  17279. exports.Element = Element;
  17280. function combineIndexedColor(indexedColorsInner, indexedColors) {
  17281. var ret = {};
  17282. if (indexedColorsInner == null || indexedColorsInner.length == 0) {
  17283. return indexedColors;
  17284. }
  17285. for (var key in indexedColors) {
  17286. var value = indexedColors[key],
  17287. kn = parseInt(key);
  17288. var inner = indexedColorsInner[kn];
  17289. if (inner == null) {
  17290. ret[key] = value;
  17291. } else {
  17292. var rgb = inner.attributeList.rgb;
  17293. ret[key] = rgb;
  17294. }
  17295. }
  17296. return ret;
  17297. } //clrScheme:Element[]
  17298. function getColor(color, styles, type) {
  17299. if (type === void 0) {
  17300. type = "g";
  17301. }
  17302. var attrList = color.attributeList;
  17303. var clrScheme = styles["clrScheme"];
  17304. var indexedColorsInner = styles["indexedColors"];
  17305. var mruColorsInner = styles["mruColors"];
  17306. var indexedColorsList = combineIndexedColor(indexedColorsInner, constant_1.indexedColors);
  17307. var indexed = attrList.indexed,
  17308. rgb = attrList.rgb,
  17309. theme = attrList.theme,
  17310. tint = attrList.tint;
  17311. var bg;
  17312. if (indexed != null) {
  17313. var indexedNum = parseInt(indexed);
  17314. bg = indexedColorsList[indexedNum];
  17315. if (bg != null) {
  17316. bg = bg.substring(bg.length - 6, bg.length);
  17317. bg = "#" + bg;
  17318. }
  17319. } else if (rgb != null) {
  17320. rgb = rgb.substring(rgb.length - 6, rgb.length);
  17321. bg = "#" + rgb;
  17322. } else if (theme != null) {
  17323. var themeNum = parseInt(theme);
  17324. if (themeNum == 0) {
  17325. themeNum = 1;
  17326. } else if (themeNum == 1) {
  17327. themeNum = 0;
  17328. } else if (themeNum == 2) {
  17329. themeNum = 3;
  17330. } else if (themeNum == 3) {
  17331. themeNum = 2;
  17332. }
  17333. var clrSchemeElement = clrScheme[themeNum];
  17334. if (clrSchemeElement != null) {
  17335. var clrs = clrSchemeElement.getInnerElements("a:sysClr|a:srgbClr");
  17336. if (clrs != null) {
  17337. var clr = clrs[0];
  17338. var clrAttrList = clr.attributeList; // console.log(clr.container, );
  17339. if (clr.container.indexOf("sysClr") > -1) {
  17340. // if(type=="g" && clrAttrList.val=="windowText"){
  17341. // bg = null;
  17342. // }
  17343. // else if((type=="t" || type=="b") && clrAttrList.val=="window"){
  17344. // bg = null;
  17345. // }
  17346. // else
  17347. if (clrAttrList.lastClr != null) {
  17348. bg = "#" + clrAttrList.lastClr;
  17349. } else if (clrAttrList.val != null) {
  17350. bg = "#" + clrAttrList.val;
  17351. }
  17352. } else if (clr.container.indexOf("srgbClr") > -1) {
  17353. // console.log(clrAttrList.val);
  17354. bg = "#" + clrAttrList.val;
  17355. }
  17356. }
  17357. }
  17358. }
  17359. if (tint != null) {
  17360. var tintNum = parseFloat(tint);
  17361. if (bg != null) {
  17362. bg = method_1.LightenDarkenColor(bg, tintNum);
  17363. }
  17364. }
  17365. return bg;
  17366. }
  17367. exports.getColor = getColor;
  17368. /**
  17369. * @dom xml attribute object
  17370. * @attr attribute name
  17371. * @d if attribute is null, return default value
  17372. * @return attribute value
  17373. */
  17374. function getlineStringAttr(frpr, attr) {
  17375. var attrEle = frpr.getInnerElements(attr),
  17376. value;
  17377. if (attrEle != null && attrEle.length > 0) {
  17378. if (attr == "b" || attr == "i" || attr == "strike") {
  17379. value = "1";
  17380. } else if (attr == "u") {
  17381. var v = attrEle[0].attributeList.val;
  17382. if (v == "double") {
  17383. value = "2";
  17384. } else if (v == "singleAccounting") {
  17385. value = "3";
  17386. } else if (v == "doubleAccounting") {
  17387. value = "4";
  17388. } else {
  17389. value = "1";
  17390. }
  17391. } else if (attr == "vertAlign") {
  17392. var v = attrEle[0].attributeList.val;
  17393. if (v == "subscript") {
  17394. value = "1";
  17395. } else if (v == "superscript") {
  17396. value = "2";
  17397. }
  17398. } else {
  17399. value = attrEle[0].attributeList.val;
  17400. }
  17401. }
  17402. return value;
  17403. }
  17404. exports.getlineStringAttr = getlineStringAttr;
  17405. }, { "../common/constant": 91, "../common/method": 93 }], 91: [function (require, module, exports) {
  17406. "use strict";
  17407. Object.defineProperty(exports, "__esModule", {
  17408. value: true
  17409. });
  17410. exports.fontFamilys = 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;
  17411. 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'];
  17412. exports.columeHeader_word_index = {
  17413. 'A': 0,
  17414. 'B': 1,
  17415. 'C': 2,
  17416. 'D': 3,
  17417. 'E': 4,
  17418. 'F': 5,
  17419. 'G': 6,
  17420. 'H': 7,
  17421. 'I': 8,
  17422. 'J': 9,
  17423. 'K': 10,
  17424. 'L': 11,
  17425. 'M': 12,
  17426. 'N': 13,
  17427. 'O': 14,
  17428. 'P': 15,
  17429. 'Q': 16,
  17430. 'R': 17,
  17431. 'S': 18,
  17432. 'T': 19,
  17433. 'U': 20,
  17434. 'V': 21,
  17435. 'W': 22,
  17436. 'X': 23,
  17437. 'Y': 24,
  17438. 'Z': 25
  17439. };
  17440. exports.coreFile = "docProps/core.xml";
  17441. exports.appFile = "docProps/app.xml";
  17442. exports.contentTypesFile = "[Content_Types].xml";
  17443. exports.workBookFile = "xl/workbook.xml";
  17444. exports.calcChainFile = "xl/calcChain.xml";
  17445. exports.stylesFile = "xl/styles.xml";
  17446. exports.sharedStringsFile = "xl/sharedStrings.xml";
  17447. exports.worksheetFilePath = "xl/worksheets/";
  17448. exports.theme1File = "xl/theme/theme1.xml";
  17449. exports.workbookRels = "xl/_rels/workbook.xml.rels"; //Excel Built-In cell type
  17450. exports.ST_CellType = {
  17451. "Boolean": "b",
  17452. "Date": "d",
  17453. "Error": "e",
  17454. "InlineString": "inlineStr",
  17455. "Number": "n",
  17456. "SharedString": "s",
  17457. "String": "str"
  17458. }; //Excel Built-In cell style
  17459. exports.BuiltInCellStyles = {
  17460. "0": "Normal"
  17461. };
  17462. exports.numFmtDefault = {
  17463. "0": 'General',
  17464. "1": '0',
  17465. "2": '0.00',
  17466. "3": '#,##0',
  17467. "4": '#,##0.00',
  17468. "9": '0%',
  17469. "10": '0.00%',
  17470. "11": '0.00E+00',
  17471. "12": '# ?/?',
  17472. "13": '# ??/??',
  17473. "14": 'm/d/yy',
  17474. "15": 'd-mmm-yy',
  17475. "16": 'd-mmm',
  17476. "17": 'mmm-yy',
  17477. "18": 'h:mm AM/PM',
  17478. "19": 'h:mm:ss AM/PM',
  17479. "20": 'h:mm',
  17480. "21": 'h:mm:ss',
  17481. "22": 'm/d/yy h:mm',
  17482. "37": '#,##0 ;(#,##0)',
  17483. "38": '#,##0 ;[Red](#,##0)',
  17484. "39": '#,##0.00;(#,##0.00)',
  17485. "40": '#,##0.00;[Red](#,##0.00)',
  17486. "45": 'mm:ss',
  17487. "46": '[h]:mm:ss',
  17488. "47": 'mmss.0',
  17489. "48": '##0.0E+0',
  17490. "49": '@'
  17491. };
  17492. exports.indexedColors = {
  17493. "0": '00000000',
  17494. "1": '00FFFFFF',
  17495. "2": '00FF0000',
  17496. "3": '0000FF00',
  17497. "4": '000000FF',
  17498. "5": '00FFFF00',
  17499. "6": '00FF00FF',
  17500. "7": '0000FFFF',
  17501. "8": '00000000',
  17502. "9": '00FFFFFF',
  17503. "10": '00FF0000',
  17504. "11": '0000FF00',
  17505. "12": '000000FF',
  17506. "13": '00FFFF00',
  17507. "14": '00FF00FF',
  17508. "15": '0000FFFF',
  17509. "16": '00800000',
  17510. "17": '00008000',
  17511. "18": '00000080',
  17512. "19": '00808000',
  17513. "20": '00800080',
  17514. "21": '00008080',
  17515. "22": '00C0C0C0',
  17516. "23": '00808080',
  17517. "24": '009999FF',
  17518. "25": '00993366',
  17519. "26": '00FFFFCC',
  17520. "27": '00CCFFFF',
  17521. "28": '00660066',
  17522. "29": '00FF8080',
  17523. "30": '000066CC',
  17524. "31": '00CCCCFF',
  17525. "32": '00000080',
  17526. "33": '00FF00FF',
  17527. "34": '00FFFF00',
  17528. "35": '0000FFFF',
  17529. "36": '00800080',
  17530. "37": '00800000',
  17531. "38": '00008080',
  17532. "39": '000000FF',
  17533. "40": '0000CCFF',
  17534. "41": '00CCFFFF',
  17535. "42": '00CCFFCC',
  17536. "43": '00FFFF99',
  17537. "44": '0099CCFF',
  17538. "45": '00FF99CC',
  17539. "46": '00CC99FF',
  17540. "47": '00FFCC99',
  17541. "48": '003366FF',
  17542. "49": '0033CCCC',
  17543. "50": '0099CC00',
  17544. "51": '00FFCC00',
  17545. "52": '00FF9900',
  17546. "53": '00FF6600',
  17547. "54": '00666699',
  17548. "55": '00969696',
  17549. "56": '00003366',
  17550. "57": '00339966',
  17551. "58": '00003300',
  17552. "59": '00333300',
  17553. "60": '00993300',
  17554. "61": '00993366',
  17555. "62": '00333399',
  17556. "63": '00333333',
  17557. "64": null,
  17558. "65": null
  17559. };
  17560. exports.OEM_CHARSET = {
  17561. "0": "ANSI_CHARSET",
  17562. "1": "DEFAULT_CHARSET",
  17563. "2": "SYMBOL_CHARSET",
  17564. "77": "MAC_CHARSET",
  17565. "128": "SHIFTJIS_CHARSET",
  17566. "129": "HANGUL_CHARSET",
  17567. "130": "JOHAB_CHARSET",
  17568. "134": "GB2312_CHARSET",
  17569. "136": "CHINESEBIG5_CHARSET",
  17570. "161": "GREEK_CHARSET",
  17571. "162": "TURKISH_CHARSET",
  17572. "163": "VIETNAMESE_CHARSET",
  17573. "177": "HEBREW_CHARSET",
  17574. "178": "ARABIC_CHARSET",
  17575. "186": "BALTIC_CHARSET",
  17576. "204": "RUSSIAN_CHARSET",
  17577. "222": "THAI_CHARSET",
  17578. "238": "EASTEUROPE_CHARSET",
  17579. "255": "OEM_CHARSET"
  17580. };
  17581. exports.borderTypes = {
  17582. "none": 0,
  17583. "thin": 1,
  17584. "hair": 2,
  17585. "dotted": 3,
  17586. "dashed": 4,
  17587. "dashDot": 5,
  17588. "dashDotDot": 6,
  17589. "double": 7,
  17590. "medium": 8,
  17591. "mediumDashed": 9,
  17592. "mediumDashDot": 10,
  17593. "mediumDashDotDot": 11,
  17594. "slantDashDot": 12,
  17595. "thick": 13
  17596. };
  17597. exports.fontFamilys = {
  17598. "0": "defualt",
  17599. "1": "Roman",
  17600. "2": "Swiss",
  17601. "3": "Modern",
  17602. "4": "Script",
  17603. "5": "Decorative"
  17604. };
  17605. }, {}], 92: [function (require, module, exports) {
  17606. "use strict";
  17607. Object.defineProperty(exports, "__esModule", {
  17608. value: true
  17609. });
  17610. exports.ToContext2D = exports.FromEMF = exports.UDOC = void 0;
  17611. exports.UDOC = {};
  17612. exports.UDOC.G = {
  17613. concat: function concat(p, r) {
  17614. for (var i = 0; i < r.cmds.length; i++) {
  17615. p.cmds.push(r.cmds[i]);
  17616. }
  17617. for (var i = 0; i < r.crds.length; i++) {
  17618. p.crds.push(r.crds[i]);
  17619. }
  17620. },
  17621. getBB: function getBB(ps) {
  17622. var x0 = 1e99,
  17623. y0 = 1e99,
  17624. x1 = -x0,
  17625. y1 = -y0;
  17626. for (var i = 0; i < ps.length; i += 2) {
  17627. var x = ps[i],
  17628. y = ps[i + 1];
  17629. if (x < x0) x0 = x; else if (x > x1) x1 = x;
  17630. if (y < y0) y0 = y; else if (y > y1) y1 = y;
  17631. }
  17632. return [x0, y0, x1, y1];
  17633. },
  17634. rectToPath: function rectToPath(r) {
  17635. return {
  17636. cmds: ["M", "L", "L", "L", "Z"],
  17637. crds: [r[0], r[1], r[2], r[1], r[2], r[3], r[0], r[3]]
  17638. };
  17639. },
  17640. // a inside b
  17641. insideBox: function insideBox(a, b) {
  17642. return b[0] <= a[0] && b[1] <= a[1] && a[2] <= b[2] && a[3] <= b[3];
  17643. },
  17644. isBox: function isBox(p, bb) {
  17645. var sameCrd8 = function sameCrd8(pcrd, crds) {
  17646. for (var o = 0; o < 8; o += 2) {
  17647. var eq = true;
  17648. for (var j = 0; j < 8; j++) {
  17649. if (Math.abs(crds[j] - pcrd[j + o & 7]) >= 2) {
  17650. eq = false;
  17651. break;
  17652. }
  17653. }
  17654. if (eq) return true;
  17655. }
  17656. return false;
  17657. };
  17658. if (p.cmds.length > 10) return false;
  17659. var cmds = p.cmds.join(""),
  17660. crds = p.crds;
  17661. var sameRect = false;
  17662. if (cmds == "MLLLZ" && crds.length == 8 || cmds == "MLLLLZ" && crds.length == 10) {
  17663. if (crds.length == 10) crds = crds.slice(0, 8);
  17664. var x0 = bb[0],
  17665. y0 = bb[1],
  17666. x1 = bb[2],
  17667. y1 = bb[3];
  17668. if (!sameRect) sameRect = sameCrd8(crds, [x0, y0, x1, y0, x1, y1, x0, y1]);
  17669. if (!sameRect) sameRect = sameCrd8(crds, [x0, y1, x1, y1, x1, y0, x0, y0]);
  17670. }
  17671. return sameRect;
  17672. },
  17673. boxArea: function boxArea(a) {
  17674. var w = a[2] - a[0],
  17675. h = a[3] - a[1];
  17676. return w * h;
  17677. },
  17678. newPath: function newPath(gst) {
  17679. gst.pth = {
  17680. cmds: [],
  17681. crds: []
  17682. };
  17683. },
  17684. moveTo: function moveTo(gst, x, y) {
  17685. var p = exports.UDOC.M.multPoint(gst.ctm, [x, y]); //if(gst.cpos[0]==p[0] && gst.cpos[1]==p[1]) return;
  17686. gst.pth.cmds.push("M");
  17687. gst.pth.crds.push(p[0], p[1]);
  17688. gst.cpos = p;
  17689. },
  17690. lineTo: function lineTo(gst, x, y) {
  17691. var p = exports.UDOC.M.multPoint(gst.ctm, [x, y]);
  17692. if (gst.cpos[0] == p[0] && gst.cpos[1] == p[1]) return;
  17693. gst.pth.cmds.push("L");
  17694. gst.pth.crds.push(p[0], p[1]);
  17695. gst.cpos = p;
  17696. },
  17697. curveTo: function curveTo(gst, x1, y1, x2, y2, x3, y3) {
  17698. var p;
  17699. p = exports.UDOC.M.multPoint(gst.ctm, [x1, y1]);
  17700. x1 = p[0];
  17701. y1 = p[1];
  17702. p = exports.UDOC.M.multPoint(gst.ctm, [x2, y2]);
  17703. x2 = p[0];
  17704. y2 = p[1];
  17705. p = exports.UDOC.M.multPoint(gst.ctm, [x3, y3]);
  17706. x3 = p[0];
  17707. y3 = p[1];
  17708. gst.cpos = p;
  17709. gst.pth.cmds.push("C");
  17710. gst.pth.crds.push(x1, y1, x2, y2, x3, y3);
  17711. },
  17712. closePath: function closePath(gst) {
  17713. gst.pth.cmds.push("Z");
  17714. },
  17715. arc: function arc(gst, x, y, r, a0, a1, neg) {
  17716. // circle from a0 counter-clock-wise to a1
  17717. if (neg) while (a1 > a0) {
  17718. a1 -= 2 * Math.PI;
  17719. } else while (a1 < a0) {
  17720. a1 += 2 * Math.PI;
  17721. }
  17722. var th = (a1 - a0) / 4;
  17723. var x0 = Math.cos(th / 2),
  17724. y0 = -Math.sin(th / 2);
  17725. var x1 = (4 - x0) / 3,
  17726. y1 = y0 == 0 ? y0 : (1 - x0) * (3 - x0) / (3 * y0);
  17727. var x2 = x1,
  17728. y2 = -y1;
  17729. var x3 = x0,
  17730. y3 = -y0;
  17731. var p0 = [x0, y0],
  17732. p1 = [x1, y1],
  17733. p2 = [x2, y2],
  17734. p3 = [x3, y3];
  17735. var pth = {
  17736. cmds: [gst.pth.cmds.length == 0 ? "M" : "L", "C", "C", "C", "C"],
  17737. crds: [x0, y0, x1, y1, x2, y2, x3, y3]
  17738. };
  17739. var rot = [1, 0, 0, 1, 0, 0];
  17740. exports.UDOC.M.rotate(rot, -th);
  17741. for (var i = 0; i < 3; i++) {
  17742. p1 = exports.UDOC.M.multPoint(rot, p1);
  17743. p2 = exports.UDOC.M.multPoint(rot, p2);
  17744. p3 = exports.UDOC.M.multPoint(rot, p3);
  17745. pth.crds.push(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
  17746. }
  17747. var sc = [r, 0, 0, r, x, y];
  17748. exports.UDOC.M.rotate(rot, -a0 + th / 2);
  17749. exports.UDOC.M.concat(rot, sc);
  17750. exports.UDOC.M.multArray(rot, pth.crds);
  17751. exports.UDOC.M.multArray(gst.ctm, pth.crds);
  17752. exports.UDOC.G.concat(gst.pth, pth);
  17753. var y = pth.crds.pop();
  17754. x = pth.crds.pop();
  17755. gst.cpos = [x, y];
  17756. },
  17757. toPoly: function toPoly(p) {
  17758. if (p.cmds[0] != "M" || p.cmds[p.cmds.length - 1] != "Z") return null;
  17759. for (var i = 1; i < p.cmds.length - 1; i++) {
  17760. if (p.cmds[i] != "L") return null;
  17761. }
  17762. var out = [],
  17763. cl = p.crds.length;
  17764. if (p.crds[0] == p.crds[cl - 2] && p.crds[1] == p.crds[cl - 1]) cl -= 2;
  17765. for (var i = 0; i < cl; i += 2) {
  17766. out.push([p.crds[i], p.crds[i + 1]]);
  17767. }
  17768. if (exports.UDOC.G.polyArea(p.crds) < 0) out.reverse();
  17769. return out;
  17770. },
  17771. fromPoly: function fromPoly(p) {
  17772. var o = {
  17773. cmds: [],
  17774. crds: []
  17775. };
  17776. for (var i = 0; i < p.length; i++) {
  17777. o.crds.push(p[i][0], p[i][1]);
  17778. o.cmds.push(i == 0 ? "M" : "L");
  17779. }
  17780. o.cmds.push("Z");
  17781. return o;
  17782. },
  17783. polyArea: function polyArea(p) {
  17784. if (p.length < 6) return 0;
  17785. var l = p.length - 2;
  17786. var sum = (p[0] - p[l]) * (p[l + 1] + p[1]);
  17787. for (var i = 0; i < l; i += 2) {
  17788. sum += (p[i + 2] - p[i]) * (p[i + 1] + p[i + 3]);
  17789. }
  17790. return -sum * 0.5;
  17791. },
  17792. polyClip: function polyClip(p0, p1) {
  17793. var cp1, cp2, s, e;
  17794. var inside = function inside(p) {
  17795. return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]);
  17796. };
  17797. var isc = function isc() {
  17798. var dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]],
  17799. dp = [s[0] - e[0], s[1] - e[1]],
  17800. n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
  17801. n2 = s[0] * e[1] - s[1] * e[0],
  17802. n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
  17803. return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3];
  17804. };
  17805. var out = p0;
  17806. cp1 = p1[p1.length - 1];
  17807. for (var j in p1) {
  17808. var cp2 = p1[j];
  17809. var inp = out;
  17810. out = [];
  17811. s = inp[inp.length - 1]; //last on the input list
  17812. for (var i in inp) {
  17813. var e = inp[i];
  17814. if (inside(e)) {
  17815. if (!inside(s)) {
  17816. out.push(isc());
  17817. }
  17818. out.push(e);
  17819. } else if (inside(s)) {
  17820. out.push(isc());
  17821. }
  17822. s = e;
  17823. }
  17824. cp1 = cp2;
  17825. }
  17826. return out;
  17827. }
  17828. };
  17829. exports.UDOC.M = {
  17830. getScale: function getScale(m) {
  17831. return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
  17832. },
  17833. translate: function translate(m, x, y) {
  17834. exports.UDOC.M.concat(m, [1, 0, 0, 1, x, y]);
  17835. },
  17836. rotate: function rotate(m, a) {
  17837. exports.UDOC.M.concat(m, [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a), 0, 0]);
  17838. },
  17839. scale: function scale(m, x, y) {
  17840. exports.UDOC.M.concat(m, [x, 0, 0, y, 0, 0]);
  17841. },
  17842. concat: function concat(m, w) {
  17843. var a = m[0],
  17844. b = m[1],
  17845. c = m[2],
  17846. d = m[3],
  17847. tx = m[4],
  17848. ty = m[5];
  17849. m[0] = a * w[0] + b * w[2];
  17850. m[1] = a * w[1] + b * w[3];
  17851. m[2] = c * w[0] + d * w[2];
  17852. m[3] = c * w[1] + d * w[3];
  17853. m[4] = tx * w[0] + ty * w[2] + w[4];
  17854. m[5] = tx * w[1] + ty * w[3] + w[5];
  17855. },
  17856. invert: function invert(m) {
  17857. var a = m[0],
  17858. b = m[1],
  17859. c = m[2],
  17860. d = m[3],
  17861. tx = m[4],
  17862. ty = m[5],
  17863. adbc = a * d - b * c;
  17864. m[0] = d / adbc;
  17865. m[1] = -b / adbc;
  17866. m[2] = -c / adbc;
  17867. m[3] = a / adbc;
  17868. m[4] = (c * ty - d * tx) / adbc;
  17869. m[5] = (b * tx - a * ty) / adbc;
  17870. },
  17871. multPoint: function multPoint(m, p) {
  17872. var x = p[0],
  17873. y = p[1];
  17874. return [x * m[0] + y * m[2] + m[4], x * m[1] + y * m[3] + m[5]];
  17875. },
  17876. multArray: function multArray(m, a) {
  17877. for (var i = 0; i < a.length; i += 2) {
  17878. var x = a[i],
  17879. y = a[i + 1];
  17880. a[i] = x * m[0] + y * m[2] + m[4];
  17881. a[i + 1] = x * m[1] + y * m[3] + m[5];
  17882. }
  17883. }
  17884. };
  17885. exports.UDOC.C = {
  17886. srgbGamma: function srgbGamma(x) {
  17887. return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055;
  17888. },
  17889. cmykToRgb: function cmykToRgb(clr) {
  17890. var c = clr[0],
  17891. m = clr[1],
  17892. y = clr[2],
  17893. k = clr[3]; // return [1-Math.min(1,c+k), 1-Math.min(1, m+k), 1-Math.min(1,y+k)];
  17894. 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);
  17895. 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);
  17896. 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);
  17897. 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];
  17898. //return [(1-c[0])*iK, (1-c[1])*iK, (1-c[2])*iK];
  17899. },
  17900. labToRgb: function labToRgb(lab) {
  17901. var k = 903.3,
  17902. e = 0.008856,
  17903. L = lab[0],
  17904. a = lab[1],
  17905. b = lab[2];
  17906. var fy = (L + 16) / 116,
  17907. fy3 = fy * fy * fy;
  17908. var fz = fy - b / 200,
  17909. fz3 = fz * fz * fz;
  17910. var fx = a / 500 + fy,
  17911. fx3 = fx * fx * fx;
  17912. var zr = fz3 > e ? fz3 : (116 * fz - 16) / k;
  17913. var yr = fy3 > e ? fy3 : (116 * fy - 16) / k;
  17914. var xr = fx3 > e ? fx3 : (116 * fx - 16) / k;
  17915. var X = xr * 96.72,
  17916. Y = yr * 100,
  17917. Z = zr * 81.427,
  17918. xyz = [X / 100, Y / 100, Z / 100];
  17919. var x2s = [3.1338561, -1.6168667, -0.4906146, -0.9787684, 1.9161415, 0.0334540, 0.0719453, -0.2289914, 1.4052427];
  17920. 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]];
  17921. for (var i = 0; i < 3; i++) {
  17922. rgb[i] = Math.max(0, Math.min(1, exports.UDOC.C.srgbGamma(rgb[i])));
  17923. }
  17924. return rgb;
  17925. }
  17926. };
  17927. exports.UDOC.getState = function (crds) {
  17928. return {
  17929. font: exports.UDOC.getFont(),
  17930. dd: {
  17931. flat: 1
  17932. },
  17933. space: "/DeviceGray",
  17934. // fill
  17935. ca: 1,
  17936. colr: [0, 0, 0],
  17937. sspace: "/DeviceGray",
  17938. // stroke
  17939. CA: 1,
  17940. COLR: [0, 0, 0],
  17941. bmode: "/Normal",
  17942. SA: false,
  17943. OPM: 0,
  17944. AIS: false,
  17945. OP: false,
  17946. op: false,
  17947. SMask: "/None",
  17948. lwidth: 1,
  17949. lcap: 0,
  17950. ljoin: 0,
  17951. mlimit: 10,
  17952. SM: 0.1,
  17953. doff: 0,
  17954. dash: [],
  17955. ctm: [1, 0, 0, 1, 0, 0],
  17956. cpos: [0, 0],
  17957. pth: {
  17958. cmds: [],
  17959. crds: []
  17960. },
  17961. cpth: crds ? exports.UDOC.G.rectToPath(crds) : null // clipping path
  17962. };
  17963. };
  17964. exports.UDOC.getFont = function () {
  17965. return {
  17966. Tc: 0,
  17967. Tw: 0,
  17968. Th: 100,
  17969. Tl: 0,
  17970. Tf: "Helvetica-Bold",
  17971. Tfs: 1,
  17972. Tmode: 0,
  17973. Trise: 0,
  17974. Tk: 0,
  17975. Tal: 0,
  17976. Tun: 0,
  17977. Tm: [1, 0, 0, 1, 0, 0],
  17978. Tlm: [1, 0, 0, 1, 0, 0],
  17979. Trm: [1, 0, 0, 1, 0, 0]
  17980. };
  17981. };
  17982. exports.FromEMF = function () { };
  17983. exports.FromEMF.Parse = function (buff, genv) {
  17984. buff = new Uint8Array(buff);
  17985. var off = 0; //console.log(buff.slice(0,32));
  17986. var prms = {
  17987. fill: false,
  17988. strk: false,
  17989. bb: [0, 0, 1, 1],
  17990. wbb: [0, 0, 1, 1],
  17991. fnt: {
  17992. nam: "Arial",
  17993. hgh: 25,
  17994. und: false,
  17995. orn: 0
  17996. },
  17997. tclr: [0, 0, 0],
  17998. talg: 0
  17999. },
  18000. gst,
  18001. tab = [],
  18002. sts = [];
  18003. var rI = exports.FromEMF.B.readShort,
  18004. rU = exports.FromEMF.B.readUshort,
  18005. rI32 = exports.FromEMF.B.readInt,
  18006. rU32 = exports.FromEMF.B.readUint,
  18007. rF32 = exports.FromEMF.B.readFloat;
  18008. var opn = 0;
  18009. while (true) {
  18010. var fnc = rU32(buff, off);
  18011. off += 4;
  18012. var fnm = exports.FromEMF.K[fnc];
  18013. var siz = rU32(buff, off);
  18014. off += 4; //if(gst && isNaN(gst.ctm[0])) throw "e";
  18015. //console.log(fnc,fnm,siz);
  18016. var loff = off; //if(opn++==253) break;
  18017. var obj = null,
  18018. oid = 0; //console.log(fnm, siz);
  18019. if (false) { } else if (fnm == "EOF") {
  18020. break;
  18021. } else if (fnm == "HEADER") {
  18022. prms.bb = exports.FromEMF._readBox(buff, loff);
  18023. loff += 16; //console.log(fnm, prms.bb);
  18024. genv.StartPage(prms.bb[0], prms.bb[1], prms.bb[2], prms.bb[3]);
  18025. gst = exports.UDOC.getState(prms.bb);
  18026. } else if (fnm == "SAVEDC") sts.push(JSON.stringify(gst), JSON.stringify(prms)); else if (fnm == "RESTOREDC") {
  18027. var dif = rI32(buff, loff);
  18028. loff += 4;
  18029. while (dif < -1) {
  18030. sts.pop();
  18031. sts.pop();
  18032. }
  18033. prms = JSON.parse(sts.pop());
  18034. gst = JSON.parse(sts.pop());
  18035. } else if (fnm == "SELECTCLIPPATH") {
  18036. gst.cpth = JSON.parse(JSON.stringify(gst.pth));
  18037. } else if (["SETMAPMODE", "SETPOLYFILLMODE", "SETBKMODE"
  18038. /*,"SETVIEWPORTEXTEX"*/
  18039. , "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); }
  18040. 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") {
  18041. if (prms.vbb == null) prms.vbb = [];
  18042. var coff = fnm == "SETVIEWPORTORGEX" ? 0 : 2;
  18043. prms.vbb[coff] = rI32(buff, loff);
  18044. loff += 4;
  18045. prms.vbb[coff + 1] = rI32(buff, loff);
  18046. loff += 4; //console.log(prms.vbb);
  18047. if (fnm == "SETVIEWPORTEXTEX") exports.FromEMF._updateCtm(prms, gst);
  18048. } else if (fnm == "SETWINDOWEXTEX" || fnm == "SETWINDOWORGEX") {
  18049. var coff = fnm == "SETWINDOWORGEX" ? 0 : 2;
  18050. prms.wbb[coff] = rI32(buff, loff);
  18051. loff += 4;
  18052. prms.wbb[coff + 1] = rI32(buff, loff);
  18053. loff += 4;
  18054. if (fnm == "SETWINDOWEXTEX") exports.FromEMF._updateCtm(prms, gst);
  18055. } //else if(fnm=="SETMETARGN") {}
  18056. else if (fnm == "COMMENT") {
  18057. var ds = rU32(buff, loff);
  18058. loff += 4;
  18059. } else if (fnm == "SELECTOBJECT") {
  18060. var ind = rU32(buff, loff);
  18061. loff += 4; //console.log(ind.toString(16), tab, tab[ind]);
  18062. if (ind == 0x80000000) {
  18063. prms.fill = true;
  18064. gst.colr = [1, 1, 1];
  18065. } // white brush
  18066. else if (ind == 0x80000005) {
  18067. prms.fill = false;
  18068. } // null brush
  18069. else if (ind == 0x80000007) {
  18070. prms.strk = true;
  18071. prms.lwidth = 1;
  18072. gst.COLR = [0, 0, 0];
  18073. } // black pen
  18074. else if (ind == 0x80000008) {
  18075. prms.strk = false;
  18076. } // null pen
  18077. else if (ind == 0x8000000d) { } // system font
  18078. else if (ind == 0x8000000e) { } // device default font
  18079. else {
  18080. var co = tab[ind]; //console.log(ind, co);
  18081. if (co.t == "b") {
  18082. prms.fill = co.stl != 1;
  18083. if (co.stl == 0) { } else if (co.stl == 1) { } else throw co.stl + " e";
  18084. gst.colr = co.clr;
  18085. } else if (co.t == "p") {
  18086. prms.strk = co.stl != 5;
  18087. gst.lwidth = co.wid;
  18088. gst.COLR = co.clr;
  18089. } else if (co.t == "f") {
  18090. prms.fnt = co;
  18091. gst.font.Tf = co.nam;
  18092. gst.font.Tfs = Math.abs(co.hgh);
  18093. gst.font.Tun = co.und;
  18094. } else throw "e";
  18095. }
  18096. } else if (fnm == "DELETEOBJECT") {
  18097. var ind = rU32(buff, loff);
  18098. loff += 4;
  18099. if (tab[ind] != null) tab[ind] = null; else throw "e";
  18100. } else if (fnm == "CREATEBRUSHINDIRECT") {
  18101. oid = rU32(buff, loff);
  18102. loff += 4;
  18103. obj = {
  18104. t: "b"
  18105. };
  18106. obj.stl = rU32(buff, loff);
  18107. loff += 4;
  18108. obj.clr = [buff[loff] / 255, buff[loff + 1] / 255, buff[loff + 2] / 255];
  18109. loff += 4;
  18110. obj.htc = rU32(buff, loff);
  18111. loff += 4; //console.log(oid, obj);
  18112. } else if (fnm == "CREATEPEN" || fnm == "EXTCREATEPEN") {
  18113. oid = rU32(buff, loff);
  18114. loff += 4;
  18115. obj = {
  18116. t: "p"
  18117. };
  18118. if (fnm == "EXTCREATEPEN") {
  18119. loff += 16;
  18120. obj.stl = rU32(buff, loff);
  18121. loff += 4;
  18122. obj.wid = rU32(buff, loff);
  18123. loff += 4; //obj.stl = rU32(buff, loff);
  18124. loff += 4;
  18125. } else {
  18126. obj.stl = rU32(buff, loff);
  18127. loff += 4;
  18128. obj.wid = rU32(buff, loff);
  18129. loff += 4;
  18130. loff += 4;
  18131. }
  18132. obj.clr = [buff[loff] / 255, buff[loff + 1] / 255, buff[loff + 2] / 255];
  18133. loff += 4;
  18134. } else if (fnm == "EXTCREATEFONTINDIRECTW") {
  18135. oid = rU32(buff, loff);
  18136. loff += 4;
  18137. obj = {
  18138. t: "f",
  18139. nam: ""
  18140. };
  18141. obj.hgh = rI32(buff, loff);
  18142. loff += 4;
  18143. loff += 4 * 2;
  18144. obj.orn = rI32(buff, loff) / 10;
  18145. loff += 4;
  18146. var wgh = rU32(buff, loff);
  18147. loff += 4; //console.log(fnm, obj.orn, wgh);
  18148. //console.log(rU32(buff,loff), rU32(buff,loff+4), buff.slice(loff,loff+8));
  18149. obj.und = buff[loff + 1];
  18150. obj.stk = buff[loff + 2];
  18151. loff += 4 * 2;
  18152. while (rU(buff, loff) != 0) {
  18153. obj.nam += String.fromCharCode(rU(buff, loff));
  18154. loff += 2;
  18155. }
  18156. if (wgh > 500) obj.nam += "-Bold"; //console.log(wgh, obj.nam);
  18157. } else if (fnm == "EXTTEXTOUTW") {
  18158. //console.log(buff.slice(loff-8, loff-8+siz));
  18159. loff += 16;
  18160. var mod = rU32(buff, loff);
  18161. loff += 4; //console.log(mod);
  18162. var scx = rF32(buff, loff);
  18163. loff += 4;
  18164. var scy = rF32(buff, loff);
  18165. loff += 4;
  18166. var rfx = rI32(buff, loff);
  18167. loff += 4;
  18168. var rfy = rI32(buff, loff);
  18169. loff += 4; //console.log(mod, scx, scy,rfx,rfy);
  18170. gst.font.Tm = [1, 0, 0, -1, 0, 0];
  18171. exports.UDOC.M.rotate(gst.font.Tm, prms.fnt.orn * Math.PI / 180);
  18172. exports.UDOC.M.translate(gst.font.Tm, rfx, rfy);
  18173. var alg = prms.talg; //console.log(alg.toString(2));
  18174. if ((alg & 6) == 6) gst.font.Tal = 2; else if ((alg & 7) == 0) gst.font.Tal = 0; else throw alg + " e";
  18175. if ((alg & 24) == 24) { } // baseline
  18176. else if ((alg & 24) == 0) exports.UDOC.M.translate(gst.font.Tm, 0, gst.font.Tfs); else throw "e";
  18177. var crs = rU32(buff, loff);
  18178. loff += 4;
  18179. var ofs = rU32(buff, loff);
  18180. loff += 4;
  18181. var ops = rU32(buff, loff);
  18182. loff += 4; //if(ops!=0) throw "e";
  18183. //console.log(ofs,ops,crs);
  18184. loff += 16;
  18185. var ofD = rU32(buff, loff);
  18186. loff += 4; //console.log(ops, ofD, loff, ofs+off-8);
  18187. ofs += off - 8; //console.log(crs, ops);
  18188. var str = "";
  18189. for (var i = 0; i < crs; i++) {
  18190. var cc = rU(buff, ofs + i * 2);
  18191. str += String.fromCharCode(cc);
  18192. }
  18193. ;
  18194. var oclr = gst.colr;
  18195. gst.colr = prms.tclr; //console.log(str, gst.colr, gst.font.Tm);
  18196. //var otfs = gst.font.Tfs; gst.font.Tfs *= 1/gst.ctm[0];
  18197. genv.PutText(gst, str, str.length * gst.font.Tfs * 0.5);
  18198. gst.colr = oclr; //gst.font.Tfs = otfs;
  18199. //console.log(rfx, rfy, scx, ops, rcX, rcY, rcW, rcH, offDx, str);
  18200. } else if (fnm == "BEGINPATH") {
  18201. exports.UDOC.G.newPath(gst);
  18202. } else if (fnm == "ENDPATH") { } else if (fnm == "CLOSEFIGURE") exports.UDOC.G.closePath(gst); else if (fnm == "MOVETOEX") {
  18203. exports.UDOC.G.moveTo(gst, rI32(buff, loff), rI32(buff, loff + 4));
  18204. } else if (fnm == "LINETO") {
  18205. if (gst.pth.cmds.length == 0) {
  18206. var im = gst.ctm.slice(0);
  18207. exports.UDOC.M.invert(im);
  18208. var p = exports.UDOC.M.multPoint(im, gst.cpos);
  18209. exports.UDOC.G.moveTo(gst, p[0], p[1]);
  18210. }
  18211. exports.UDOC.G.lineTo(gst, rI32(buff, loff), rI32(buff, loff + 4));
  18212. } else if (fnm == "POLYGON" || fnm == "POLYGON16" || fnm == "POLYLINE" || fnm == "POLYLINE16" || fnm == "POLYLINETO" || fnm == "POLYLINETO16") {
  18213. loff += 16;
  18214. var ndf = fnm.startsWith("POLYGON"),
  18215. isTo = fnm.indexOf("TO") != -1;
  18216. var cnt = rU32(buff, loff);
  18217. loff += 4;
  18218. if (!isTo) exports.UDOC.G.newPath(gst);
  18219. loff = exports.FromEMF._drawPoly(buff, loff, cnt, gst, fnm.endsWith("16") ? 2 : 4, ndf, isTo);
  18220. if (!isTo) exports.FromEMF._draw(genv, gst, prms, ndf); //console.log(prms, gst.lwidth);
  18221. //console.log(JSON.parse(JSON.stringify(gst.pth)));
  18222. } else if (fnm == "POLYPOLYGON16") {
  18223. loff += 16;
  18224. var ndf = fnm.startsWith("POLYPOLYGON"),
  18225. isTo = fnm.indexOf("TO") != -1;
  18226. var nop = rU32(buff, loff);
  18227. loff += 4;
  18228. loff += 4;
  18229. var pi = loff;
  18230. loff += nop * 4;
  18231. if (!isTo) exports.UDOC.G.newPath(gst);
  18232. for (var i = 0; i < nop; i++) {
  18233. var ppp = rU(buff, pi + i * 4);
  18234. loff = exports.FromEMF._drawPoly(buff, loff, ppp, gst, fnm.endsWith("16") ? 2 : 4, ndf, isTo);
  18235. }
  18236. if (!isTo) exports.FromEMF._draw(genv, gst, prms, ndf);
  18237. } else if (fnm == "POLYBEZIER" || fnm == "POLYBEZIER16" || fnm == "POLYBEZIERTO" || fnm == "POLYBEZIERTO16") {
  18238. loff += 16;
  18239. var is16 = fnm.endsWith("16"),
  18240. rC = is16 ? rI : rI32,
  18241. nl = is16 ? 2 : 4;
  18242. var cnt = rU32(buff, loff);
  18243. loff += 4;
  18244. if (fnm.indexOf("TO") == -1) {
  18245. exports.UDOC.G.moveTo(gst, rC(buff, loff), rC(buff, loff + nl));
  18246. loff += 2 * nl;
  18247. cnt--;
  18248. }
  18249. while (cnt > 0) {
  18250. 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));
  18251. loff += 6 * nl;
  18252. cnt -= 3;
  18253. } //console.log(JSON.parse(JSON.stringify(gst.pth)));
  18254. } else if (fnm == "RECTANGLE" || fnm == "ELLIPSE") {
  18255. exports.UDOC.G.newPath(gst);
  18256. var bx = exports.FromEMF._readBox(buff, loff);
  18257. if (fnm == "RECTANGLE") {
  18258. exports.UDOC.G.moveTo(gst, bx[0], bx[1]);
  18259. exports.UDOC.G.lineTo(gst, bx[2], bx[1]);
  18260. exports.UDOC.G.lineTo(gst, bx[2], bx[3]);
  18261. exports.UDOC.G.lineTo(gst, bx[0], bx[3]);
  18262. } else {
  18263. var x = (bx[0] + bx[2]) / 2,
  18264. y = (bx[1] + bx[3]) / 2;
  18265. exports.UDOC.G.arc(gst, x, y, (bx[2] - bx[0]) / 2, 0, 2 * Math.PI, false);
  18266. }
  18267. exports.UDOC.G.closePath(gst);
  18268. exports.FromEMF._draw(genv, gst, prms, true); //console.log(prms, gst.lwidth);
  18269. } else if (fnm == "FILLPATH") genv.Fill(gst, false); else if (fnm == "STROKEPATH") genv.Stroke(gst); else if (fnm == "STROKEANDFILLPATH") {
  18270. genv.Fill(gst, false);
  18271. genv.Stroke(gst);
  18272. } else if (fnm == "SETWORLDTRANSFORM" || fnm == "MODIFYWORLDTRANSFORM") {
  18273. var mat = [];
  18274. for (var i = 0; i < 6; i++) {
  18275. mat.push(rF32(buff, loff + i * 4));
  18276. }
  18277. loff += 24; //console.log(fnm, gst.ctm.slice(0), mat);
  18278. if (fnm == "SETWORLDTRANSFORM") gst.ctm = mat; else {
  18279. var mod = rU32(buff, loff);
  18280. loff += 4;
  18281. if (mod == 2) {
  18282. var om = gst.ctm;
  18283. gst.ctm = mat;
  18284. exports.UDOC.M.concat(gst.ctm, om);
  18285. } else throw "e";
  18286. }
  18287. } else if (fnm == "SETSTRETCHBLTMODE") {
  18288. var sm = rU32(buff, loff);
  18289. loff += 4;
  18290. } else if (fnm == "STRETCHDIBITS") {
  18291. var bx = exports.FromEMF._readBox(buff, loff);
  18292. loff += 16;
  18293. var xD = rI32(buff, loff);
  18294. loff += 4;
  18295. var yD = rI32(buff, loff);
  18296. loff += 4;
  18297. var xS = rI32(buff, loff);
  18298. loff += 4;
  18299. var yS = rI32(buff, loff);
  18300. loff += 4;
  18301. var wS = rI32(buff, loff);
  18302. loff += 4;
  18303. var hS = rI32(buff, loff);
  18304. loff += 4;
  18305. var ofH = rU32(buff, loff) + off - 8;
  18306. loff += 4;
  18307. var szH = rU32(buff, loff);
  18308. loff += 4;
  18309. var ofB = rU32(buff, loff) + off - 8;
  18310. loff += 4;
  18311. var szB = rU32(buff, loff);
  18312. loff += 4;
  18313. var usg = rU32(buff, loff);
  18314. loff += 4;
  18315. if (usg != 0) throw "e";
  18316. var bop = rU32(buff, loff);
  18317. loff += 4;
  18318. var wD = rI32(buff, loff);
  18319. loff += 4;
  18320. var hD = rI32(buff, loff);
  18321. loff += 4; //console.log(bop, wD, hD);
  18322. //console.log(ofH, szH, ofB, szB, ofH+40);
  18323. //console.log(bx, xD,yD,wD,hD);
  18324. //console.log(xS,yS,wS,hS);
  18325. //console.log(ofH,szH,ofB,szB,usg,bop);
  18326. var hl = rU32(buff, ofH);
  18327. ofH += 4;
  18328. var w = rU32(buff, ofH);
  18329. ofH += 4;
  18330. var h = rU32(buff, ofH);
  18331. ofH += 4;
  18332. if (w != wS || h != hS) throw "e";
  18333. var ps = rU(buff, ofH);
  18334. ofH += 2;
  18335. var bc = rU(buff, ofH);
  18336. ofH += 2;
  18337. if (bc != 8 && bc != 24 && bc != 32) throw bc + " e";
  18338. var cpr = rU32(buff, ofH);
  18339. ofH += 4;
  18340. if (cpr != 0) throw cpr + " e";
  18341. var sz = rU32(buff, ofH);
  18342. ofH += 4;
  18343. var xpm = rU32(buff, ofH);
  18344. ofH += 4;
  18345. var ypm = rU32(buff, ofH);
  18346. ofH += 4;
  18347. var cu = rU32(buff, ofH);
  18348. ofH += 4;
  18349. var ci = rU32(buff, ofH);
  18350. ofH += 4; //console.log(hl, w, h, ps, bc, cpr, sz, xpm, ypm, cu, ci);
  18351. //console.log(hl,w,h,",",xS,yS,wS,hS,",",xD,yD,wD,hD,",",xpm,ypm);
  18352. var rl = Math.floor((w * ps * bc + 31 & ~31) / 8);
  18353. var img = new Uint8Array(w * h * 4);
  18354. if (bc == 8) {
  18355. for (var y = 0; y < h; y++) {
  18356. for (var x = 0; x < w; x++) {
  18357. var qi = y * w + x << 2,
  18358. ind = buff[ofB + (h - 1 - y) * rl + x] << 2;
  18359. img[qi] = buff[ofH + ind + 2];
  18360. img[qi + 1] = buff[ofH + ind + 1];
  18361. img[qi + 2] = buff[ofH + ind + 0];
  18362. img[qi + 3] = 255;
  18363. }
  18364. }
  18365. }
  18366. if (bc == 24) {
  18367. for (var y = 0; y < h; y++) {
  18368. for (var x = 0; x < w; x++) {
  18369. var qi = y * w + x << 2,
  18370. ti = ofB + (h - 1 - y) * rl + x * 3;
  18371. img[qi] = buff[ti + 2];
  18372. img[qi + 1] = buff[ti + 1];
  18373. img[qi + 2] = buff[ti + 0];
  18374. img[qi + 3] = 255;
  18375. }
  18376. }
  18377. }
  18378. if (bc == 32) {
  18379. for (var y = 0; y < h; y++) {
  18380. for (var x = 0; x < w; x++) {
  18381. var qi = y * w + x << 2,
  18382. ti = ofB + (h - 1 - y) * rl + x * 4;
  18383. img[qi] = buff[ti + 2];
  18384. img[qi + 1] = buff[ti + 1];
  18385. img[qi + 2] = buff[ti + 0];
  18386. img[qi + 3] = buff[ti + 3];
  18387. }
  18388. }
  18389. }
  18390. var ctm = gst.ctm.slice(0);
  18391. gst.ctm = [1, 0, 0, 1, 0, 0];
  18392. exports.UDOC.M.scale(gst.ctm, wD, -hD);
  18393. exports.UDOC.M.translate(gst.ctm, xD, yD + hD);
  18394. exports.UDOC.M.concat(gst.ctm, ctm);
  18395. genv.PutImage(gst, img, w, h);
  18396. gst.ctm = ctm;
  18397. } else {
  18398. console.log(fnm, siz);
  18399. }
  18400. if (obj != null) tab[oid] = obj;
  18401. off += siz - 8;
  18402. } //genv.Stroke(gst);
  18403. genv.ShowPage();
  18404. genv.Done();
  18405. };
  18406. exports.FromEMF._readBox = function (buff, off) {
  18407. var b = [];
  18408. for (var i = 0; i < 4; i++) {
  18409. b[i] = exports.FromEMF.B.readInt(buff, off + i * 4);
  18410. }
  18411. return b;
  18412. };
  18413. exports.FromEMF._updateCtm = function (prms, gst) {
  18414. var mat = [1, 0, 0, 1, 0, 0];
  18415. var wbb = prms.wbb,
  18416. bb = prms.bb,
  18417. 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);
  18418. exports.UDOC.M.translate(mat, -wbb[0], -wbb[1]);
  18419. exports.UDOC.M.scale(mat, 1 / wbb[2], 1 / wbb[3]);
  18420. 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]));
  18421. //UDOC.M.scale(mat, bb[2]-bb[0],bb[3]-bb[1]);
  18422. gst.ctm = mat;
  18423. };
  18424. exports.FromEMF._draw = function (genv, gst, prms, needFill) {
  18425. if (prms.fill && needFill) genv.Fill(gst, false);
  18426. if (prms.strk && gst.lwidth != 0) genv.Stroke(gst);
  18427. };
  18428. exports.FromEMF._drawPoly = function (buff, off, ppp, gst, nl, clos, justLine) {
  18429. var rS = nl == 2 ? exports.FromEMF.B.readShort : exports.FromEMF.B.readInt;
  18430. for (var j = 0; j < ppp; j++) {
  18431. var px = rS(buff, off);
  18432. off += nl;
  18433. var py = rS(buff, off);
  18434. off += nl;
  18435. if (j == 0 && !justLine) exports.UDOC.G.moveTo(gst, px, py); else exports.UDOC.G.lineTo(gst, px, py);
  18436. }
  18437. if (clos) exports.UDOC.G.closePath(gst);
  18438. return off;
  18439. };
  18440. exports.FromEMF.B = {
  18441. uint8: new Uint8Array(4),
  18442. readShort: function readShort(buff, p) {
  18443. var u8 = exports.FromEMF.B.uint8;
  18444. u8[0] = buff[p];
  18445. u8[1] = buff[p + 1];
  18446. return exports.FromEMF.B.int16[0];
  18447. },
  18448. readUshort: function readUshort(buff, p) {
  18449. var u8 = exports.FromEMF.B.uint8;
  18450. u8[0] = buff[p];
  18451. u8[1] = buff[p + 1];
  18452. return exports.FromEMF.B.uint16[0];
  18453. },
  18454. readInt: function readInt(buff, p) {
  18455. var u8 = exports.FromEMF.B.uint8;
  18456. u8[0] = buff[p];
  18457. u8[1] = buff[p + 1];
  18458. u8[2] = buff[p + 2];
  18459. u8[3] = buff[p + 3];
  18460. return exports.FromEMF.B.int32[0];
  18461. },
  18462. readUint: function readUint(buff, p) {
  18463. var u8 = exports.FromEMF.B.uint8;
  18464. u8[0] = buff[p];
  18465. u8[1] = buff[p + 1];
  18466. u8[2] = buff[p + 2];
  18467. u8[3] = buff[p + 3];
  18468. return exports.FromEMF.B.uint32[0];
  18469. },
  18470. readFloat: function readFloat(buff, p) {
  18471. var u8 = exports.FromEMF.B.uint8;
  18472. u8[0] = buff[p];
  18473. u8[1] = buff[p + 1];
  18474. u8[2] = buff[p + 2];
  18475. u8[3] = buff[p + 3];
  18476. return exports.FromEMF.B.flot32[0];
  18477. },
  18478. readASCII: function readASCII(buff, p, l) {
  18479. var s = "";
  18480. for (var i = 0; i < l; i++) {
  18481. s += String.fromCharCode(buff[p + i]);
  18482. }
  18483. return s;
  18484. }
  18485. };
  18486. exports.FromEMF.B.int16 = new Int16Array(exports.FromEMF.B.uint8.buffer);
  18487. exports.FromEMF.B.uint16 = new Uint16Array(exports.FromEMF.B.uint8.buffer);
  18488. exports.FromEMF.B.int32 = new Int32Array(exports.FromEMF.B.uint8.buffer);
  18489. exports.FromEMF.B.uint32 = new Uint32Array(exports.FromEMF.B.uint8.buffer);
  18490. exports.FromEMF.B.flot32 = new Float32Array(exports.FromEMF.B.uint8.buffer);
  18491. exports.FromEMF.C = {
  18492. EMR_HEADER: 0x00000001,
  18493. EMR_POLYBEZIER: 0x00000002,
  18494. EMR_POLYGON: 0x00000003,
  18495. EMR_POLYLINE: 0x00000004,
  18496. EMR_POLYBEZIERTO: 0x00000005,
  18497. EMR_POLYLINETO: 0x00000006,
  18498. EMR_POLYPOLYLINE: 0x00000007,
  18499. EMR_POLYPOLYGON: 0x00000008,
  18500. EMR_SETWINDOWEXTEX: 0x00000009,
  18501. EMR_SETWINDOWORGEX: 0x0000000A,
  18502. EMR_SETVIEWPORTEXTEX: 0x0000000B,
  18503. EMR_SETVIEWPORTORGEX: 0x0000000C,
  18504. EMR_SETBRUSHORGEX: 0x0000000D,
  18505. EMR_EOF: 0x0000000E,
  18506. EMR_SETPIXELV: 0x0000000F,
  18507. EMR_SETMAPPERFLAGS: 0x00000010,
  18508. EMR_SETMAPMODE: 0x00000011,
  18509. EMR_SETBKMODE: 0x00000012,
  18510. EMR_SETPOLYFILLMODE: 0x00000013,
  18511. EMR_SETROP2: 0x00000014,
  18512. EMR_SETSTRETCHBLTMODE: 0x00000015,
  18513. EMR_SETTEXTALIGN: 0x00000016,
  18514. EMR_SETCOLORADJUSTMENT: 0x00000017,
  18515. EMR_SETTEXTCOLOR: 0x00000018,
  18516. EMR_SETBKCOLOR: 0x00000019,
  18517. EMR_OFFSETCLIPRGN: 0x0000001A,
  18518. EMR_MOVETOEX: 0x0000001B,
  18519. EMR_SETMETARGN: 0x0000001C,
  18520. EMR_EXCLUDECLIPRECT: 0x0000001D,
  18521. EMR_INTERSECTCLIPRECT: 0x0000001E,
  18522. EMR_SCALEVIEWPORTEXTEX: 0x0000001F,
  18523. EMR_SCALEWINDOWEXTEX: 0x00000020,
  18524. EMR_SAVEDC: 0x00000021,
  18525. EMR_RESTOREDC: 0x00000022,
  18526. EMR_SETWORLDTRANSFORM: 0x00000023,
  18527. EMR_MODIFYWORLDTRANSFORM: 0x00000024,
  18528. EMR_SELECTOBJECT: 0x00000025,
  18529. EMR_CREATEPEN: 0x00000026,
  18530. EMR_CREATEBRUSHINDIRECT: 0x00000027,
  18531. EMR_DELETEOBJECT: 0x00000028,
  18532. EMR_ANGLEARC: 0x00000029,
  18533. EMR_ELLIPSE: 0x0000002A,
  18534. EMR_RECTANGLE: 0x0000002B,
  18535. EMR_ROUNDRECT: 0x0000002C,
  18536. EMR_ARC: 0x0000002D,
  18537. EMR_CHORD: 0x0000002E,
  18538. EMR_PIE: 0x0000002F,
  18539. EMR_SELECTPALETTE: 0x00000030,
  18540. EMR_CREATEPALETTE: 0x00000031,
  18541. EMR_SETPALETTEENTRIES: 0x00000032,
  18542. EMR_RESIZEPALETTE: 0x00000033,
  18543. EMR_REALIZEPALETTE: 0x00000034,
  18544. EMR_EXTFLOODFILL: 0x00000035,
  18545. EMR_LINETO: 0x00000036,
  18546. EMR_ARCTO: 0x00000037,
  18547. EMR_POLYDRAW: 0x00000038,
  18548. EMR_SETARCDIRECTION: 0x00000039,
  18549. EMR_SETMITERLIMIT: 0x0000003A,
  18550. EMR_BEGINPATH: 0x0000003B,
  18551. EMR_ENDPATH: 0x0000003C,
  18552. EMR_CLOSEFIGURE: 0x0000003D,
  18553. EMR_FILLPATH: 0x0000003E,
  18554. EMR_STROKEANDFILLPATH: 0x0000003F,
  18555. EMR_STROKEPATH: 0x00000040,
  18556. EMR_FLATTENPATH: 0x00000041,
  18557. EMR_WIDENPATH: 0x00000042,
  18558. EMR_SELECTCLIPPATH: 0x00000043,
  18559. EMR_ABORTPATH: 0x00000044,
  18560. EMR_COMMENT: 0x00000046,
  18561. EMR_FILLRGN: 0x00000047,
  18562. EMR_FRAMERGN: 0x00000048,
  18563. EMR_INVERTRGN: 0x00000049,
  18564. EMR_PAINTRGN: 0x0000004A,
  18565. EMR_EXTSELECTCLIPRGN: 0x0000004B,
  18566. EMR_BITBLT: 0x0000004C,
  18567. EMR_STRETCHBLT: 0x0000004D,
  18568. EMR_MASKBLT: 0x0000004E,
  18569. EMR_PLGBLT: 0x0000004F,
  18570. EMR_SETDIBITSTODEVICE: 0x00000050,
  18571. EMR_STRETCHDIBITS: 0x00000051,
  18572. EMR_EXTCREATEFONTINDIRECTW: 0x00000052,
  18573. EMR_EXTTEXTOUTA: 0x00000053,
  18574. EMR_EXTTEXTOUTW: 0x00000054,
  18575. EMR_POLYBEZIER16: 0x00000055,
  18576. EMR_POLYGON16: 0x00000056,
  18577. EMR_POLYLINE16: 0x00000057,
  18578. EMR_POLYBEZIERTO16: 0x00000058,
  18579. EMR_POLYLINETO16: 0x00000059,
  18580. EMR_POLYPOLYLINE16: 0x0000005A,
  18581. EMR_POLYPOLYGON16: 0x0000005B,
  18582. EMR_POLYDRAW16: 0x0000005C,
  18583. EMR_CREATEMONOBRUSH: 0x0000005D,
  18584. EMR_CREATEDIBPATTERNBRUSHPT: 0x0000005E,
  18585. EMR_EXTCREATEPEN: 0x0000005F,
  18586. EMR_POLYTEXTOUTA: 0x00000060,
  18587. EMR_POLYTEXTOUTW: 0x00000061,
  18588. EMR_SETICMMODE: 0x00000062,
  18589. EMR_CREATECOLORSPACE: 0x00000063,
  18590. EMR_SETCOLORSPACE: 0x00000064,
  18591. EMR_DELETECOLORSPACE: 0x00000065,
  18592. EMR_GLSRECORD: 0x00000066,
  18593. EMR_GLSBOUNDEDRECORD: 0x00000067,
  18594. EMR_PIXELFORMAT: 0x00000068,
  18595. EMR_DRAWESCAPE: 0x00000069,
  18596. EMR_EXTESCAPE: 0x0000006A,
  18597. EMR_SMALLTEXTOUT: 0x0000006C,
  18598. EMR_FORCEUFIMAPPING: 0x0000006D,
  18599. EMR_NAMEDESCAPE: 0x0000006E,
  18600. EMR_COLORCORRECTPALETTE: 0x0000006F,
  18601. EMR_SETICMPROFILEA: 0x00000070,
  18602. EMR_SETICMPROFILEW: 0x00000071,
  18603. EMR_ALPHABLEND: 0x00000072,
  18604. EMR_SETLAYOUT: 0x00000073,
  18605. EMR_TRANSPARENTBLT: 0x00000074,
  18606. EMR_GRADIENTFILL: 0x00000076,
  18607. EMR_SETLINKEDUFIS: 0x00000077,
  18608. EMR_SETTEXTJUSTIFICATION: 0x00000078,
  18609. EMR_COLORMATCHTOTARGETW: 0x00000079,
  18610. EMR_CREATECOLORSPACEW: 0x0000007A
  18611. };
  18612. exports.FromEMF.K = []; // (function() {
  18613. // var inp, out, stt;
  18614. // inp = FromEMF.C; out = FromEMF.K; stt=4;
  18615. // for(var p in inp) out[inp[p]] = p.slice(stt);
  18616. // } )();
  18617. exports.ToContext2D = function (needPage, scale) {
  18618. this.canvas = document.createElement("canvas");
  18619. this.ctx = this.canvas.getContext("2d");
  18620. this.bb = null;
  18621. this.currPage = 0;
  18622. this.needPage = needPage;
  18623. this.scale = scale;
  18624. };
  18625. exports.ToContext2D.prototype.StartPage = function (x, y, w, h) {
  18626. if (this.currPage != this.needPage) return;
  18627. this.bb = [x, y, w, h];
  18628. var scl = this.scale,
  18629. dpr = window.devicePixelRatio;
  18630. var cnv = this.canvas,
  18631. ctx = this.ctx;
  18632. cnv.width = Math.round(w * scl);
  18633. cnv.height = Math.round(h * scl);
  18634. ctx.translate(0, h * scl);
  18635. ctx.scale(scl, -scl);
  18636. cnv.setAttribute("style", "border:1px solid; width:" + cnv.width / dpr + "px; height:" + cnv.height / dpr + "px");
  18637. };
  18638. exports.ToContext2D.prototype.Fill = function (gst, evenOdd) {
  18639. if (this.currPage != this.needPage) return;
  18640. var ctx = this.ctx;
  18641. ctx.beginPath();
  18642. this._setStyle(gst, ctx);
  18643. this._draw(gst.pth, ctx);
  18644. ctx.fill();
  18645. };
  18646. exports.ToContext2D.prototype.Stroke = function (gst) {
  18647. if (this.currPage != this.needPage) return;
  18648. var ctx = this.ctx;
  18649. ctx.beginPath();
  18650. this._setStyle(gst, ctx);
  18651. this._draw(gst.pth, ctx);
  18652. ctx.stroke();
  18653. };
  18654. exports.ToContext2D.prototype.PutText = function (gst, str, stw) {
  18655. if (this.currPage != this.needPage) return;
  18656. var scl = this._scale(gst.ctm);
  18657. var ctx = this.ctx;
  18658. this._setStyle(gst, ctx);
  18659. ctx.save();
  18660. var m = [1, 0, 0, -1, 0, 0];
  18661. this._concat(m, gst.font.Tm);
  18662. this._concat(m, gst.ctm); //console.log(str, m, gst); throw "e";
  18663. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  18664. ctx.fillText(str, 0, 0);
  18665. ctx.restore();
  18666. };
  18667. exports.ToContext2D.prototype.PutImage = function (gst, buff, w, h, msk) {
  18668. if (this.currPage != this.needPage) return;
  18669. var ctx = this.ctx;
  18670. if (buff.length == w * h * 4) {
  18671. buff = buff.slice(0);
  18672. if (msk && msk.length == w * h * 4) for (var i = 0; i < buff.length; i += 4) {
  18673. buff[i + 3] = msk[i + 1];
  18674. }
  18675. var cnv = document.createElement("canvas"),
  18676. cctx = cnv.getContext("2d");
  18677. cnv.width = w;
  18678. cnv.height = h;
  18679. var imgd = cctx.createImageData(w, h);
  18680. for (var i = 0; i < buff.length; i++) {
  18681. imgd.data[i] = buff[i];
  18682. }
  18683. cctx.putImageData(imgd, 0, 0);
  18684. ctx.save();
  18685. var m = [1, 0, 0, 1, 0, 0];
  18686. this._concat(m, [1 / w, 0, 0, -1 / h, 0, 1]);
  18687. this._concat(m, gst.ctm);
  18688. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  18689. ctx.drawImage(cnv, 0, 0);
  18690. ctx.restore();
  18691. }
  18692. };
  18693. exports.ToContext2D.prototype.ShowPage = function () {
  18694. this.currPage++;
  18695. };
  18696. exports.ToContext2D.prototype.Done = function () { };
  18697. function _flt(n) {
  18698. return "" + parseFloat(n.toFixed(2));
  18699. }
  18700. exports.ToContext2D.prototype._setStyle = function (gst, ctx) {
  18701. var scl = this._scale(gst.ctm);
  18702. ctx.fillStyle = this._getFill(gst.colr, gst.ca, ctx);
  18703. ctx.strokeStyle = this._getFill(gst.COLR, gst.CA, ctx);
  18704. ctx.lineCap = ["butt", "round", "square"][gst.lcap];
  18705. ctx.lineJoin = ["miter", "round", "bevel"][gst.ljoin];
  18706. ctx.lineWidth = gst.lwidth * scl;
  18707. var dsh = gst.dash.slice(0);
  18708. for (var i = 0; i < dsh.length; i++) {
  18709. dsh[i] = _flt(dsh[i] * scl);
  18710. }
  18711. ctx.setLineDash(dsh);
  18712. ctx.miterLimit = gst.mlimit * scl;
  18713. var fn = gst.font.Tf,
  18714. ln = fn.toLowerCase();
  18715. var p0 = ln.indexOf("bold") != -1 ? "bold " : "";
  18716. var p1 = ln.indexOf("italic") != -1 || ln.indexOf("oblique") != -1 ? "italic " : "";
  18717. ctx.font = p0 + p1 + gst.font.Tfs + "px \"" + fn + "\"";
  18718. };
  18719. exports.ToContext2D.prototype._getFill = function (colr, ca, ctx) {
  18720. if (colr.typ == null) return this._colr(colr, ca); else {
  18721. var grd = colr,
  18722. crd = grd.crds,
  18723. mat = grd.mat,
  18724. scl = this._scale(mat),
  18725. gf;
  18726. if (grd.typ == "lin") {
  18727. var p0 = this._multPoint(mat, crd.slice(0, 2)),
  18728. p1 = this._multPoint(mat, crd.slice(2));
  18729. gf = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  18730. } else if (grd.typ == "rad") {
  18731. var p0 = this._multPoint(mat, crd.slice(0, 2)),
  18732. p1 = this._multPoint(mat, crd.slice(3));
  18733. gf = ctx.createRadialGradient(p0[0], p0[1], crd[2] * scl, p1[0], p1[1], crd[5] * scl);
  18734. }
  18735. for (var i = 0; i < grd.grad.length; i++) {
  18736. gf.addColorStop(grd.grad[i][0], this._colr(grd.grad[i][1], ca));
  18737. }
  18738. return gf;
  18739. }
  18740. };
  18741. exports.ToContext2D.prototype._colr = function (c, a) {
  18742. return "rgba(" + Math.round(c[0] * 255) + "," + Math.round(c[1] * 255) + "," + Math.round(c[2] * 255) + "," + a + ")";
  18743. };
  18744. exports.ToContext2D.prototype._scale = function (m) {
  18745. return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
  18746. };
  18747. exports.ToContext2D.prototype._concat = function (m, w) {
  18748. var a = m[0],
  18749. b = m[1],
  18750. c = m[2],
  18751. d = m[3],
  18752. tx = m[4],
  18753. ty = m[5];
  18754. m[0] = a * w[0] + b * w[2];
  18755. m[1] = a * w[1] + b * w[3];
  18756. m[2] = c * w[0] + d * w[2];
  18757. m[3] = c * w[1] + d * w[3];
  18758. m[4] = tx * w[0] + ty * w[2] + w[4];
  18759. m[5] = tx * w[1] + ty * w[3] + w[5];
  18760. };
  18761. exports.ToContext2D.prototype._multPoint = function (m, p) {
  18762. var x = p[0],
  18763. y = p[1];
  18764. return [x * m[0] + y * m[2] + m[4], x * m[1] + y * m[3] + m[5]];
  18765. }, exports.ToContext2D.prototype._draw = function (path, ctx) {
  18766. var c = 0,
  18767. crds = path.crds;
  18768. for (var j = 0; j < path.cmds.length; j++) {
  18769. var cmd = path.cmds[j];
  18770. if (cmd == "M") {
  18771. ctx.moveTo(crds[c], crds[c + 1]);
  18772. c += 2;
  18773. } else if (cmd == "L") {
  18774. ctx.lineTo(crds[c], crds[c + 1]);
  18775. c += 2;
  18776. } else if (cmd == "C") {
  18777. ctx.bezierCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3], crds[c + 4], crds[c + 5]);
  18778. c += 6;
  18779. } else if (cmd == "Q") {
  18780. ctx.quadraticCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3]);
  18781. c += 4;
  18782. } else if (cmd == "Z") {
  18783. ctx.closePath();
  18784. }
  18785. }
  18786. };
  18787. }, {}], 93: [function (require, module, exports) {
  18788. "use strict";
  18789. Object.defineProperty(exports, "__esModule", {
  18790. value: true
  18791. });
  18792. 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;
  18793. var constant_1 = require("./constant");
  18794. function getRangetxt(range, sheettxt) {
  18795. var row0 = range["row"][0],
  18796. row1 = range["row"][1];
  18797. var column0 = range["column"][0],
  18798. column1 = range["column"][1];
  18799. if (row0 == null && row1 == null) {
  18800. return sheettxt + chatatABC(column0) + ":" + chatatABC(column1);
  18801. } else if (column0 == null && column1 == null) {
  18802. return sheettxt + (row0 + 1) + ":" + (row1 + 1);
  18803. } else {
  18804. if (column0 == column1 && row0 == row1) {
  18805. return sheettxt + chatatABC(column0) + (row0 + 1);
  18806. } else {
  18807. return sheettxt + chatatABC(column0) + (row0 + 1) + ":" + chatatABC(column1) + (row1 + 1);
  18808. }
  18809. }
  18810. }
  18811. exports.getRangetxt = getRangetxt;
  18812. function getcellrange(txt, sheets, sheetId) {
  18813. if (sheets === void 0) {
  18814. sheets = {};
  18815. }
  18816. if (sheetId === void 0) {
  18817. sheetId = "1";
  18818. }
  18819. var val = txt.split("!");
  18820. var sheettxt = "",
  18821. rangetxt = "",
  18822. sheetIndex = -1;
  18823. if (val.length > 1) {
  18824. sheettxt = val[0];
  18825. rangetxt = val[1];
  18826. var si = sheets[sheettxt];
  18827. if (si == null) {
  18828. sheetIndex = parseInt(sheetId);
  18829. } else {
  18830. sheetIndex = parseInt(si);
  18831. }
  18832. } else {
  18833. sheetIndex = parseInt(sheetId);
  18834. rangetxt = val[0];
  18835. }
  18836. if (rangetxt.indexOf(":") == -1) {
  18837. var row = parseInt(rangetxt.replace(/[^0-9]/g, "")) - 1;
  18838. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  18839. if (!isNaN(row) && !isNaN(col)) {
  18840. return {
  18841. "row": [row, row],
  18842. "column": [col, col],
  18843. "sheetIndex": sheetIndex
  18844. };
  18845. } else {
  18846. return null;
  18847. }
  18848. } else {
  18849. var rangetxtArray = rangetxt.split(":");
  18850. var row = [],
  18851. col = [];
  18852. row[0] = parseInt(rangetxtArray[0].replace(/[^0-9]/g, "")) - 1;
  18853. row[1] = parseInt(rangetxtArray[1].replace(/[^0-9]/g, "")) - 1; // if (isNaN(row[0])) {
  18854. // row[0] = 0;
  18855. // }
  18856. // if (isNaN(row[1])) {
  18857. // row[1] = sheetdata.length - 1;
  18858. // }
  18859. if (row[0] > row[1]) {
  18860. return null;
  18861. }
  18862. col[0] = ABCatNum(rangetxtArray[0].replace(/[^A-Za-z]/g, ""));
  18863. col[1] = ABCatNum(rangetxtArray[1].replace(/[^A-Za-z]/g, "")); // if (isNaN(col[0])) {
  18864. // col[0] = 0;
  18865. // }
  18866. // if (isNaN(col[1])) {
  18867. // col[1] = sheetdata[0].length - 1;
  18868. // }
  18869. if (col[0] > col[1]) {
  18870. return null;
  18871. }
  18872. return {
  18873. "row": row,
  18874. "column": col,
  18875. "sheetIndex": sheetIndex
  18876. };
  18877. }
  18878. }
  18879. exports.getcellrange = getcellrange; //列下标 字母转数字
  18880. function ABCatNum(abc) {
  18881. abc = abc.toUpperCase();
  18882. var abc_len = abc.length;
  18883. if (abc_len == 0) {
  18884. return NaN;
  18885. }
  18886. var abc_array = abc.split("");
  18887. var wordlen = constant_1.columeHeader_word.length;
  18888. var ret = 0;
  18889. for (var i = abc_len - 1; i >= 0; i--) {
  18890. if (i == abc_len - 1) {
  18891. ret += constant_1.columeHeader_word_index[abc_array[i]];
  18892. } else {
  18893. ret += Math.pow(wordlen, abc_len - i - 1) * (constant_1.columeHeader_word_index[abc_array[i]] + 1);
  18894. }
  18895. }
  18896. return ret;
  18897. } //列下标 数字转字母
  18898. function chatatABC(index) {
  18899. var wordlen = constant_1.columeHeader_word.length;
  18900. if (index < wordlen) {
  18901. return constant_1.columeHeader_word[index];
  18902. } else {
  18903. var last = 0,
  18904. pre = 0,
  18905. ret = "";
  18906. var i = 1,
  18907. n = 0;
  18908. while (index >= wordlen / (wordlen - 1) * (Math.pow(wordlen, i++) - 1)) {
  18909. n = i;
  18910. }
  18911. var index_ab = index - wordlen / (wordlen - 1) * (Math.pow(wordlen, n - 1) - 1); //970
  18912. last = index_ab + 1;
  18913. for (var x = n; x > 0; x--) {
  18914. var last1 = last,
  18915. x1 = x; //-702=268, 3
  18916. if (x == 1) {
  18917. last1 = last1 % wordlen;
  18918. if (last1 == 0) {
  18919. last1 = 26;
  18920. }
  18921. return ret + constant_1.columeHeader_word[last1 - 1];
  18922. }
  18923. last1 = Math.ceil(last1 / Math.pow(wordlen, x - 1)); //last1 = last1 % wordlen;
  18924. ret += constant_1.columeHeader_word[last1 - 1];
  18925. if (x > 1) {
  18926. last = last - (last1 - 1) * wordlen;
  18927. }
  18928. }
  18929. }
  18930. }
  18931. /**
  18932. * @return ratio, default 0.75 1in = 2.54cm = 25.4mm = 72pt = 6pc, pt = 1/72 In, px = 1/dpi In
  18933. */
  18934. function getptToPxRatioByDPI() {
  18935. return 72 / 96;
  18936. }
  18937. exports.getptToPxRatioByDPI = getptToPxRatioByDPI;
  18938. /**
  18939. * @emus EMUs, Excel drawing unit
  18940. * @return pixel
  18941. */
  18942. function getPxByEMUs(emus) {
  18943. if (emus == null) {
  18944. return 0;
  18945. }
  18946. var inch = emus / 914400;
  18947. var pt = inch * 72;
  18948. var px = pt / getptToPxRatioByDPI();
  18949. return px;
  18950. }
  18951. exports.getPxByEMUs = getPxByEMUs;
  18952. /**
  18953. * @dom xml attribute object
  18954. * @attr attribute name
  18955. * @d if attribute is null, return default value
  18956. * @return attribute value
  18957. */
  18958. function getXmlAttibute(dom, attr, d) {
  18959. var value = dom[attr];
  18960. value = value == null ? d : value;
  18961. return value;
  18962. }
  18963. exports.getXmlAttibute = getXmlAttibute;
  18964. /**
  18965. * @columnWidth Excel column width
  18966. * @return pixel column width
  18967. */
  18968. function getColumnWidthPixel(columnWidth) {
  18969. var pix = Math.round((columnWidth - 0.83) * 8 + 5);
  18970. return pix;
  18971. }
  18972. exports.getColumnWidthPixel = getColumnWidthPixel;
  18973. /**
  18974. * @rowHeight Excel row height
  18975. * @return pixel row height
  18976. */
  18977. function getRowHeightPixel(rowHeight) {
  18978. var pix = Math.round(rowHeight / getptToPxRatioByDPI());
  18979. return pix;
  18980. }
  18981. exports.getRowHeightPixel = getRowHeightPixel;
  18982. function LightenDarkenColor(sixColor, tint) {
  18983. var hex = sixColor.substring(sixColor.length - 6, sixColor.length);
  18984. var rgbArray = hexToRgbArray("#" + hex);
  18985. var hslArray = rgbToHsl(rgbArray[0], rgbArray[1], rgbArray[2]);
  18986. if (tint > 0) {
  18987. hslArray[2] = hslArray[2] * (1.0 - tint) + tint;
  18988. } else if (tint < 0) {
  18989. hslArray[2] = hslArray[2] * (1.0 + tint);
  18990. } else {
  18991. return "#" + hex;
  18992. }
  18993. var newRgbArray = hslToRgb(hslArray[0], hslArray[1], hslArray[2]);
  18994. return rgbToHex("RGB(" + newRgbArray.join(",") + ")");
  18995. }
  18996. exports.LightenDarkenColor = LightenDarkenColor;
  18997. function rgbToHex(rgb) {
  18998. //十六进制颜色值的正则表达式
  18999. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是rgb颜色表示
  19000. if (/^(rgb|RGB)/.test(rgb)) {
  19001. var aColor = rgb.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
  19002. var strHex = "#";
  19003. for (var i = 0; i < aColor.length; i++) {
  19004. var hex = Number(aColor[i]).toString(16);
  19005. if (hex.length < 2) {
  19006. hex = '0' + hex;
  19007. }
  19008. strHex += hex;
  19009. }
  19010. if (strHex.length !== 7) {
  19011. strHex = rgb;
  19012. }
  19013. return strHex;
  19014. } else if (reg.test(rgb)) {
  19015. var aNum = rgb.replace(/#/, "").split("");
  19016. if (aNum.length === 6) {
  19017. return rgb;
  19018. } else if (aNum.length === 3) {
  19019. var numHex = "#";
  19020. for (var i = 0; i < aNum.length; i += 1) {
  19021. numHex += aNum[i] + aNum[i];
  19022. }
  19023. return numHex;
  19024. }
  19025. }
  19026. return rgb;
  19027. }
  19028. function hexToRgb(hex) {
  19029. var sColor = hex.toLowerCase(); //十六进制颜色值的正则表达式
  19030. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是16进制颜色
  19031. if (sColor && reg.test(sColor)) {
  19032. if (sColor.length === 4) {
  19033. var sColorNew = "#";
  19034. for (var i = 1; i < 4; i += 1) {
  19035. sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
  19036. }
  19037. sColor = sColorNew;
  19038. } //处理六位的颜色值
  19039. var sColorChange = [];
  19040. for (var i = 1; i < 7; i += 2) {
  19041. sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
  19042. }
  19043. return "RGB(" + sColorChange.join(",") + ")";
  19044. }
  19045. return sColor;
  19046. }
  19047. function hexToRgbArray(hex) {
  19048. var sColor = hex.toLowerCase(); //十六进制颜色值的正则表达式
  19049. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 如果是16进制颜色
  19050. if (sColor && reg.test(sColor)) {
  19051. if (sColor.length === 4) {
  19052. var sColorNew = "#";
  19053. for (var i = 1; i < 4; i += 1) {
  19054. sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
  19055. }
  19056. sColor = sColorNew;
  19057. } //处理六位的颜色值
  19058. var sColorChange = [];
  19059. for (var i = 1; i < 7; i += 2) {
  19060. sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
  19061. }
  19062. return sColorChange;
  19063. }
  19064. return null;
  19065. }
  19066. /**
  19067. * HSL颜色值转换为RGB.
  19068. * 换算公式改编自 http://en.wikipedia.org/wiki/HSL_color_space.
  19069. * h, s, 和 l 设定在 [0, 1] 之间
  19070. * 返回的 r, g, 和 b 在 [0, 255]之间
  19071. *
  19072. * @param Number h 色相
  19073. * @param Number s 饱和度
  19074. * @param Number l 亮度
  19075. * @return Array RGB色值数值
  19076. */
  19077. function hslToRgb(h, s, l) {
  19078. var r, g, b;
  19079. if (s == 0) {
  19080. r = g = b = l; // achromatic
  19081. } else {
  19082. var hue2rgb = function hue2rgb(p, q, t) {
  19083. if (t < 0) t += 1;
  19084. if (t > 1) t -= 1;
  19085. if (t < 1 / 6) return p + (q - p) * 6 * t;
  19086. if (t < 1 / 2) return q;
  19087. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  19088. return p;
  19089. };
  19090. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  19091. var p = 2 * l - q;
  19092. r = hue2rgb(p, q, h + 1 / 3);
  19093. g = hue2rgb(p, q, h);
  19094. b = hue2rgb(p, q, h - 1 / 3);
  19095. }
  19096. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  19097. }
  19098. /**
  19099. * RGB 颜色值转换为 HSL.
  19100. * 转换公式参考自 http://en.wikipedia.org/wiki/HSL_color_space.
  19101. * r, g, 和 b 需要在 [0, 255] 范围内
  19102. * 返回的 h, s, 和 l 在 [0, 1] 之间
  19103. *
  19104. * @param Number r 红色色值
  19105. * @param Number g 绿色色值
  19106. * @param Number b 蓝色色值
  19107. * @return Array HSL各值数组
  19108. */
  19109. function rgbToHsl(r, g, b) {
  19110. r /= 255, g /= 255, b /= 255;
  19111. var max = Math.max(r, g, b),
  19112. min = Math.min(r, g, b);
  19113. var h,
  19114. s,
  19115. l = (max + min) / 2;
  19116. if (max == min) {
  19117. h = s = 0; // achromatic
  19118. } else {
  19119. var d = max - min;
  19120. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  19121. switch (max) {
  19122. case r:
  19123. h = (g - b) / d + (g < b ? 6 : 0);
  19124. break;
  19125. case g:
  19126. h = (b - r) / d + 2;
  19127. break;
  19128. case b:
  19129. h = (r - g) / d + 4;
  19130. break;
  19131. }
  19132. h /= 6;
  19133. }
  19134. return [h, s, l];
  19135. }
  19136. function generateRandomIndex(prefix) {
  19137. if (prefix == null) {
  19138. prefix = "Sheet";
  19139. }
  19140. var userAgent = window.navigator.userAgent.replace(/[^a-zA-Z0-9]/g, "").split("");
  19141. var mid = "";
  19142. for (var i = 0; i < 5; i++) {
  19143. mid += userAgent[Math.round(Math.random() * (userAgent.length - 1))];
  19144. }
  19145. var time = new Date().getTime();
  19146. return prefix + "_" + mid + "_" + time;
  19147. }
  19148. exports.generateRandomIndex = generateRandomIndex;
  19149. function escapeCharacter(str) {
  19150. if (str == null || str.length == 0) {
  19151. return str;
  19152. }
  19153. 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, "ÿ");
  19154. }
  19155. exports.escapeCharacter = escapeCharacter;
  19156. var fromulaRef =
  19157. /** @class */
  19158. function () {
  19159. function fromulaRef() { }
  19160. fromulaRef.trim = function (str) {
  19161. if (str == null) {
  19162. str = "";
  19163. }
  19164. return str.replace(/(^\s*)|(\s*$)/g, "");
  19165. };
  19166. fromulaRef.functionCopy = function (txt, mode, step) {
  19167. var _this = this;
  19168. if (_this.operatorjson == null) {
  19169. var arr = _this.operator.split("|"),
  19170. op = {};
  19171. for (var i_1 = 0; i_1 < arr.length; i_1++) {
  19172. op[arr[i_1].toString()] = 1;
  19173. }
  19174. _this.operatorjson = op;
  19175. }
  19176. if (mode == null) {
  19177. mode = "down";
  19178. }
  19179. if (step == null) {
  19180. step = 1;
  19181. }
  19182. if (txt.substr(0, 1) == "=") {
  19183. txt = txt.substr(1);
  19184. }
  19185. var funcstack = txt.split("");
  19186. var i = 0,
  19187. str = "",
  19188. function_str = "",
  19189. ispassby = true;
  19190. var matchConfig = {
  19191. "bracket": 0,
  19192. "comma": 0,
  19193. "squote": 0,
  19194. "dquote": 0
  19195. };
  19196. while (i < funcstack.length) {
  19197. var s = funcstack[i];
  19198. if (s == "(" && matchConfig.dquote == 0) {
  19199. matchConfig.bracket += 1;
  19200. if (str.length > 0) {
  19201. function_str += str + "(";
  19202. } else {
  19203. function_str += "(";
  19204. }
  19205. str = "";
  19206. } else if (s == ")" && matchConfig.dquote == 0) {
  19207. matchConfig.bracket -= 1;
  19208. function_str += _this.functionCopy(str, mode, step) + ")";
  19209. str = "";
  19210. } else if (s == '"' && matchConfig.squote == 0) {
  19211. if (matchConfig.dquote > 0) {
  19212. function_str += str + '"';
  19213. matchConfig.dquote -= 1;
  19214. str = "";
  19215. } else {
  19216. matchConfig.dquote += 1;
  19217. str += '"';
  19218. }
  19219. } else if (s == ',' && matchConfig.dquote == 0) {
  19220. function_str += _this.functionCopy(str, mode, step) + ',';
  19221. str = "";
  19222. } else if (s == '&' && matchConfig.dquote == 0) {
  19223. if (str.length > 0) {
  19224. function_str += _this.functionCopy(str, mode, step) + "&";
  19225. str = "";
  19226. } else {
  19227. function_str += "&";
  19228. }
  19229. } else if (s in _this.operatorjson && matchConfig.dquote == 0) {
  19230. var s_next = "";
  19231. if (i + 1 < funcstack.length) {
  19232. s_next = funcstack[i + 1];
  19233. }
  19234. var p = i - 1,
  19235. s_pre = null;
  19236. if (p >= 0) {
  19237. do {
  19238. s_pre = funcstack[p--];
  19239. } while (p >= 0 && s_pre == " ");
  19240. }
  19241. if (s + s_next in _this.operatorjson) {
  19242. if (str.length > 0) {
  19243. function_str += _this.functionCopy(str, mode, step) + s + s_next;
  19244. str = "";
  19245. } else {
  19246. function_str += s + s_next;
  19247. }
  19248. i++;
  19249. } else if (!/[^0-9]/.test(s_next) && s == "-" && (s_pre == "(" || s_pre == null || s_pre == "," || s_pre == " " || s_pre in _this.operatorjson)) {
  19250. str += s;
  19251. } else {
  19252. if (str.length > 0) {
  19253. function_str += _this.functionCopy(str, mode, step) + s;
  19254. str = "";
  19255. } else {
  19256. function_str += s;
  19257. }
  19258. }
  19259. } else {
  19260. str += s;
  19261. }
  19262. if (i == funcstack.length - 1) {
  19263. if (_this.iscelldata(_this.trim(str))) {
  19264. if (mode == "down") {
  19265. function_str += _this.downparam(_this.trim(str), step);
  19266. } else if (mode == "up") {
  19267. function_str += _this.upparam(_this.trim(str), step);
  19268. } else if (mode == "left") {
  19269. function_str += _this.leftparam(_this.trim(str), step);
  19270. } else if (mode == "right") {
  19271. function_str += _this.rightparam(_this.trim(str), step);
  19272. }
  19273. } else {
  19274. function_str += _this.trim(str);
  19275. }
  19276. }
  19277. i++;
  19278. }
  19279. return function_str;
  19280. };
  19281. fromulaRef.downparam = function (txt, step) {
  19282. return this.updateparam("d", txt, step);
  19283. };
  19284. fromulaRef.upparam = function (txt, step) {
  19285. return this.updateparam("u", txt, step);
  19286. };
  19287. fromulaRef.leftparam = function (txt, step) {
  19288. return this.updateparam("l", txt, step);
  19289. };
  19290. fromulaRef.rightparam = function (txt, step) {
  19291. return this.updateparam("r", txt, step);
  19292. };
  19293. fromulaRef.updateparam = function (orient, txt, step) {
  19294. var _this = this;
  19295. var val = txt.split("!"),
  19296. rangetxt,
  19297. prefix = "";
  19298. if (val.length > 1) {
  19299. rangetxt = val[1];
  19300. prefix = val[0] + "!";
  19301. } else {
  19302. rangetxt = val[0];
  19303. }
  19304. if (rangetxt.indexOf(":") == -1) {
  19305. var row = parseInt(rangetxt.replace(/[^0-9]/g, ""));
  19306. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  19307. var freezonFuc = _this.isfreezonFuc(rangetxt);
  19308. var $row = freezonFuc[0] ? "$" : "",
  19309. $col = freezonFuc[1] ? "$" : "";
  19310. if (orient == "u" && !freezonFuc[0]) {
  19311. row -= step;
  19312. } else if (orient == "r" && !freezonFuc[1]) {
  19313. col += step;
  19314. } else if (orient == "l" && !freezonFuc[1]) {
  19315. col -= step;
  19316. } else if (!freezonFuc[0]) {
  19317. row += step;
  19318. }
  19319. if (row < 0 || col < 0) {
  19320. return _this.error.r;
  19321. }
  19322. if (!isNaN(row) && !isNaN(col)) {
  19323. return prefix + $col + chatatABC(col) + $row + row;
  19324. } else if (!isNaN(row)) {
  19325. return prefix + $row + row;
  19326. } else if (!isNaN(col)) {
  19327. return prefix + $col + chatatABC(col);
  19328. } else {
  19329. return txt;
  19330. }
  19331. } else {
  19332. rangetxt = rangetxt.split(":");
  19333. var row = [],
  19334. col = [];
  19335. row[0] = parseInt(rangetxt[0].replace(/[^0-9]/g, ""));
  19336. row[1] = parseInt(rangetxt[1].replace(/[^0-9]/g, ""));
  19337. if (row[0] > row[1]) {
  19338. return txt;
  19339. }
  19340. col[0] = ABCatNum(rangetxt[0].replace(/[^A-Za-z]/g, ""));
  19341. col[1] = ABCatNum(rangetxt[1].replace(/[^A-Za-z]/g, ""));
  19342. if (col[0] > col[1]) {
  19343. return txt;
  19344. }
  19345. var freezonFuc0 = _this.isfreezonFuc(rangetxt[0]);
  19346. var freezonFuc1 = _this.isfreezonFuc(rangetxt[1]);
  19347. var $row0 = freezonFuc0[0] ? "$" : "",
  19348. $col0 = freezonFuc0[1] ? "$" : "";
  19349. var $row1 = freezonFuc1[0] ? "$" : "",
  19350. $col1 = freezonFuc1[1] ? "$" : "";
  19351. if (orient == "u") {
  19352. if (!freezonFuc0[0]) {
  19353. row[0] -= step;
  19354. }
  19355. if (!freezonFuc1[0]) {
  19356. row[1] -= step;
  19357. }
  19358. } else if (orient == "r") {
  19359. if (!freezonFuc0[1]) {
  19360. col[0] += step;
  19361. }
  19362. if (!freezonFuc1[1]) {
  19363. col[1] += step;
  19364. }
  19365. } else if (orient == "l") {
  19366. if (!freezonFuc0[1]) {
  19367. col[0] -= step;
  19368. }
  19369. if (!freezonFuc1[1]) {
  19370. col[1] -= step;
  19371. }
  19372. } else {
  19373. if (!freezonFuc0[0]) {
  19374. row[0] += step;
  19375. }
  19376. if (!freezonFuc1[0]) {
  19377. row[1] += step;
  19378. }
  19379. }
  19380. if (row[0] < 0 || col[0] < 0) {
  19381. return _this.error.r;
  19382. }
  19383. if (isNaN(col[0]) && isNaN(col[1])) {
  19384. return prefix + $row0 + row[0] + ":" + $row1 + row[1];
  19385. } else if (isNaN(row[0]) && isNaN(row[1])) {
  19386. return prefix + $col0 + chatatABC(col[0]) + ":" + $col1 + chatatABC(col[1]);
  19387. } else {
  19388. return prefix + $col0 + chatatABC(col[0]) + $row0 + row[0] + ":" + $col1 + chatatABC(col[1]) + $row1 + row[1];
  19389. }
  19390. }
  19391. };
  19392. fromulaRef.iscelldata = function (txt) {
  19393. var val = txt.split("!"),
  19394. rangetxt;
  19395. if (val.length > 1) {
  19396. rangetxt = val[1];
  19397. } else {
  19398. rangetxt = val[0];
  19399. }
  19400. var reg_cell = /^(([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+))$/g; //增加正则判断单元格为字母+数字的格式:如 A1:B3
  19401. var reg_cellRange = /^(((([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+)))|((([a-zA-Z]+)|([$][a-zA-Z]+))))$/g; //增加正则判断单元格为字母+数字或字母的格式:如 A1:B3,A:A
  19402. if (rangetxt.indexOf(":") == -1) {
  19403. var row = parseInt(rangetxt.replace(/[^0-9]/g, "")) - 1;
  19404. var col = ABCatNum(rangetxt.replace(/[^A-Za-z]/g, ""));
  19405. if (!isNaN(row) && !isNaN(col) && rangetxt.toString().match(reg_cell)) {
  19406. return true;
  19407. } else if (!isNaN(row)) {
  19408. return false;
  19409. } else if (!isNaN(col)) {
  19410. return false;
  19411. } else {
  19412. return false;
  19413. }
  19414. } else {
  19415. reg_cellRange = /^(((([a-zA-Z]+)|([$][a-zA-Z]+))(([0-9]+)|([$][0-9]+)))|((([a-zA-Z]+)|([$][a-zA-Z]+)))|((([0-9]+)|([$][0-9]+s))))$/g;
  19416. rangetxt = rangetxt.split(":");
  19417. var row = [],
  19418. col = [];
  19419. row[0] = parseInt(rangetxt[0].replace(/[^0-9]/g, "")) - 1;
  19420. row[1] = parseInt(rangetxt[1].replace(/[^0-9]/g, "")) - 1;
  19421. if (row[0] > row[1]) {
  19422. return false;
  19423. }
  19424. col[0] = ABCatNum(rangetxt[0].replace(/[^A-Za-z]/g, ""));
  19425. col[1] = ABCatNum(rangetxt[1].replace(/[^A-Za-z]/g, ""));
  19426. if (col[0] > col[1]) {
  19427. return false;
  19428. }
  19429. if (rangetxt[0].toString().match(reg_cellRange) && rangetxt[1].toString().match(reg_cellRange)) {
  19430. return true;
  19431. } else {
  19432. return false;
  19433. }
  19434. }
  19435. };
  19436. fromulaRef.isfreezonFuc = function (txt) {
  19437. var row = txt.replace(/[^0-9]/g, "");
  19438. var col = txt.replace(/[^A-Za-z]/g, "");
  19439. var row$ = txt.substr(txt.indexOf(row) - 1, 1);
  19440. var col$ = txt.substr(txt.indexOf(col) - 1, 1);
  19441. var ret = [false, false];
  19442. if (row$ == "$") {
  19443. ret[0] = true;
  19444. }
  19445. if (col$ == "$") {
  19446. ret[1] = true;
  19447. }
  19448. return ret;
  19449. };
  19450. fromulaRef.operator = '==|!=|<>|<=|>=|=|+|-|>|<|/|*|%|&|^';
  19451. fromulaRef.error = {
  19452. v: "#VALUE!",
  19453. n: "#NAME?",
  19454. na: "#N/A",
  19455. r: "#REF!",
  19456. d: "#DIV/0!",
  19457. nm: "#NUM!",
  19458. nl: "#NULL!",
  19459. sp: "#SPILL!" //数组范围有其它值
  19460. };
  19461. fromulaRef.operatorjson = null;
  19462. return fromulaRef;
  19463. }();
  19464. exports.fromulaRef = fromulaRef;
  19465. function isChinese(temp) {
  19466. var re = /[^\u4e00-\u9fa5]/;
  19467. 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]/;
  19468. if (reg.test(temp)) return true;
  19469. if (re.test(temp)) return false;
  19470. return true;
  19471. }
  19472. exports.isChinese = isChinese;
  19473. function isJapanese(temp) {
  19474. var re = /[^\u0800-\u4e00]/;
  19475. if (re.test(temp)) return false;
  19476. return true;
  19477. }
  19478. exports.isJapanese = isJapanese;
  19479. function isKoera(chr) {
  19480. if (chr > 0x3130 && chr < 0x318F || chr >= 0xAC00 && chr <= 0xD7A3) {
  19481. return true;
  19482. }
  19483. return false;
  19484. }
  19485. exports.isKoera = isKoera;
  19486. function isContainMultiType(str) {
  19487. var isUnicode = false;
  19488. if (escape(str).indexOf("%u") > -1) {
  19489. isUnicode = true;
  19490. }
  19491. var isNot = false;
  19492. var reg = /[0-9a-z]/gi;
  19493. if (reg.test(str)) {
  19494. isNot = true;
  19495. }
  19496. var reEnSign = /[\x00-\xff]+/g;
  19497. if (reEnSign.test(str)) {
  19498. isNot = true;
  19499. }
  19500. if (isUnicode && isNot) {
  19501. return true;
  19502. }
  19503. return false;
  19504. }
  19505. exports.isContainMultiType = isContainMultiType;
  19506. function getBinaryContent(path, options) {
  19507. var promise, resolve, reject;
  19508. var callback;
  19509. if (!options) {
  19510. options = {};
  19511. } // taken from jQuery
  19512. var createStandardXHR = function createStandardXHR() {
  19513. try {
  19514. return new window.XMLHttpRequest();
  19515. } catch (e) { }
  19516. };
  19517. var createActiveXHR = function createActiveXHR() {
  19518. try {
  19519. return new window.ActiveXObject("Microsoft.XMLHTTP");
  19520. } catch (e) { }
  19521. }; // Create the request object
  19522. var createXHR = typeof window !== "undefined" && window.ActiveXObject ?
  19523. /* Microsoft failed to properly
  19524. * implement the XMLHttpRequest in IE7 (can't request local files),
  19525. * so we use the ActiveXObject when it is available
  19526. * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
  19527. * we need a fallback.
  19528. */
  19529. function () {
  19530. return createStandardXHR() || createActiveXHR();
  19531. } : // For all other browsers, use the standard XMLHttpRequest object
  19532. createStandardXHR; // backward compatible callback
  19533. if (typeof options === "function") {
  19534. callback = options;
  19535. options = {};
  19536. } else if (typeof options.callback === 'function') {
  19537. // callback inside options object
  19538. callback = options.callback;
  19539. }
  19540. resolve = function resolve(data) {
  19541. callback(null, data);
  19542. };
  19543. reject = function reject(err) {
  19544. callback(err, null);
  19545. };
  19546. try {
  19547. var xhr = createXHR();
  19548. xhr.open('GET', path, true); // recent browsers
  19549. if ("responseType" in xhr) {
  19550. xhr.responseType = "arraybuffer";
  19551. } // older browser
  19552. if (xhr.overrideMimeType) {
  19553. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  19554. }
  19555. xhr.onreadystatechange = function (event) {
  19556. // use `xhr` and not `this`... thanks IE
  19557. if (xhr.readyState === 4) {
  19558. if (xhr.status === 200 || xhr.status === 0) {
  19559. try {
  19560. resolve(function (xhr) {
  19561. // for xhr.responseText, the 0xFF mask is applied by JSZip
  19562. return xhr.response || xhr.responseText;
  19563. }(xhr));
  19564. } catch (err) {
  19565. reject(new Error(err));
  19566. }
  19567. } else {
  19568. reject(new Error("Ajax error for " + path + " : " + this.status + " " + this.statusText));
  19569. }
  19570. }
  19571. };
  19572. if (options.progress) {
  19573. xhr.onprogress = function (e) {
  19574. options.progress({
  19575. path: path,
  19576. originalEvent: e,
  19577. percent: e.loaded / e.total * 100,
  19578. loaded: e.loaded,
  19579. total: e.total
  19580. });
  19581. };
  19582. }
  19583. xhr.send();
  19584. } catch (e) {
  19585. reject(new Error(e), null);
  19586. } // returns a promise or undefined depending on whether a callback was
  19587. // provided
  19588. return promise;
  19589. }
  19590. exports.getBinaryContent = getBinaryContent;
  19591. }, { "./constant": 91 }], 94: [function (require, module, exports) {
  19592. "use strict";
  19593. Object.defineProperty(exports, "__esModule", {
  19594. value: true
  19595. });
  19596. exports.LuckyExcel = void 0;
  19597. var LuckyFile_1 = require("./ToLuckySheet/LuckyFile"); // import {SecurityDoor,Car} from './content';
  19598. var HandleZip_1 = require("./HandleZip"); // //demo
  19599. // function demoHandler(){
  19600. // let upload = document.getElementById("Luckyexcel-demo-file");
  19601. // let selectADemo = document.getElementById("Luckyexcel-select-demo");
  19602. // let downlodDemo = document.getElementById("Luckyexcel-downlod-file");
  19603. // let mask = document.getElementById("lucky-mask-demo");
  19604. // if(upload){
  19605. // window.onload = () => {
  19606. // upload.addEventListener("change", function(evt){
  19607. // var files:FileList = (evt.target as any).files;
  19608. // if(files==null || files.length==0){
  19609. // alert("No files wait for import");
  19610. // return;
  19611. // }
  19612. // let name = files[0].name;
  19613. // let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
  19614. // if(suffix!="xlsx"){
  19615. // alert("Currently only supports the import of xlsx files");
  19616. // return;
  19617. // }
  19618. // LuckyExcel.transformExcelToLucky(files[0], function(exportJson:any, luckysheetfile:string){
  19619. // if(exportJson.sheets==null || exportJson.sheets.length==0){
  19620. // alert("Failed to read the content of the excel file, currently does not support xls files!");
  19621. // return;
  19622. // }
  19623. // console.log(exportJson, luckysheetfile);
  19624. // window.luckysheet.destroy();
  19625. // window.luckysheet.create({
  19626. // container: 'luckysheet', //luckysheet is the container id
  19627. // showinfobar:false,
  19628. // data:exportJson.sheets,
  19629. // title:exportJson.info.name,
  19630. // userInfo:exportJson.info.name.creator
  19631. // });
  19632. // });
  19633. // });
  19634. // selectADemo.addEventListener("change", function(evt){
  19635. // var obj:any = selectADemo;
  19636. // var index = obj.selectedIndex;
  19637. // var value = obj.options[index].value;
  19638. // var name = obj.options[index].innerHTML;
  19639. // if(value==""){
  19640. // return;
  19641. // }
  19642. // mask.style.display = "flex";
  19643. // LuckyExcel.transformExcelToLuckyByUrl(value, name, function(exportJson:any, luckysheetfile:string){
  19644. // if(exportJson.sheets==null || exportJson.sheets.length==0){
  19645. // alert("Failed to read the content of the excel file, currently does not support xls files!");
  19646. // return;
  19647. // }
  19648. // console.log(exportJson, luckysheetfile);
  19649. // mask.style.display = "none";
  19650. // window.luckysheet.destroy();
  19651. // window.luckysheet.create({
  19652. // container: 'luckysheet', //luckysheet is the container id
  19653. // showinfobar:false,
  19654. // data:exportJson.sheets,
  19655. // title:exportJson.info.name,
  19656. // userInfo:exportJson.info.name.creator
  19657. // });
  19658. // });
  19659. // });
  19660. // downlodDemo.addEventListener("click", function(evt){
  19661. // var obj:any = selectADemo;
  19662. // var index = obj.selectedIndex;
  19663. // var value = obj.options[index].value;
  19664. // if(value.length==0){
  19665. // alert("Please select a demo file");
  19666. // return;
  19667. // }
  19668. // var elemIF:any = document.getElementById("Lucky-download-frame");
  19669. // if(elemIF==null){
  19670. // elemIF = document.createElement("iframe");
  19671. // elemIF.style.display = "none";
  19672. // elemIF.id = "Lucky-download-frame";
  19673. // document.body.appendChild(elemIF);
  19674. // }
  19675. // elemIF.src = value;
  19676. // // elemIF.parentNode.removeChild(elemIF);
  19677. // });
  19678. // }
  19679. // }
  19680. // }
  19681. // demoHandler();
  19682. // api
  19683. var LuckyExcel =
  19684. /** @class */
  19685. function () {
  19686. function LuckyExcel() { }
  19687. LuckyExcel.transformExcelToLucky = function (excelFile, callBack) {
  19688. var handleZip = new HandleZip_1.HandleZip(excelFile);
  19689. handleZip.unzipFile(function (files) {
  19690. var luckyFile = new LuckyFile_1.LuckyFile(files, excelFile.name);
  19691. var luckysheetfile = luckyFile.Parse();
  19692. var exportJson = JSON.parse(luckysheetfile);
  19693. if (callBack != undefined) {
  19694. callBack(exportJson, luckysheetfile);
  19695. }
  19696. }, function (err) {
  19697. console.error(err);
  19698. });
  19699. };
  19700. LuckyExcel.transformExcelToLuckyByUrl = function (url, name, callBack) {
  19701. var handleZip = new HandleZip_1.HandleZip();
  19702. handleZip.unzipFileByUrl(url, function (files) {
  19703. var luckyFile = new LuckyFile_1.LuckyFile(files, name);
  19704. var luckysheetfile = luckyFile.Parse();
  19705. var exportJson = JSON.parse(luckysheetfile);
  19706. if (callBack != undefined) {
  19707. callBack(exportJson, luckysheetfile);
  19708. }
  19709. }, function (err) {
  19710. console.error(err);
  19711. });
  19712. };
  19713. LuckyExcel.transformLuckyToExcel = function (LuckyFile, callBack) { };
  19714. return LuckyExcel;
  19715. }();
  19716. exports.LuckyExcel = LuckyExcel;
  19717. }, { "./HandleZip": 84, "./ToLuckySheet/LuckyFile": 87 }], 95: [function (require, module, exports) {
  19718. "use strict";
  19719. var main_1 = require("./main");
  19720. module.exports = main_1.LuckyExcel;
  19721. }, { "./main": 94 }]
  19722. }, {}, [95])(95)
  19723. });