mammoth.browser.js 972 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386
  1. // Module: [email protected]
  2. // License: MIT
  3. //
  4. // Module: [email protected]
  5. // License: MIT
  6. //
  7. // Module: [email protected]
  8. // License: MIT
  9. //
  10. // Module: [email protected]
  11. // License: MIT
  12. //
  13. // Module: [email protected]
  14. // License: MIT
  15. //
  16. // Module: [email protected]
  17. // License: MIT
  18. //
  19. // Module: [email protected]
  20. // License: MIT
  21. //
  22. // Module: [email protected]
  23. // License: ISC
  24. //
  25. // Module: [email protected]
  26. // License: MIT
  27. //
  28. // Module: [email protected]
  29. // License: MIT
  30. //
  31. // Module: [email protected]
  32. // License: MIT or GPLv3
  33. //
  34. // Module: [email protected]
  35. // License: MIT
  36. //
  37. // Module: [email protected]
  38. // License: BSD
  39. //
  40. // Module: [email protected]
  41. // License: BSD-2-Clause
  42. //
  43. // Module: [email protected]
  44. // License: BSD
  45. //
  46. // Module: [email protected]
  47. // License: MIT
  48. //
  49. // Module: [email protected]
  50. // License: MIT
  51. //
  52. // Module: [email protected]
  53. // License: MIT
  54. //
  55. // Module: [email protected]
  56. // License: MIT
  57. //
  58. // Module: [email protected]
  59. // License: MIT
  60. //
  61. // Module: [email protected]
  62. // License: ISC
  63. //
  64. // Module: [email protected]
  65. // License: MIT
  66. //
  67. // Module: [email protected]
  68. // License: MIT
  69. //
  70. // Module: [email protected]
  71. // License: MIT
  72. //
  73. // Module: [email protected]
  74. // License: MIT
  75. //
  76. // Module: [email protected]
  77. // License: MIT
  78. //
  79. // Module: [email protected]
  80. // License: MIT
  81. //
  82. // Module: [email protected]
  83. // License: MIT
  84. //
  85. (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.mammoth = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  86. var promises = require("../../lib/promises");
  87. exports.Files = Files;
  88. function Files() {
  89. function read(uri) {
  90. return promises.reject(new Error("could not open external image: '" + uri + "'\ncannot open linked files from a web browser"));
  91. }
  92. return {
  93. read: read
  94. };
  95. }
  96. },{"../../lib/promises":24}],2:[function(require,module,exports){
  97. var promises = require("../lib/promises");
  98. var zipfile = require("../lib/zipfile");
  99. exports.openZip = openZip;
  100. function openZip(options) {
  101. if (options.arrayBuffer) {
  102. return promises.resolve(zipfile.openArrayBuffer(options.arrayBuffer));
  103. } else {
  104. return promises.reject(new Error("Could not find file in options"));
  105. }
  106. }
  107. },{"../lib/promises":24,"../lib/zipfile":36}],3:[function(require,module,exports){
  108. exports.paragraph = paragraph;
  109. exports.run = run;
  110. exports.bold = new Matcher("bold");
  111. exports.italic = new Matcher("italic");
  112. exports.underline = new Matcher("underline");
  113. exports.strikethrough = new Matcher("strikethrough");
  114. exports.commentReference = new Matcher("commentReference");
  115. function paragraph(options) {
  116. return new Matcher("paragraph", options);
  117. }
  118. function run(options) {
  119. return new Matcher("run", options);
  120. }
  121. function Matcher(elementType, options) {
  122. options = options || {};
  123. this._elementType = elementType;
  124. this._styleId = options.styleId;
  125. this._styleName = options.styleName;
  126. if (options.list) {
  127. this._listIndex = options.list.levelIndex;
  128. this._listIsOrdered = options.list.isOrdered;
  129. }
  130. }
  131. Matcher.prototype.matches = function(element) {
  132. return element.type === this._elementType &&
  133. (this._styleId === undefined || element.styleId === this._styleId) &&
  134. (this._styleName === undefined || (element.styleName && element.styleName.toUpperCase() === this._styleName.toUpperCase())) &&
  135. (this._listIndex === undefined || isList(element, this._listIndex, this._listIsOrdered));
  136. };
  137. function isList(element, levelIndex, isOrdered) {
  138. return element.numbering &&
  139. element.numbering.level == levelIndex &&
  140. element.numbering.isOrdered == isOrdered;
  141. }
  142. },{}],4:[function(require,module,exports){
  143. var _ = require("underscore");
  144. var promises = require("./promises");
  145. var documents = require("./documents");
  146. var htmlPaths = require("./html-paths");
  147. var results = require("./results");
  148. var images = require("./images");
  149. var Html = require("./html");
  150. var writers = require("./writers");
  151. exports.DocumentConverter = DocumentConverter;
  152. function DocumentConverter(options) {
  153. return {
  154. convertToHtml: function(element) {
  155. var comments = _.indexBy(
  156. element.type === documents.types.document ? element.comments : [],
  157. "commentId"
  158. );
  159. var conversion = new DocumentConversion(options, comments);
  160. return conversion.convertToHtml(element);
  161. }
  162. };
  163. }
  164. function DocumentConversion(options, comments) {
  165. var noteNumber = 1;
  166. var noteReferences = [];
  167. var referencedComments = [];
  168. options = _.extend({ignoreEmptyParagraphs: true}, options);
  169. var idPrefix = options.idPrefix === undefined ? "" : options.idPrefix;
  170. var defaultParagraphStyle = htmlPaths.topLevelElement("p");
  171. var styleMap = options.styleMap || [];
  172. function convertToHtml(document) {
  173. var messages = [];
  174. var html = elementToHtml(document, messages);
  175. var deferredNodes = [];
  176. walkHtml(html, function(node) {
  177. if (node.type === "deferred") {
  178. deferredNodes.push(node);
  179. }
  180. });
  181. var deferredValues = {};
  182. return promises.mapSeries(deferredNodes, function(deferred) {
  183. return deferred.value().then(function(value) {
  184. deferredValues[deferred.id] = value;
  185. });
  186. }).then(function() {
  187. function replaceDeferred(nodes) {
  188. return flatMap(nodes, function(node) {
  189. if (node.type === "deferred") {
  190. return deferredValues[node.id];
  191. } else if (node.children) {
  192. return [
  193. _.extend({}, node, {
  194. children: replaceDeferred(node.children)
  195. })
  196. ];
  197. } else {
  198. return [node];
  199. }
  200. });
  201. }
  202. var writer = writers.writer({
  203. prettyPrint: options.prettyPrint,
  204. outputFormat: options.outputFormat
  205. });
  206. Html.write(writer, Html.simplify(replaceDeferred(html)));
  207. return new results.Result(writer.asString(), messages);
  208. });
  209. }
  210. function convertElements(elements, messages) {
  211. return flatMap(elements, function(element) {
  212. return elementToHtml(element, messages);
  213. });
  214. }
  215. function elementToHtml(element, messages) {
  216. var handler = elementConverters[element.type];
  217. if (handler) {
  218. return handler(element, messages);
  219. } else {
  220. return [];
  221. }
  222. }
  223. function convertParagraph(element, messages) {
  224. return htmlPathForParagraph(element, messages).wrap(function() {
  225. var content = convertElements(element.children, messages);
  226. if (options.ignoreEmptyParagraphs) {
  227. return content;
  228. } else {
  229. return [Html.forceWrite].concat(content);
  230. }
  231. });
  232. }
  233. function htmlPathForParagraph(element, messages) {
  234. var style = findStyle(element);
  235. if (style) {
  236. return style.to;
  237. } else {
  238. if (element.styleId) {
  239. messages.push(unrecognisedStyleWarning("paragraph", element));
  240. }
  241. return defaultParagraphStyle;
  242. }
  243. }
  244. function convertRun(run, messages) {
  245. var nodes = function() {
  246. return convertElements(run.children, messages);
  247. };
  248. var paths = [];
  249. if (run.isStrikethrough) {
  250. paths.push(findHtmlPathForRunProperty("strikethrough", "s"));
  251. }
  252. if (run.isUnderline) {
  253. paths.push(findHtmlPathForRunProperty("underline"));
  254. }
  255. if (run.verticalAlignment === documents.verticalAlignment.subscript) {
  256. paths.push(htmlPaths.element("sub", {}, {fresh: false}));
  257. }
  258. if (run.verticalAlignment === documents.verticalAlignment.superscript) {
  259. paths.push(htmlPaths.element("sup", {}, {fresh: false}));
  260. }
  261. if (run.isItalic) {
  262. paths.push(findHtmlPathForRunProperty("italic", "em"));
  263. }
  264. if (run.isBold) {
  265. paths.push(findHtmlPathForRunProperty("bold", "strong"));
  266. }
  267. var stylePath = htmlPaths.empty;
  268. if (run.styleId) {
  269. var style = findStyle(run);
  270. if (style) {
  271. stylePath = style.to;
  272. } else {
  273. messages.push(unrecognisedStyleWarning("run", run));
  274. }
  275. }
  276. paths.push(stylePath);
  277. paths.forEach(function(path) {
  278. nodes = path.wrap.bind(path, nodes);
  279. });
  280. return nodes();
  281. }
  282. function findHtmlPathForRunProperty(elementType, defaultTagName) {
  283. var path = findHtmlPath({type: elementType});
  284. if (path) {
  285. return path;
  286. } else if (defaultTagName) {
  287. return htmlPaths.element(defaultTagName, {}, {fresh: false});
  288. } else {
  289. return htmlPaths.empty;
  290. }
  291. }
  292. function findHtmlPath(element, defaultPath) {
  293. var style = findStyle(element);
  294. return style ? style.to : defaultPath;
  295. }
  296. function findStyle(element) {
  297. for (var i = 0; i < styleMap.length; i++) {
  298. if (styleMap[i].from.matches(element)) {
  299. return styleMap[i];
  300. }
  301. }
  302. }
  303. var defaultConvertImage = images.imgElement(function(element) {
  304. return element.read("base64").then(function(imageBuffer) {
  305. return {
  306. src: "data:" + element.contentType + ";base64," + imageBuffer
  307. };
  308. });
  309. });
  310. function recoveringConvertImage(convertImage) {
  311. return function(image, messages) {
  312. return promises.attempt(function() {
  313. return convertImage(image, messages);
  314. }).caught(function(error) {
  315. messages.push(results.error(error));
  316. return [];
  317. });
  318. };
  319. }
  320. function noteHtmlId(note) {
  321. return referentHtmlId(note.noteType, note.noteId);
  322. }
  323. function noteRefHtmlId(note) {
  324. return referenceHtmlId(note.noteType, note.noteId);
  325. }
  326. function referentHtmlId(referenceType, referenceId) {
  327. return htmlId(referenceType + "-" + referenceId);
  328. }
  329. function referenceHtmlId(referenceType, referenceId) {
  330. return htmlId(referenceType + "-ref-" + referenceId);
  331. }
  332. function htmlId(suffix) {
  333. return idPrefix + suffix;
  334. }
  335. function convertTable(element, messages) {
  336. return wrapChildrenInFreshElement(element, "table", messages);
  337. }
  338. function convertTableRow(element, messages) {
  339. return wrapChildrenInFreshElement(element, "tr", messages);
  340. }
  341. function convertTableCell(element, messages) {
  342. var children = convertElements(element.children, messages);
  343. var attributes = {};
  344. if (element.colSpan !== 1) {
  345. attributes.colspan = element.colSpan.toString();
  346. }
  347. if (element.rowSpan !== 1) {
  348. attributes.rowspan = element.rowSpan.toString();
  349. }
  350. return [
  351. Html.freshElement("td", attributes, [Html.forceWrite].concat(children))
  352. ];
  353. }
  354. function convertCommentReference(reference, messages) {
  355. return findHtmlPath(reference, htmlPaths.ignore).wrap(function() {
  356. var comment = comments[reference.commentId];
  357. var count = referencedComments.length + 1;
  358. var label = "[" + commentAuthorLabel(comment) + count + "]";
  359. referencedComments.push({label: label, comment: comment});
  360. // TODO: remove duplication with note references
  361. return [
  362. Html.freshElement("a", {
  363. href: "#" + referentHtmlId("comment", reference.commentId),
  364. id: referenceHtmlId("comment", reference.commentId)
  365. }, [Html.text(label)])
  366. ];
  367. });
  368. }
  369. function convertComment(referencedComment, messages) {
  370. // TODO: remove duplication with note references
  371. var label = referencedComment.label;
  372. var comment = referencedComment.comment;
  373. var body = convertElements(comment.body).concat([
  374. Html.nonFreshElement("p", {}, [
  375. Html.text(" "),
  376. Html.freshElement("a", {"href": "#" + referenceHtmlId("comment", comment.commentId)}, [
  377. Html.text("↑")
  378. ])
  379. ])
  380. ]);
  381. return [
  382. Html.freshElement(
  383. "dt",
  384. {"id": referentHtmlId("comment", comment.commentId)},
  385. [Html.text("Comment " + label)]
  386. ),
  387. Html.freshElement("dd", {}, body)
  388. ];
  389. }
  390. function wrapChildrenInFreshElement(element, wrapElementName, messages) {
  391. var children = convertElements(element.children, messages);
  392. return [
  393. Html.freshElement(wrapElementName, {}, [Html.forceWrite].concat(children))
  394. ];
  395. }
  396. var elementConverters = {
  397. "document": function(document, messages) {
  398. var children = convertElements(document.children, messages);
  399. var notes = noteReferences.map(function(noteReference) {
  400. return document.notes.resolve(noteReference);
  401. });
  402. var notesNodes = convertElements(notes, messages);
  403. return children.concat([
  404. Html.freshElement("ol", {}, notesNodes),
  405. Html.freshElement("dl", {}, flatMap(referencedComments, function(referencedComment) {
  406. return convertComment(referencedComment, messages);
  407. }))
  408. ]);
  409. },
  410. "paragraph": convertParagraph,
  411. "run": convertRun,
  412. "text": function(element, messages) {
  413. return [Html.text(element.value)];
  414. },
  415. "tab": function(element, messages) {
  416. return [Html.text("\t")];
  417. },
  418. "hyperlink": function(element, messages) {
  419. var href = element.anchor ? "#" + htmlId(element.anchor) : element.href;
  420. var children = convertElements(element.children, messages);
  421. return [Html.freshElement("a", {href: href}, children)];
  422. },
  423. "bookmarkStart": function(element, messages) {
  424. var anchor = Html.freshElement("a", {
  425. id: htmlId(element.name)
  426. }, [Html.forceWrite]);
  427. return [anchor];
  428. },
  429. "noteReference": function(element, messages) {
  430. noteReferences.push(element);
  431. var anchor = Html.freshElement("a", {
  432. href: "#" + noteHtmlId(element),
  433. id: noteRefHtmlId(element)
  434. }, [Html.text("[" + (noteNumber++) + "]")]);
  435. return [Html.freshElement("sup", {}, [anchor])];
  436. },
  437. "note": function(element, messages) {
  438. var children = convertElements(element.body, messages);
  439. var backLink = Html.elementWithTag(htmlPaths.element("p", {}, {fresh: false}), [
  440. Html.text(" "),
  441. Html.freshElement("a", {href: "#" + noteRefHtmlId(element)}, [Html.text("↑")])
  442. ]);
  443. var body = children.concat([backLink]);
  444. return Html.freshElement("li", {id: noteHtmlId(element)}, body);
  445. },
  446. "commentReference": convertCommentReference,
  447. "comment": convertComment,
  448. "image": deferredConversion(recoveringConvertImage(options.convertImage || defaultConvertImage)),
  449. "table": convertTable,
  450. "tableRow": convertTableRow,
  451. "tableCell": convertTableCell,
  452. "lineBreak": function(element, messages) {
  453. return [Html.selfClosingElement("br")];
  454. }
  455. };
  456. return {
  457. convertToHtml: convertToHtml
  458. };
  459. }
  460. var deferredId = 1;
  461. function deferredConversion(func) {
  462. return function(element, messages) {
  463. return [
  464. {
  465. type: "deferred",
  466. id: deferredId++,
  467. value: function() {
  468. return func(element, messages);
  469. }
  470. }
  471. ];
  472. };
  473. }
  474. function unrecognisedStyleWarning(type, element) {
  475. return results.warning(
  476. "Unrecognised " + type + " style: '" + element.styleName + "'" +
  477. " (Style ID: " + element.styleId + ")"
  478. );
  479. }
  480. function flatMap(values, func) {
  481. return _.flatten(values.map(func), true);
  482. }
  483. function walkHtml(nodes, callback) {
  484. nodes.forEach(function(node) {
  485. callback(node);
  486. if (node.children) {
  487. walkHtml(node.children, callback);
  488. }
  489. });
  490. }
  491. var commentAuthorLabel = exports.commentAuthorLabel = function commentAuthorLabel(comment) {
  492. return comment.authorInitials || "";
  493. };
  494. },{"./documents":5,"./html":19,"./html-paths":17,"./images":21,"./promises":24,"./results":25,"./writers":30,"underscore":154}],5:[function(require,module,exports){
  495. var _ = require("underscore");
  496. var types = exports.types = {
  497. document: "document",
  498. paragraph: "paragraph",
  499. run: "run",
  500. text: "text",
  501. tab: "tab",
  502. hyperlink: "hyperlink",
  503. noteReference: "noteReference",
  504. image: "image",
  505. note: "note",
  506. commentReference: "commentReference",
  507. comment: "comment",
  508. table: "table",
  509. tableRow: "tableRow",
  510. tableCell: "tableCell",
  511. lineBreak: "lineBreak",
  512. bookmarkStart: "bookmarkStart"
  513. };
  514. function Document(children, options) {
  515. options = options || {};
  516. return {
  517. type: types.document,
  518. children: children,
  519. notes: options.notes || new Notes({}),
  520. comments: options.comments || []
  521. };
  522. }
  523. function Paragraph(children, properties) {
  524. properties = properties || {};
  525. return {
  526. type: types.paragraph,
  527. children: children,
  528. styleId: properties.styleId || null,
  529. styleName: properties.styleName || null,
  530. numbering: properties.numbering || null,
  531. alignment: properties.alignment || null
  532. };
  533. }
  534. function Run(children, properties) {
  535. properties = properties || {};
  536. return {
  537. type: types.run,
  538. children: children,
  539. styleId: properties.styleId || null,
  540. styleName: properties.styleName || null,
  541. isBold: properties.isBold,
  542. isUnderline: properties.isUnderline,
  543. isItalic: properties.isItalic,
  544. isStrikethrough: properties.isStrikethrough,
  545. verticalAlignment: properties.verticalAlignment || verticalAlignment.baseline
  546. };
  547. }
  548. var verticalAlignment = {
  549. baseline: "baseline",
  550. superscript: "superscript",
  551. subscript: "subscript"
  552. };
  553. function Text(value) {
  554. return {
  555. type: types.text,
  556. value: value
  557. };
  558. }
  559. function Tab() {
  560. return {
  561. type: types.tab
  562. };
  563. }
  564. function Hyperlink(children, options) {
  565. return {
  566. type: types.hyperlink,
  567. children: children,
  568. href: options.href,
  569. anchor: options.anchor
  570. };
  571. }
  572. function NoteReference(options) {
  573. return {
  574. type: types.noteReference,
  575. noteType: options.noteType,
  576. noteId: options.noteId
  577. };
  578. }
  579. function Notes(notes) {
  580. this._notes = _.indexBy(notes, function(note) {
  581. return noteKey(note.noteType, note.noteId);
  582. });
  583. }
  584. Notes.prototype.resolve = function(reference) {
  585. return this.findNoteByKey(noteKey(reference.noteType, reference.noteId));
  586. };
  587. Notes.prototype.findNoteByKey = function(key) {
  588. return this._notes[key] || null;
  589. };
  590. function Note(options) {
  591. return {
  592. type: types.note,
  593. noteType: options.noteType,
  594. noteId: options.noteId,
  595. body: options.body
  596. };
  597. }
  598. function commentReference(options) {
  599. return {
  600. type: types.commentReference,
  601. commentId: options.commentId
  602. };
  603. }
  604. function comment(options) {
  605. return {
  606. type: types.comment,
  607. commentId: options.commentId,
  608. body: options.body,
  609. authorName: options.authorName,
  610. authorInitials: options.authorInitials
  611. };
  612. }
  613. function noteKey(noteType, id) {
  614. return noteType + "-" + id;
  615. }
  616. function Image(options) {
  617. return {
  618. type: types.image,
  619. read: options.readImage,
  620. altText: options.altText,
  621. contentType: options.contentType
  622. };
  623. }
  624. function Table(children) {
  625. return {
  626. type: types.table,
  627. children: children
  628. };
  629. }
  630. function TableRow(children) {
  631. return {
  632. type: types.tableRow,
  633. children: children
  634. };
  635. }
  636. function TableCell(children, options) {
  637. options = options || {};
  638. return {
  639. type: types.tableCell,
  640. children: children,
  641. colSpan: options.colSpan == null ? 1 : options.colSpan,
  642. rowSpan: options.rowSpan == null ? 1 : options.rowSpan
  643. };
  644. }
  645. function LineBreak() {
  646. return {
  647. type: types.lineBreak
  648. };
  649. }
  650. function BookmarkStart(options) {
  651. return {
  652. type: types.bookmarkStart,
  653. name: options.name
  654. };
  655. }
  656. exports.document = exports.Document = Document;
  657. exports.paragraph = exports.Paragraph = Paragraph;
  658. exports.run = exports.Run = Run;
  659. exports.Text = Text;
  660. exports.Tab = Tab;
  661. exports.Hyperlink = Hyperlink;
  662. exports.noteReference = exports.NoteReference = NoteReference;
  663. exports.Notes = Notes;
  664. exports.Note = Note;
  665. exports.commentReference = commentReference;
  666. exports.comment = comment;
  667. exports.Image = Image;
  668. exports.Table = Table;
  669. exports.TableRow = TableRow;
  670. exports.TableCell = TableCell;
  671. exports.LineBreak = LineBreak;
  672. exports.BookmarkStart = BookmarkStart;
  673. exports.verticalAlignment = verticalAlignment;
  674. },{"underscore":154}],6:[function(require,module,exports){
  675. exports.BodyReader = BodyReader;
  676. var _ = require("underscore");
  677. var documents = require("../documents");
  678. var Result = require("../results").Result;
  679. var warning = require("../results").warning;
  680. function BodyReader(options) {
  681. var relationships = options.relationships;
  682. var contentTypes = options.contentTypes;
  683. var docxFile = options.docxFile;
  684. var files = options.files;
  685. var numbering = options.numbering;
  686. var styles = options.styles;
  687. function readXmlElements(elements) {
  688. var results = elements.map(readXmlElement);
  689. return combineResults(results);
  690. }
  691. function readXmlElement(element) {
  692. if (element.type === "element") {
  693. var handler = xmlElementReaders[element.name];
  694. if (handler) {
  695. return handler(element);
  696. } else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
  697. var message = warning("An unrecognised element was ignored: " + element.name);
  698. return emptyResultWithMessages([message]);
  699. }
  700. }
  701. return emptyResult();
  702. }
  703. function readRunProperties(element) {
  704. var properties = {
  705. type: "runProperties"
  706. };
  707. var verticalAlignmentElement = element.first("w:vertAlign");
  708. if (verticalAlignmentElement) {
  709. properties.verticalAlignment = verticalAlignmentElement.attributes["w:val"];
  710. }
  711. properties.isBold = readBooleanElement(element.first("w:b"));
  712. properties.isUnderline = readBooleanElement(element.first("w:u"));
  713. properties.isItalic = readBooleanElement(element.first("w:i"));
  714. properties.isStrikethrough = readBooleanElement(element.first("w:strike"));
  715. return readRunStyle(element).map(function(style) {
  716. properties.styleId = style.styleId;
  717. properties.styleName = style.name;
  718. return properties;
  719. });
  720. }
  721. function readBooleanElement(element) {
  722. if (element) {
  723. var value = element.attributes["w:val"];
  724. return value !== "false" && value !== "0";
  725. } else {
  726. return false;
  727. }
  728. }
  729. function readParagraphStyle(element) {
  730. return readStyle(element, "w:pStyle", "Paragraph", styles.findParagraphStyleById);
  731. }
  732. function readRunStyle(element) {
  733. return readStyle(element, "w:rStyle", "Run", styles.findCharacterStyleById);
  734. }
  735. function readStyle(element, styleTagName, styleType, findStyleById) {
  736. var messages = [];
  737. var styleElement = element.first(styleTagName);
  738. var styleId = null;
  739. var name = null;
  740. if (styleElement) {
  741. styleId = styleElement.attributes["w:val"];
  742. if (styleId) {
  743. var style = findStyleById(styleId);
  744. if (style) {
  745. name = style.name;
  746. } else {
  747. messages.push(undefinedStyleWarning(styleType, styleId));
  748. }
  749. }
  750. }
  751. return elementResultWithMessages({styleId: styleId, name: name}, messages);
  752. }
  753. function noteReferenceReader(noteType) {
  754. return function(element) {
  755. var noteId = element.attributes["w:id"];
  756. return elementResult(new documents.NoteReference({
  757. noteType: noteType,
  758. noteId: noteId
  759. }));
  760. };
  761. }
  762. function readCommentReference(element) {
  763. return elementResult(documents.commentReference({
  764. commentId: element.attributes["w:id"]
  765. }));
  766. }
  767. function readChildElements(element) {
  768. return readXmlElements(element.children);
  769. }
  770. var xmlElementReaders = {
  771. "w:p": function(element) {
  772. return readXmlElements(element.children)
  773. .map(function(children) {
  774. var properties = _.find(children, isParagraphProperties);
  775. return new documents.Paragraph(
  776. children.filter(negate(isParagraphProperties)),
  777. properties
  778. );
  779. })
  780. .insertExtra();
  781. },
  782. "w:pPr": function(element) {
  783. var properties = {
  784. type: "paragraphProperties"
  785. };
  786. var alignElement = element.first("w:jc");
  787. if (alignElement) {
  788. properties.alignment = alignElement.attributes["w:val"];
  789. }
  790. properties.numbering = readNumberingProperties(element.firstOrEmpty("w:numPr"));
  791. return readParagraphStyle(element).map(function(style) {
  792. properties.styleId = style.styleId;
  793. properties.styleName = style.name;
  794. return properties;
  795. });
  796. },
  797. "w:r": function(element) {
  798. return readXmlElements(element.children)
  799. .map(function(children) {
  800. var properties = _.find(children, isRunProperties);
  801. return new documents.Run(
  802. children.filter(negate(isRunProperties)),
  803. properties
  804. );
  805. });
  806. },
  807. "w:rPr": readRunProperties,
  808. "w:t": function(element) {
  809. return elementResult(new documents.Text(element.text()));
  810. },
  811. "w:tab": function(element) {
  812. return elementResult(new documents.Tab());
  813. },
  814. "w:hyperlink": function(element) {
  815. var relationshipId = element.attributes["r:id"];
  816. var anchor = element.attributes["w:anchor"];
  817. return readXmlElements(element.children).map(function(children) {
  818. if (relationshipId) {
  819. var href = relationships[relationshipId].target;
  820. return new documents.Hyperlink(children, {href: href});
  821. } else if (anchor) {
  822. return new documents.Hyperlink(children, {anchor: anchor});
  823. } else {
  824. return children;
  825. }
  826. });
  827. },
  828. "w:tbl": readTable,
  829. "w:tr": readTableRow,
  830. "w:tc": readTableCell,
  831. "w:footnoteReference": noteReferenceReader("footnote"),
  832. "w:endnoteReference": noteReferenceReader("endnote"),
  833. "w:commentReference": readCommentReference,
  834. "w:br": function(element) {
  835. var breakType = element.attributes["w:type"];
  836. if (breakType) {
  837. return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
  838. } else {
  839. return elementResult(new documents.LineBreak());
  840. }
  841. },
  842. "w:bookmarkStart": function(element){
  843. var name = element.attributes["w:name"];
  844. if (name === "_GoBack") {
  845. return emptyResult();
  846. } else {
  847. return elementResult(new documents.BookmarkStart({name: name}));
  848. }
  849. },
  850. "mc:AlternateContent": function(element) {
  851. return readChildElements(element.first("mc:Fallback"));
  852. },
  853. "w:sdt": function(element) {
  854. return readXmlElements(element.firstOrEmpty("w:sdtContent").children);
  855. },
  856. "w:ins": readChildElements,
  857. "w:smartTag": readChildElements,
  858. "w:drawing": readChildElements,
  859. "w:pict": function(element) {
  860. return readChildElements(element).toExtra();
  861. },
  862. "v:roundrect": readChildElements,
  863. "v:shape": readChildElements,
  864. "v:textbox": readChildElements,
  865. "w:txbxContent": readChildElements,
  866. "wp:inline": readDrawingElement,
  867. "wp:anchor": readDrawingElement,
  868. "v:imagedata": readImageData
  869. };
  870. return {
  871. readXmlElement: readXmlElement,
  872. readXmlElements: readXmlElements,
  873. _readNumberingProperties: readNumberingProperties
  874. };
  875. function readNumberingProperties(element) {
  876. var level = element.firstOrEmpty("w:ilvl").attributes["w:val"];
  877. var numId = element.firstOrEmpty("w:numId").attributes["w:val"];
  878. if (level === undefined || numId === undefined) {
  879. return null;
  880. } else {
  881. return numbering.findLevel(numId, level);
  882. }
  883. }
  884. function readTable(element) {
  885. return readXmlElements(element.children)
  886. .flatMap(calculateRowSpans)
  887. .map(documents.Table);
  888. }
  889. function readTableRow(element) {
  890. return readXmlElements(element.children).map(documents.TableRow);
  891. }
  892. function readTableCell(element) {
  893. return readXmlElements(element.children).map(function(children) {
  894. var properties = element.firstOrEmpty("w:tcPr");
  895. var gridSpan = properties.firstOrEmpty("w:gridSpan").attributes["w:val"];
  896. var colSpan = gridSpan ? parseInt(gridSpan, 10) : 1;
  897. var cell = documents.TableCell(children, {colSpan: colSpan});
  898. cell._vMerge = readVMerge(properties);
  899. return cell;
  900. });
  901. }
  902. function readVMerge(properties) {
  903. var element = properties.first("w:vMerge");
  904. if (element) {
  905. var val = element.attributes["w:val"];
  906. return val === "continue" || !val;
  907. } else {
  908. return null;
  909. }
  910. }
  911. function calculateRowSpans(rows) {
  912. var unexpectedNonRows = _.any(rows, function(row) {
  913. return row.type !== documents.types.tableRow;
  914. });
  915. if (unexpectedNonRows) {
  916. return elementResultWithMessages(rows, [warning(
  917. "unexpected non-row element in table, cell merging may be incorrect"
  918. )]);
  919. }
  920. var unexpectedNonCells = _.any(rows, function(row) {
  921. return _.any(row.children, function(cell) {
  922. return cell.type !== documents.types.tableCell;
  923. });
  924. });
  925. if (unexpectedNonCells) {
  926. return elementResultWithMessages(rows, [warning(
  927. "unexpected non-cell element in table row, cell merging may be incorrect"
  928. )]);
  929. }
  930. var columns = {};
  931. rows.forEach(function(row) {
  932. var cellIndex = 0;
  933. row.children.forEach(function(cell) {
  934. if (cell._vMerge && columns[cellIndex]) {
  935. columns[cellIndex].rowSpan++;
  936. } else {
  937. columns[cellIndex] = cell;
  938. cell._vMerge = false;
  939. }
  940. cellIndex += cell.colSpan;
  941. });
  942. });
  943. rows.forEach(function(row) {
  944. row.children = row.children.filter(function(cell) {
  945. return !cell._vMerge;
  946. });
  947. row.children.forEach(function(cell) {
  948. delete cell._vMerge;
  949. });
  950. });
  951. return elementResult(rows);
  952. }
  953. function readDrawingElement(element) {
  954. var blips = element
  955. .getElementsByTagName("a:graphic")
  956. .getElementsByTagName("a:graphicData")
  957. .getElementsByTagName("pic:pic")
  958. .getElementsByTagName("pic:blipFill")
  959. .getElementsByTagName("a:blip");
  960. return combineResults(blips.map(readBlip.bind(null, element)));
  961. }
  962. function readBlip(element, blip) {
  963. var properties = element.first("wp:docPr").attributes;
  964. var altText = isBlank(properties.descr) ? properties.title : properties.descr;
  965. return readImage(findBlipImageFile(blip), altText);
  966. }
  967. function isBlank(value) {
  968. return value == null || /^\s*$/.test(value);
  969. }
  970. function findBlipImageFile(blip) {
  971. var embedRelationshipId = blip.attributes["r:embed"];
  972. var linkRelationshipid = blip.attributes["r:link"];
  973. if (embedRelationshipId) {
  974. return findEmbeddedImageFile(embedRelationshipId);
  975. } else {
  976. var imagePath = relationships[linkRelationshipid].target;
  977. return {
  978. path: imagePath,
  979. read: files.read.bind(files, imagePath)
  980. };
  981. }
  982. }
  983. function readImageData(element) {
  984. var relationshipId = element.attributes['r:id'];
  985. if (relationshipId) {
  986. return readImage(
  987. findEmbeddedImageFile(relationshipId),
  988. element.attributes["o:title"]);
  989. } else {
  990. return emptyResultWithMessages([warning("A v:imagedata element without a relationship ID was ignored")]);
  991. }
  992. }
  993. function findEmbeddedImageFile(relationshipId) {
  994. var path = joinZipPath("word", relationships[relationshipId].target);
  995. return {
  996. path: path,
  997. read: docxFile.read.bind(docxFile, path)
  998. };
  999. }
  1000. function readImage(imageFile, altText) {
  1001. var contentType = contentTypes.findContentType(imageFile.path);
  1002. var image = documents.Image({
  1003. readImage: imageFile.read,
  1004. altText: altText,
  1005. contentType: contentType
  1006. });
  1007. var warnings = supportedImageTypes[contentType] ?
  1008. [] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
  1009. return elementResultWithMessages(image, warnings);
  1010. }
  1011. function undefinedStyleWarning(type, styleId) {
  1012. return warning(
  1013. type + " style with ID " + styleId + " was referenced but not defined in the document");
  1014. }
  1015. }
  1016. var supportedImageTypes = {
  1017. "image/png": true,
  1018. "image/gif": true,
  1019. "image/jpeg": true,
  1020. "image/svg+xml": true,
  1021. "image/tiff": true
  1022. };
  1023. var ignoreElements = {
  1024. "office-word:wrap": true,
  1025. "v:shadow": true,
  1026. "v:shapetype": true,
  1027. "w:annotationRef": true,
  1028. "w:bookmarkEnd": true,
  1029. "w:sectPr": true,
  1030. "w:proofErr": true,
  1031. "w:lastRenderedPageBreak": true,
  1032. "w:commentRangeStart": true,
  1033. "w:commentRangeEnd": true,
  1034. "w:del": true,
  1035. "w:footnoteRef": true,
  1036. "w:endnoteRef": true,
  1037. "w:tblPr": true,
  1038. "w:tblGrid": true,
  1039. "w:tcPr": true
  1040. };
  1041. function isParagraphProperties(element) {
  1042. return element.type === "paragraphProperties";
  1043. }
  1044. function isRunProperties(element) {
  1045. return element.type === "runProperties";
  1046. }
  1047. function negate(predicate) {
  1048. return function(value) {
  1049. return !predicate(value);
  1050. };
  1051. }
  1052. function joinZipPath(first, second) {
  1053. // In general, we should check first and second for trailing and leading slashes,
  1054. // but in our specific case this seems to be sufficient
  1055. return first + "/" + second;
  1056. }
  1057. function emptyResultWithMessages(messages) {
  1058. return new ReadResult(null, null, messages);
  1059. }
  1060. function emptyResult() {
  1061. return new ReadResult(null);
  1062. }
  1063. function elementResult(element) {
  1064. return new ReadResult(element);
  1065. }
  1066. function elementResultWithMessages(element, messages) {
  1067. return new ReadResult(element, null, messages);
  1068. }
  1069. function ReadResult(element, extra, messages) {
  1070. this.value = element || [];
  1071. this.extra = extra;
  1072. this._result = new Result({
  1073. element: this.value,
  1074. extra: extra
  1075. }, messages);
  1076. this.messages = this._result.messages;
  1077. }
  1078. ReadResult.prototype.toExtra = function() {
  1079. return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
  1080. };
  1081. ReadResult.prototype.insertExtra = function() {
  1082. var extra = this.extra;
  1083. if (extra && extra.length) {
  1084. return new ReadResult(joinElements(this.value, extra), null, this.messages);
  1085. } else {
  1086. return this;
  1087. }
  1088. };
  1089. ReadResult.prototype.map = function(func) {
  1090. var result = this._result.map(function(value) {
  1091. return func(value.element);
  1092. });
  1093. return new ReadResult(result.value, this.extra, result.messages);
  1094. };
  1095. ReadResult.prototype.flatMap = function(func) {
  1096. var result = this._result.flatMap(function(value) {
  1097. return func(value.element)._result;
  1098. });
  1099. return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
  1100. };
  1101. function combineResults(results) {
  1102. var result = Result.combine(_.pluck(results, "_result"));
  1103. return new ReadResult(
  1104. _.flatten(_.pluck(result.value, "element")),
  1105. _.filter(_.flatten(_.pluck(result.value, "extra")), identity),
  1106. result.messages
  1107. );
  1108. }
  1109. function joinElements(first, second) {
  1110. return _.flatten([first, second]);
  1111. }
  1112. function identity(value) {
  1113. return value;
  1114. }
  1115. },{"../documents":5,"../results":25,"underscore":154}],7:[function(require,module,exports){
  1116. var documents = require("../documents");
  1117. var Result = require("../results").Result;
  1118. function createCommentsReader(bodyReader) {
  1119. function readCommentsXml(element) {
  1120. return Result.combine(element.getElementsByTagName("w:comment")
  1121. .map(readCommentElement));
  1122. }
  1123. function readCommentElement(element) {
  1124. var id = element.attributes["w:id"];
  1125. function readOptionalAttribute(name) {
  1126. return (element.attributes[name] || "").trim() || null;
  1127. }
  1128. return bodyReader.readXmlElements(element.children)
  1129. .map(function(body) {
  1130. return documents.comment({
  1131. commentId: id,
  1132. body: body,
  1133. authorName: readOptionalAttribute("w:author"),
  1134. authorInitials: readOptionalAttribute("w:initials")
  1135. });
  1136. });
  1137. }
  1138. return readCommentsXml;
  1139. }
  1140. exports.createCommentsReader = createCommentsReader;
  1141. },{"../documents":5,"../results":25}],8:[function(require,module,exports){
  1142. exports.readContentTypesFromXml = readContentTypesFromXml;
  1143. var fallbackContentTypes = {
  1144. "png": "png",
  1145. "gif": "gif",
  1146. "jpeg": "jpeg",
  1147. "jpg": "jpeg",
  1148. "tif": "tiff",
  1149. "tiff": "tiff",
  1150. "bmp": "bmp"
  1151. };
  1152. exports.defaultContentTypes = contentTypes({}, {});
  1153. function readContentTypesFromXml(element) {
  1154. var extensionDefaults = {};
  1155. var overrides = {};
  1156. element.children.forEach(function(child) {
  1157. if (child.name === "content-types:Default") {
  1158. extensionDefaults[child.attributes.Extension] = child.attributes.ContentType;
  1159. }
  1160. if (child.name === "content-types:Override") {
  1161. var name = child.attributes.PartName;
  1162. if (name.charAt(0) === "/") {
  1163. name = name.substring(1);
  1164. }
  1165. overrides[name] = child.attributes.ContentType;
  1166. }
  1167. });
  1168. return contentTypes(overrides, extensionDefaults);
  1169. }
  1170. function contentTypes(overrides, extensionDefaults) {
  1171. return {
  1172. findContentType: function(path) {
  1173. var overrideContentType = overrides[path];
  1174. if (overrideContentType) {
  1175. return overrideContentType;
  1176. } else {
  1177. var pathParts = path.split(".");
  1178. var extension = pathParts[pathParts.length - 1];
  1179. if (extensionDefaults.hasOwnProperty(extension)) {
  1180. return extensionDefaults[extension];
  1181. } else {
  1182. var fallback = fallbackContentTypes[extension.toLowerCase()];
  1183. if (fallback) {
  1184. return "image/" + fallback;
  1185. } else {
  1186. return null;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. };
  1192. }
  1193. },{}],9:[function(require,module,exports){
  1194. exports.DocumentXmlReader = DocumentXmlReader;
  1195. var documents = require("../documents");
  1196. var Result = require("../results").Result;
  1197. function DocumentXmlReader(options) {
  1198. var bodyReader = options.bodyReader;
  1199. function convertXmlToDocument(element) {
  1200. var body = element.first("w:body");
  1201. var result = bodyReader.readXmlElements(body.children)
  1202. .map(function(children) {
  1203. return new documents.Document(children, {
  1204. notes: options.notes,
  1205. comments: options.comments
  1206. });
  1207. });
  1208. return new Result(result.value, result.messages);
  1209. }
  1210. return {
  1211. convertXmlToDocument: convertXmlToDocument
  1212. };
  1213. }
  1214. },{"../documents":5,"../results":25}],10:[function(require,module,exports){
  1215. exports.read = read;
  1216. var path = require("path");
  1217. var promises = require("../promises");
  1218. var documents = require("../documents");
  1219. var Result = require("../results").Result;
  1220. var readXmlFromZipFile = require("./office-xml-reader").readXmlFromZipFile;
  1221. var BodyReader = require("./body-reader").BodyReader;
  1222. var DocumentXmlReader = require("./document-xml-reader").DocumentXmlReader;
  1223. var relationshipsReader = require("./relationships-reader");
  1224. var contentTypesReader = require("./content-types-reader");
  1225. var numberingXml = require("./numbering-xml");
  1226. var stylesReader = require("./styles-reader");
  1227. var notesReader = require("./notes-reader");
  1228. var commentsReader = require("./comments-reader");
  1229. var Files = require("./files").Files;
  1230. function read(docxFile, input) {
  1231. input = input || {};
  1232. return promises.props({
  1233. contentTypes: readContentTypesFromZipFile(docxFile),
  1234. numbering: readNumberingFromZipFile(docxFile),
  1235. styles: readStylesFromZipFile(docxFile),
  1236. docxFile: docxFile,
  1237. files: new Files(input.path ? path.dirname(input.path) : null)
  1238. }).also(function(result) {
  1239. return {
  1240. footnotes: readXmlFileWithBody("footnotes", result, function(bodyReader, xml) {
  1241. if (xml) {
  1242. return notesReader.createFootnotesReader(bodyReader)(xml);
  1243. } else {
  1244. return new Result([]);
  1245. }
  1246. }),
  1247. endnotes: readXmlFileWithBody("endnotes", result, function(bodyReader, xml) {
  1248. if (xml) {
  1249. return notesReader.createEndnotesReader(bodyReader)(xml);
  1250. } else {
  1251. return new Result([]);
  1252. }
  1253. }),
  1254. comments: readXmlFileWithBody("comments", result, function(bodyReader, xml) {
  1255. if (xml) {
  1256. return commentsReader.createCommentsReader(bodyReader)(xml);
  1257. } else {
  1258. return new Result([]);
  1259. }
  1260. })
  1261. };
  1262. }).also(function(result) {
  1263. return {
  1264. notes: result.footnotes.flatMap(function(footnotes) {
  1265. return result.endnotes.map(function(endnotes) {
  1266. return new documents.Notes(footnotes.concat(endnotes));
  1267. });
  1268. })
  1269. };
  1270. }).then(function(result) {
  1271. return readXmlFileWithBody("document", result, function(bodyReader, xml) {
  1272. if (xml) {
  1273. return result.notes.flatMap(function(notes) {
  1274. return result.comments.flatMap(function(comments) {
  1275. var reader = new DocumentXmlReader({
  1276. bodyReader: bodyReader,
  1277. notes: notes,
  1278. comments: comments
  1279. });
  1280. return reader.convertXmlToDocument(xml);
  1281. });
  1282. });
  1283. } else {
  1284. throw new Error("Could not find word/document.xml in ZIP file. Are you sure this is a valid .docx file?");
  1285. }
  1286. });
  1287. });
  1288. }
  1289. function xmlFileReader(options) {
  1290. return function(zipFile) {
  1291. return readXmlFromZipFile(zipFile, options.filename)
  1292. .then(function(element) {
  1293. return element ? options.readElement(element) : options.defaultValue;
  1294. });
  1295. };
  1296. }
  1297. function readXmlFileWithBody(name, options, func) {
  1298. var readRelationshipsFromZipFile = xmlFileReader({
  1299. filename: "word/_rels/" + name + ".xml.rels",
  1300. readElement: relationshipsReader.readRelationships,
  1301. defaultValue: {}
  1302. });
  1303. return readRelationshipsFromZipFile(options.docxFile).then(function(relationships) {
  1304. var bodyReader = new BodyReader({
  1305. relationships: relationships,
  1306. contentTypes: options.contentTypes,
  1307. docxFile: options.docxFile,
  1308. numbering: options.numbering,
  1309. styles: options.styles,
  1310. files: options.files
  1311. });
  1312. return readXmlFromZipFile(options.docxFile, "word/" + name + ".xml")
  1313. .then(function(xml) {
  1314. return func(bodyReader, xml);
  1315. });
  1316. });
  1317. }
  1318. var readContentTypesFromZipFile = xmlFileReader({
  1319. filename: "[Content_Types].xml",
  1320. readElement: contentTypesReader.readContentTypesFromXml,
  1321. defaultValue: contentTypesReader.defaultContentTypes
  1322. });
  1323. var readNumberingFromZipFile = xmlFileReader({
  1324. filename: "word/numbering.xml",
  1325. readElement: numberingXml.readNumberingXml,
  1326. defaultValue: numberingXml.defaultNumbering
  1327. });
  1328. var readStylesFromZipFile = xmlFileReader({
  1329. filename: "word/styles.xml",
  1330. readElement: stylesReader.readStylesXml,
  1331. defaultValue: stylesReader.defaultStyles
  1332. });
  1333. },{"../documents":5,"../promises":24,"../results":25,"./body-reader":6,"./comments-reader":7,"./content-types-reader":8,"./document-xml-reader":9,"./files":1,"./notes-reader":11,"./numbering-xml":12,"./office-xml-reader":13,"./relationships-reader":14,"./styles-reader":16,"path":80}],11:[function(require,module,exports){
  1334. var documents = require("../documents");
  1335. var Result = require("../results").Result;
  1336. exports.createFootnotesReader = createReader.bind(this, "footnote");
  1337. exports.createEndnotesReader = createReader.bind(this, "endnote");
  1338. function createReader(noteType, bodyReader) {
  1339. function readNotesXml(element) {
  1340. return Result.combine(element.getElementsByTagName("w:" + noteType)
  1341. .filter(isFootnoteElement)
  1342. .map(readFootnoteElement));
  1343. }
  1344. function isFootnoteElement(element) {
  1345. var type = element.attributes["w:type"];
  1346. return type !== "continuationSeparator" && type !== "separator";
  1347. }
  1348. function readFootnoteElement(footnoteElement) {
  1349. var id = footnoteElement.attributes["w:id"];
  1350. return bodyReader.readXmlElements(footnoteElement.children)
  1351. .map(function(body) {
  1352. return documents.Note({noteType: noteType, noteId: id, body: body});
  1353. });
  1354. }
  1355. return readNotesXml;
  1356. }
  1357. },{"../documents":5,"../results":25}],12:[function(require,module,exports){
  1358. exports.readNumberingXml = readNumberingXml;
  1359. exports.Numbering = Numbering;
  1360. exports.defaultNumbering = new Numbering({});
  1361. function Numbering(nums) {
  1362. return {
  1363. findLevel: function(numId, level) {
  1364. var num = nums[numId];
  1365. if (num) {
  1366. return num[level];
  1367. } else {
  1368. return null;
  1369. }
  1370. }
  1371. };
  1372. }
  1373. function readNumberingXml(root) {
  1374. var abstractNums = readAbstractNums(root);
  1375. var nums = readNums(root, abstractNums);
  1376. return new Numbering(nums);
  1377. }
  1378. function readAbstractNums(root) {
  1379. var abstractNums = {};
  1380. root.getElementsByTagName("w:abstractNum").forEach(function(element) {
  1381. var id = element.attributes["w:abstractNumId"];
  1382. abstractNums[id] = readAbstractNum(element);
  1383. });
  1384. return abstractNums;
  1385. }
  1386. function readAbstractNum(element) {
  1387. var levels = {};
  1388. element.getElementsByTagName("w:lvl").forEach(function(levelElement) {
  1389. var levelIndex = levelElement.attributes["w:ilvl"];
  1390. var numFmt = levelElement.first("w:numFmt").attributes["w:val"];
  1391. levels[levelIndex] = {
  1392. isOrdered: numFmt !== "bullet",
  1393. level: levelIndex
  1394. };
  1395. });
  1396. return levels;
  1397. }
  1398. function readNums(root, abstractNums) {
  1399. var nums = {};
  1400. root.getElementsByTagName("w:num").forEach(function(element) {
  1401. var id = element.attributes["w:numId"];
  1402. var abstractNumId = element.first("w:abstractNumId").attributes["w:val"];
  1403. nums[id] = abstractNums[abstractNumId];
  1404. });
  1405. return nums;
  1406. }
  1407. },{}],13:[function(require,module,exports){
  1408. var _ = require("underscore");
  1409. var promises = require("../promises");
  1410. var xml = require("../xml");
  1411. exports.read = read;
  1412. exports.readXmlFromZipFile = readXmlFromZipFile;
  1413. var xmlNamespaceMap = {
  1414. "http://schemas.openxmlformats.org/wordprocessingml/2006/main": "w",
  1415. "http://schemas.openxmlformats.org/officeDocument/2006/relationships": "r",
  1416. "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing": "wp",
  1417. "http://schemas.openxmlformats.org/drawingml/2006/main": "a",
  1418. "http://schemas.openxmlformats.org/drawingml/2006/picture": "pic",
  1419. "http://schemas.openxmlformats.org/package/2006/content-types": "content-types",
  1420. "urn:schemas-microsoft-com:vml": "v",
  1421. "http://schemas.openxmlformats.org/markup-compatibility/2006": "mc",
  1422. "urn:schemas-microsoft-com:office:word": "office-word"
  1423. };
  1424. function read(xmlString) {
  1425. return xml.readString(xmlString, xmlNamespaceMap)
  1426. .then(function(document) {
  1427. return collapseAlternateContent(document)[0];
  1428. });
  1429. }
  1430. function readXmlFromZipFile(docxFile, path) {
  1431. if (docxFile.exists(path)) {
  1432. return docxFile.read(path, "utf-8")
  1433. .then(stripUtf8Bom)
  1434. .then(read);
  1435. } else {
  1436. return promises.resolve(null);
  1437. }
  1438. }
  1439. function stripUtf8Bom(xmlString) {
  1440. return xmlString.replace(/^\uFEFF/g, '');
  1441. }
  1442. function collapseAlternateContent(node) {
  1443. if (node.type === "element") {
  1444. if (node.name === "mc:AlternateContent") {
  1445. return node.first("mc:Fallback").children;
  1446. } else {
  1447. node.children = _.flatten(node.children.map(collapseAlternateContent, true));
  1448. return [node];
  1449. }
  1450. } else {
  1451. return [node];
  1452. }
  1453. }
  1454. },{"../promises":24,"../xml":32,"underscore":154}],14:[function(require,module,exports){
  1455. exports.readRelationships = readRelationships;
  1456. function readRelationships(element) {
  1457. var relationships = {};
  1458. element.children.forEach(function(child) {
  1459. if (child.name === "{http://schemas.openxmlformats.org/package/2006/relationships}Relationship") {
  1460. relationships[child.attributes.Id] = {
  1461. target: child.attributes.Target
  1462. };
  1463. }
  1464. });
  1465. return relationships;
  1466. }
  1467. },{}],15:[function(require,module,exports){
  1468. var _ = require("underscore");
  1469. var promises = require("../promises");
  1470. var xml = require("../xml");
  1471. exports.writeStyleMap = writeStyleMap;
  1472. exports.readStyleMap = readStyleMap;
  1473. var schema = "http://schemas.zwobble.org/mammoth/style-map";
  1474. var styleMapPath = "mammoth/style-map";
  1475. var styleMapAbsolutePath = "/" + styleMapPath;
  1476. function writeStyleMap(docxFile, styleMap) {
  1477. docxFile.write(styleMapPath, styleMap);
  1478. return updateRelationships(docxFile).then(function() {
  1479. return updateContentTypes(docxFile);
  1480. });
  1481. }
  1482. function updateRelationships(docxFile) {
  1483. var path = "word/_rels/document.xml.rels";
  1484. var relationshipsUri = "http://schemas.openxmlformats.org/package/2006/relationships";
  1485. var relationshipElementName = "{" + relationshipsUri + "}Relationship";
  1486. return docxFile.read(path, "utf8")
  1487. .then(xml.readString)
  1488. .then(function(relationshipsContainer) {
  1489. var relationships = relationshipsContainer.children;
  1490. addOrUpdateElement(relationships, relationshipElementName, "Id", {
  1491. "Id": "rMammothStyleMap",
  1492. "Type": schema,
  1493. "Target": styleMapAbsolutePath
  1494. });
  1495. var namespaces = {"": relationshipsUri};
  1496. return docxFile.write(path, xml.writeString(relationshipsContainer, namespaces));
  1497. });
  1498. }
  1499. function updateContentTypes(docxFile) {
  1500. var path = "[Content_Types].xml";
  1501. var contentTypesUri = "http://schemas.openxmlformats.org/package/2006/content-types";
  1502. var overrideName = "{" + contentTypesUri + "}Override";
  1503. return docxFile.read(path, "utf8")
  1504. .then(xml.readString)
  1505. .then(function(typesElement) {
  1506. var children = typesElement.children;
  1507. addOrUpdateElement(children, overrideName, "PartName", {
  1508. "PartName": styleMapAbsolutePath,
  1509. "ContentType": "text/prs.mammoth.style-map"
  1510. });
  1511. var namespaces = {"": contentTypesUri};
  1512. return docxFile.write(path, xml.writeString(typesElement, namespaces));
  1513. });
  1514. }
  1515. function addOrUpdateElement(elements, name, identifyingAttribute, attributes) {
  1516. var existingElement = _.find(elements, function(element) {
  1517. return element.name === name &&
  1518. element.attributes[identifyingAttribute] === attributes[identifyingAttribute];
  1519. });
  1520. if (existingElement) {
  1521. existingElement.attributes = attributes;
  1522. } else {
  1523. elements.push(xml.element(name, attributes));
  1524. }
  1525. }
  1526. function readStyleMap(docxFile) {
  1527. if (docxFile.exists(styleMapPath)) {
  1528. return docxFile.read(styleMapPath, "utf8");
  1529. } else {
  1530. return promises.resolve(null);
  1531. }
  1532. }
  1533. },{"../promises":24,"../xml":32,"underscore":154}],16:[function(require,module,exports){
  1534. exports.readStylesXml = readStylesXml;
  1535. exports.Styles = Styles;
  1536. exports.defaultStyles = new Styles({}, {});
  1537. function Styles(paragraphStyles, characterStyles) {
  1538. return {
  1539. findParagraphStyleById: function(styleId) {
  1540. return paragraphStyles[styleId];
  1541. },
  1542. findCharacterStyleById: function(styleId) {
  1543. return characterStyles[styleId];
  1544. }
  1545. };
  1546. }
  1547. function readStylesXml(root) {
  1548. var paragraphStyles = {};
  1549. var characterStyles = {};
  1550. var styles = {
  1551. "paragraph": paragraphStyles,
  1552. "character": characterStyles
  1553. };
  1554. root.getElementsByTagName("w:style").forEach(function(styleElement) {
  1555. var style = readStyleElement(styleElement);
  1556. var styleSet = styles[style.type];
  1557. if (styleSet) {
  1558. styleSet[style.styleId] = style;
  1559. }
  1560. });
  1561. return new Styles(paragraphStyles, characterStyles);
  1562. }
  1563. function readStyleElement(styleElement) {
  1564. var type = styleElement.attributes["w:type"];
  1565. var styleId = styleElement.attributes["w:styleId"];
  1566. var name = styleName(styleElement);
  1567. return {type: type, styleId: styleId, name: name};
  1568. }
  1569. function styleName(styleElement) {
  1570. var nameElement = styleElement.first("w:name");
  1571. return nameElement ? nameElement.attributes["w:val"] : null;
  1572. }
  1573. },{}],17:[function(require,module,exports){
  1574. var _ = require("underscore");
  1575. var html = require("./html");
  1576. exports.topLevelElement = topLevelElement;
  1577. exports.elements = elements;
  1578. exports.element = element;
  1579. function topLevelElement(tagName, attributes) {
  1580. return elements([element(tagName, attributes, {fresh: true})]);
  1581. }
  1582. function elements(elementStyles) {
  1583. return new HtmlPath(elementStyles.map(function(elementStyle) {
  1584. if (_.isString(elementStyle)) {
  1585. return element(elementStyle);
  1586. } else {
  1587. return elementStyle;
  1588. }
  1589. }));
  1590. }
  1591. function HtmlPath(elements) {
  1592. this._elements = elements;
  1593. }
  1594. HtmlPath.prototype.wrap = function wrap(children) {
  1595. var result = children();
  1596. for (var index = this._elements.length - 1; index >= 0; index--) {
  1597. result = this._elements[index].wrapNodes(result);
  1598. }
  1599. return result;
  1600. };
  1601. function element(tagName, attributes, options) {
  1602. options = options || {};
  1603. return new Element(tagName, attributes, options);
  1604. }
  1605. function Element(tagName, attributes, options) {
  1606. var tagNames = {};
  1607. if (_.isArray(tagName)) {
  1608. tagName.forEach(function(tagName) {
  1609. tagNames[tagName] = true;
  1610. });
  1611. tagName = tagName[0];
  1612. } else {
  1613. tagNames[tagName] = true;
  1614. }
  1615. this.tagName = tagName;
  1616. this.tagNames = tagNames;
  1617. this.attributes = attributes || {};
  1618. this.fresh = options.fresh;
  1619. }
  1620. Element.prototype.matchesElement = function(element) {
  1621. return this.tagNames[element.tagName] && _.isEqual(this.attributes || {}, element.attributes || {});
  1622. };
  1623. Element.prototype.wrap = function wrap(generateNodes) {
  1624. return this.wrapNodes(generateNodes());
  1625. };
  1626. Element.prototype.wrapNodes = function wrapNodes(nodes) {
  1627. return [html.elementWithTag(this, nodes)];
  1628. };
  1629. exports.empty = elements([]);
  1630. exports.ignore = {
  1631. wrap: function() {
  1632. return [];
  1633. }
  1634. };
  1635. },{"./html":19,"underscore":154}],18:[function(require,module,exports){
  1636. var htmlPaths = require("../html-paths");
  1637. function nonFreshElement(tagName, attributes, children) {
  1638. return elementWithTag(
  1639. htmlPaths.element(tagName, attributes, {fresh: false}),
  1640. children);
  1641. }
  1642. function freshElement(tagName, attributes, children) {
  1643. return elementWithTag(
  1644. htmlPaths.element(tagName, attributes, {fresh: true}),
  1645. children);
  1646. }
  1647. function elementWithTag(tag, children) {
  1648. return {
  1649. type: "element",
  1650. tag: tag,
  1651. children: children || []
  1652. };
  1653. }
  1654. function selfClosingElement(tagName, attributes) {
  1655. return {
  1656. type: "selfClosingElement",
  1657. tagName: tagName,
  1658. attributes: attributes
  1659. };
  1660. }
  1661. function text(value) {
  1662. return {
  1663. type: "text",
  1664. value: value
  1665. };
  1666. }
  1667. var forceWrite = {
  1668. type: "forceWrite"
  1669. };
  1670. exports.freshElement = freshElement;
  1671. exports.nonFreshElement = nonFreshElement;
  1672. exports.elementWithTag = elementWithTag;
  1673. exports.selfClosingElement = selfClosingElement;
  1674. exports.text = text;
  1675. exports.forceWrite = forceWrite;
  1676. },{"../html-paths":17}],19:[function(require,module,exports){
  1677. var ast = require("./ast");
  1678. exports.freshElement = ast.freshElement;
  1679. exports.nonFreshElement = ast.nonFreshElement;
  1680. exports.elementWithTag = ast.elementWithTag;
  1681. exports.selfClosingElement = ast.selfClosingElement;
  1682. exports.text = ast.text;
  1683. exports.forceWrite = ast.forceWrite;
  1684. exports.simplify = require("./simplify");
  1685. function write(writer, nodes) {
  1686. nodes.forEach(function(node) {
  1687. writeNode(writer, node);
  1688. });
  1689. }
  1690. function writeNode(writer, node) {
  1691. toStrings[node.type](writer, node);
  1692. }
  1693. var toStrings = {
  1694. element: generateElementString,
  1695. selfClosingElement: generateSelfClosingElementString,
  1696. text: generateTextString,
  1697. forceWrite: function() { }
  1698. };
  1699. function generateElementString(writer, node) {
  1700. writer.open(node.tag.tagName, node.tag.attributes);
  1701. write(writer, node.children);
  1702. writer.close(node.tag.tagName);
  1703. }
  1704. function generateSelfClosingElementString(writer, node) {
  1705. writer.selfClosing(node.tagName, node.attributes);
  1706. }
  1707. function generateTextString(writer, node) {
  1708. writer.text(node.value);
  1709. }
  1710. exports.write = write;
  1711. },{"./ast":18,"./simplify":20}],20:[function(require,module,exports){
  1712. var _ = require("underscore");
  1713. var ast = require("./ast");
  1714. function simplify(nodes) {
  1715. return collapse(removeEmpty(nodes));
  1716. }
  1717. function collapse(nodes) {
  1718. var children = [];
  1719. nodes.map(collapseNode).forEach(function(child) {
  1720. appendChild(children, child);
  1721. });
  1722. return children;
  1723. }
  1724. function collapseNode(node) {
  1725. return collapsers[node.type](node);
  1726. }
  1727. var collapsers = {
  1728. element: collapseElement,
  1729. selfClosingElement: identity,
  1730. text: identity,
  1731. forceWrite: identity
  1732. };
  1733. function collapseElement(node) {
  1734. return ast.elementWithTag(node.tag, collapse(node.children));
  1735. }
  1736. function identity(value) {
  1737. return value;
  1738. }
  1739. function appendChild(children, child) {
  1740. var lastChild = children[children.length - 1];
  1741. if (child.type === "element" && !child.tag.fresh && lastChild && lastChild.type === "element" && child.tag.matchesElement(lastChild.tag)) {
  1742. child.children.forEach(function(grandChild) {
  1743. // Mutation is fine since simplifying elements create a copy of the children.
  1744. appendChild(lastChild.children, grandChild);
  1745. });
  1746. } else {
  1747. children.push(child);
  1748. }
  1749. }
  1750. function removeEmpty(nodes) {
  1751. return flatMap(nodes, function(node) {
  1752. return emptiers[node.type](node);
  1753. });
  1754. }
  1755. function flatMap(values, func) {
  1756. return _.flatten(_.map(values, func), true);
  1757. }
  1758. var emptiers = {
  1759. element: elementEmptier,
  1760. selfClosingElement: neverEmpty,
  1761. text: textEmptier,
  1762. forceWrite: neverEmpty
  1763. };
  1764. function neverEmpty(node) {
  1765. return [node];
  1766. }
  1767. function elementEmptier(element) {
  1768. var children = removeEmpty(element.children);
  1769. if (children.length === 0) {
  1770. return [];
  1771. } else {
  1772. return ast.elementWithTag(element.tag, children);
  1773. }
  1774. }
  1775. function textEmptier(node) {
  1776. if (node.value.length === 0) {
  1777. return [];
  1778. } else {
  1779. return [node];
  1780. }
  1781. }
  1782. module.exports = simplify;
  1783. },{"./ast":18,"underscore":154}],21:[function(require,module,exports){
  1784. var _ = require("underscore");
  1785. var promises = require("./promises");
  1786. var Html = require("./html");
  1787. exports.imgElement = function(func) {
  1788. return function(element, messages) {
  1789. return promises.when(func(element)).then(function(result) {
  1790. var attributes = _.clone(result);
  1791. if (element.altText) {
  1792. attributes.alt = element.altText;
  1793. }
  1794. return [Html.selfClosingElement("img", attributes)];
  1795. });
  1796. };
  1797. };
  1798. // Undocumented, but retained for backwards-compatibility with 0.3.x
  1799. exports.inline = exports.imgElement;
  1800. },{"./html":19,"./promises":24,"underscore":154}],22:[function(require,module,exports){
  1801. var docxReader = require("./docx/docx-reader");
  1802. var docxStyleMap = require("./docx/style-map");
  1803. var DocumentConverter = require("./document-to-html").DocumentConverter;
  1804. var readStyle = require("./style-reader").readStyle;
  1805. var readOptions = require("./options-reader").readOptions;
  1806. var unzip = require("./unzip");
  1807. var Result = require("./results").Result;
  1808. exports.convertToHtml = convertToHtml;
  1809. exports.convertToMarkdown = convertToMarkdown;
  1810. exports.convert = convert;
  1811. exports.extractRawText = extractRawText;
  1812. exports.images = require("./images");
  1813. exports.transforms = require("./transforms");
  1814. exports.underline = require("./underline");
  1815. exports.embedStyleMap = embedStyleMap;
  1816. exports.readEmbeddedStyleMap = readEmbeddedStyleMap;
  1817. function convertToHtml(input, options) {
  1818. return convert(input, options);
  1819. }
  1820. function convertToMarkdown(input, options) {
  1821. var markdownOptions = Object.create(options || {});
  1822. markdownOptions.outputFormat = "markdown";
  1823. return convert(input, markdownOptions);
  1824. }
  1825. function convert(input, options) {
  1826. options = Object.create(options || {});
  1827. return unzip.openZip(input)
  1828. .tap(function(docxFile) {
  1829. if (!options.styleMap) {
  1830. return docxStyleMap.readStyleMap(docxFile).then(function(styleMap) {
  1831. options.styleMap = styleMap || "";
  1832. });
  1833. }
  1834. })
  1835. .then(function(docxFile) {
  1836. var fullOptions = readOptions(options);
  1837. return docxReader.read(docxFile, input)
  1838. .then(function(documentResult) {
  1839. return documentResult.map(fullOptions.transformDocument);
  1840. })
  1841. .then(function(documentResult) {
  1842. return convertDocumentToHtml(documentResult, fullOptions);
  1843. });
  1844. });
  1845. }
  1846. function readEmbeddedStyleMap(input) {
  1847. return unzip.openZip(input)
  1848. .then(docxStyleMap.readStyleMap);
  1849. }
  1850. function convertDocumentToHtml(documentResult, options) {
  1851. var parsedOptions = Object.create(options);
  1852. var styleMapResult = parseStyleMap(options.styleMap);
  1853. parsedOptions.styleMap = styleMapResult.value;
  1854. var documentConverter = new DocumentConverter(parsedOptions);
  1855. return documentResult.flatMapThen(function(document) {
  1856. return styleMapResult.flatMapThen(function(styleMap) {
  1857. return documentConverter.convertToHtml(document);
  1858. });
  1859. });
  1860. }
  1861. function parseStyleMap(styleMap) {
  1862. return Result.combine((styleMap || []).map(readStyle))
  1863. .map(function(styleMap) {
  1864. return styleMap.filter(function(styleMapping) {
  1865. return !!styleMapping;
  1866. });
  1867. });
  1868. }
  1869. function extractRawText(input) {
  1870. return unzip.openZip(input)
  1871. .then(docxReader.read)
  1872. .then(function(documentResult) {
  1873. return documentResult.map(convertElementToRawText);
  1874. });
  1875. }
  1876. function convertElementToRawText(element) {
  1877. if (element.type === "text") {
  1878. return element.value;
  1879. } else {
  1880. var tail = element.type === "paragraph" ? "\n\n" : "";
  1881. return (element.children || []).map(convertElementToRawText).join("") + tail;
  1882. }
  1883. }
  1884. function embedStyleMap(input, styleMap) {
  1885. return unzip.openZip(input)
  1886. .tap(function(docxFile) {
  1887. return docxStyleMap.writeStyleMap(docxFile, styleMap);
  1888. })
  1889. .then(function(docxFile) {
  1890. return {
  1891. toBuffer: docxFile.toBuffer
  1892. };
  1893. });
  1894. }
  1895. exports.styleMapping = function() {
  1896. throw new Error('Use a raw string instead of mammoth.styleMapping e.g. "p[style-name=\'Title\'] => h1" instead of mammoth.styleMapping("p[style-name=\'Title\'] => h1")');
  1897. };
  1898. },{"./document-to-html":4,"./docx/docx-reader":10,"./docx/style-map":15,"./images":21,"./options-reader":23,"./results":25,"./style-reader":26,"./transforms":27,"./underline":28,"./unzip":2}],23:[function(require,module,exports){
  1899. exports.readOptions = readOptions;
  1900. var _ = require("underscore");
  1901. var standardOptions = exports._standardOptions = {
  1902. styleMap: [
  1903. "p.Heading1 => h1:fresh",
  1904. "p.Heading2 => h2:fresh",
  1905. "p.Heading3 => h3:fresh",
  1906. "p.Heading4 => h4:fresh",
  1907. "p[style-name='Heading 1'] => h1:fresh",
  1908. "p[style-name='Heading 2'] => h2:fresh",
  1909. "p[style-name='Heading 3'] => h3:fresh",
  1910. "p[style-name='Heading 4'] => h4:fresh",
  1911. "p[style-name='heading 1'] => h1:fresh",
  1912. "p[style-name='heading 2'] => h2:fresh",
  1913. "p[style-name='heading 3'] => h3:fresh",
  1914. "p[style-name='heading 4'] => h4:fresh",
  1915. "p[style-name='heading 4'] => h4:fresh",
  1916. "r[style-name='Strong'] => strong",
  1917. "p[style-name='footnote text'] => p",
  1918. "r[style-name='footnote reference'] =>",
  1919. "p[style-name='endnote text'] => p",
  1920. "r[style-name='endnote reference'] =>",
  1921. "p[style-name='annotation text'] => p",
  1922. "r[style-name='annotation reference'] =>",
  1923. // LibreOffice
  1924. "p[style-name='Footnote'] => p",
  1925. "r[style-name='Footnote anchor'] =>",
  1926. "p[style-name='Endnote'] => p",
  1927. "r[style-name='Endnote anchor'] =>",
  1928. "p:unordered-list(1) => ul > li:fresh",
  1929. "p:unordered-list(2) => ul|ol > li > ul > li:fresh",
  1930. "p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh",
  1931. "p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
  1932. "p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
  1933. "p:ordered-list(1) => ol > li:fresh",
  1934. "p:ordered-list(2) => ul|ol > li > ol > li:fresh",
  1935. "p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh",
  1936. "p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
  1937. "p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
  1938. "r[style-name='Hyperlink'] =>",
  1939. "p[style-name='Normal'] => p:fresh"
  1940. ],
  1941. transformDocument: identity,
  1942. includeDefaultStyleMap: true
  1943. };
  1944. function readOptions(options) {
  1945. options = options || {};
  1946. var fullOptions = {};
  1947. _.extend(fullOptions, standardOptions, options);
  1948. fullOptions.styleMap = readStyleMap(options.styleMap, fullOptions);
  1949. return fullOptions;
  1950. }
  1951. function readStyleMap(styleMap, options) {
  1952. var customStyleMap = readCustomStyleMap(styleMap);
  1953. return customStyleMap.concat(options.includeDefaultStyleMap ? standardOptions.styleMap : []);
  1954. }
  1955. function readCustomStyleMap(styleMap) {
  1956. if (!styleMap) {
  1957. return [];
  1958. } else if (_.isString(styleMap)) {
  1959. return styleMap.split("\n")
  1960. .map(function(line) {
  1961. return line.trim();
  1962. })
  1963. .filter(function(line) {
  1964. return line !== "" && line.charAt(0) !== "#";
  1965. });
  1966. } else {
  1967. return styleMap;
  1968. }
  1969. }
  1970. function identity(value) {
  1971. return value;
  1972. }
  1973. },{"underscore":154}],24:[function(require,module,exports){
  1974. var _ = require("underscore");
  1975. var bluebird = require("bluebird/js/release/promise")();
  1976. exports.defer = bluebird.defer;
  1977. exports.when = bluebird.resolve;
  1978. exports.resolve = bluebird.resolve;
  1979. exports.all = bluebird.all;
  1980. exports.props = bluebird.props;
  1981. exports.reject = bluebird.reject;
  1982. exports.promisify = bluebird.promisify;
  1983. exports.mapSeries = bluebird.mapSeries;
  1984. exports.attempt = bluebird.attempt;
  1985. exports.nfcall = function(func) {
  1986. var args = Array.prototype.slice.call(arguments, 1);
  1987. var promisedFunc = bluebird.promisify(func);
  1988. return promisedFunc.apply(null, args);
  1989. };
  1990. bluebird.prototype.fail = bluebird.prototype.caught;
  1991. bluebird.prototype.also = function(func) {
  1992. return this.then(function(value) {
  1993. var returnValue = _.extend({}, value, func(value));
  1994. return bluebird.props(returnValue);
  1995. });
  1996. };
  1997. },{"bluebird/js/release/promise":57,"underscore":154}],25:[function(require,module,exports){
  1998. var _ = require("underscore");
  1999. exports.Result = Result;
  2000. exports.success = success;
  2001. exports.warning = warning;
  2002. exports.error = error;
  2003. function Result(value, messages) {
  2004. this.value = value;
  2005. this.messages = messages || [];
  2006. }
  2007. Result.prototype.map = function(func) {
  2008. return new Result(func(this.value), this.messages);
  2009. };
  2010. Result.prototype.flatMap = function(func) {
  2011. var funcResult = func(this.value);
  2012. return new Result(funcResult.value, combineMessages([this, funcResult]));
  2013. };
  2014. Result.prototype.flatMapThen = function(func) {
  2015. var that = this;
  2016. return func(this.value).then(function(otherResult) {
  2017. return new Result(otherResult.value, combineMessages([that, otherResult]));
  2018. });
  2019. };
  2020. Result.combine = function(results) {
  2021. var values = _.flatten(_.pluck(results, "value"));
  2022. var messages = combineMessages(results);
  2023. return new Result(values, messages);
  2024. };
  2025. function success(value) {
  2026. return new Result(value, []);
  2027. }
  2028. function warning(message) {
  2029. return {
  2030. type: "warning",
  2031. message: message
  2032. };
  2033. }
  2034. function error(exception) {
  2035. return {
  2036. type: "error",
  2037. message: exception.message,
  2038. error: exception
  2039. };
  2040. }
  2041. function combineMessages(results) {
  2042. var messages = [];
  2043. _.flatten(_.pluck(results, "messages"), true).forEach(function(message) {
  2044. if (!containsMessage(messages, message)) {
  2045. messages.push(message);
  2046. }
  2047. });
  2048. return messages;
  2049. }
  2050. function containsMessage(messages, message) {
  2051. return _.find(messages, isSameMessage.bind(null, message)) !== undefined;
  2052. }
  2053. function isSameMessage(first, second) {
  2054. return first.type === second.type && first.message === second.message;
  2055. }
  2056. },{"underscore":154}],26:[function(require,module,exports){
  2057. var _ = require("underscore");
  2058. var lop = require("lop");
  2059. var RegexTokeniser = lop.RegexTokeniser;
  2060. var documentMatchers = require("./document-matchers");
  2061. var htmlPaths = require("./html-paths");
  2062. var results = require("../lib/results");
  2063. exports.readHtmlPath = readHtmlPath;
  2064. exports.readDocumentMatcher = readDocumentMatcher;
  2065. exports.readStyle = readStyle;
  2066. function readStyle(string) {
  2067. return parseString(styleRule, string);
  2068. }
  2069. function createStyleRule() {
  2070. return lop.rules.sequence(
  2071. lop.rules.sequence.capture(documentMatcherRule()),
  2072. lop.rules.tokenOfType("whitespace"),
  2073. lop.rules.tokenOfType("arrow"),
  2074. lop.rules.sequence.capture(lop.rules.optional(lop.rules.sequence(
  2075. lop.rules.tokenOfType("whitespace"),
  2076. lop.rules.sequence.capture(htmlPathRule())
  2077. ).head())),
  2078. lop.rules.tokenOfType("end")
  2079. ).map(function(documentMatcher, htmlPath) {
  2080. return {
  2081. from: documentMatcher,
  2082. to: htmlPath.valueOrElse(htmlPaths.empty)
  2083. };
  2084. });
  2085. }
  2086. function readDocumentMatcher(string) {
  2087. return parseString(documentMatcherRule(), string);
  2088. }
  2089. function documentMatcherRule() {
  2090. var sequence = lop.rules.sequence;
  2091. var identifierToConstant = function(identifier, constant) {
  2092. return lop.rules.then(
  2093. lop.rules.token("identifier", identifier),
  2094. function() {
  2095. return constant;
  2096. }
  2097. );
  2098. };
  2099. var paragraphRule = identifierToConstant("p", documentMatchers.paragraph);
  2100. var runRule = identifierToConstant("r", documentMatchers.run);
  2101. var elementTypeRule = lop.rules.firstOf("p or r",
  2102. paragraphRule,
  2103. runRule
  2104. );
  2105. var styleIdRule = lop.rules.then(
  2106. classRule,
  2107. function(styleId) {
  2108. return {styleId: styleId};
  2109. }
  2110. );
  2111. var stringRule = lop.rules.then(
  2112. lop.rules.tokenOfType("string"),
  2113. function(value) {
  2114. return value;
  2115. }
  2116. );
  2117. var styleNameRule = lop.rules.then(
  2118. lop.rules.sequence(
  2119. lop.rules.tokenOfType("open-square-bracket"),
  2120. lop.rules.token("identifier", "style-name"),
  2121. lop.rules.tokenOfType("equals"),
  2122. lop.rules.sequence.capture(stringRule),
  2123. lop.rules.tokenOfType("close-square-bracket")
  2124. ).head(),
  2125. function(styleName) {
  2126. return {styleName: styleName};
  2127. }
  2128. );
  2129. var listTypeRule = lop.rules.firstOf("list type",
  2130. identifierToConstant("ordered-list", {isOrdered: true}),
  2131. identifierToConstant("unordered-list", {isOrdered: false})
  2132. );
  2133. var listRule = sequence(
  2134. lop.rules.tokenOfType("colon"),
  2135. sequence.capture(listTypeRule),
  2136. sequence.cut(),
  2137. lop.rules.tokenOfType("open-paren"),
  2138. sequence.capture(integerRule),
  2139. lop.rules.tokenOfType("close-paren")
  2140. ).map(function(listType, levelNumber) {
  2141. return {
  2142. list: {
  2143. isOrdered: listType.isOrdered,
  2144. levelIndex: levelNumber - 1
  2145. }
  2146. };
  2147. });
  2148. var matcherSuffix = lop.rules.firstOf("matcher suffix",
  2149. styleIdRule,
  2150. styleNameRule,
  2151. listRule
  2152. );
  2153. var matcherSuffixes = lop.rules.zeroOrMore(matcherSuffix);
  2154. var paragraphOrRun = sequence(
  2155. sequence.capture(elementTypeRule),
  2156. sequence.capture(matcherSuffixes)
  2157. ).map(function(createMatcher, suffixes) {
  2158. var matcherOptions = {};
  2159. suffixes.forEach(function(suffix) {
  2160. _.extend(matcherOptions, suffix);
  2161. });
  2162. return createMatcher(matcherOptions);
  2163. });
  2164. var bold = identifierToConstant("b", documentMatchers.bold);
  2165. var italic = identifierToConstant("i", documentMatchers.italic);
  2166. var underline = identifierToConstant("u", documentMatchers.underline);
  2167. var strikethrough = identifierToConstant("strike", documentMatchers.strikethrough);
  2168. var commentReference = identifierToConstant("comment-reference", documentMatchers.commentReference);
  2169. return lop.rules.firstOf("element type",
  2170. paragraphOrRun,
  2171. bold,
  2172. italic,
  2173. underline,
  2174. strikethrough,
  2175. commentReference
  2176. );
  2177. }
  2178. function readHtmlPath(string) {
  2179. return parseString(htmlPathRule(), string);
  2180. }
  2181. function htmlPathRule() {
  2182. var capture = lop.rules.sequence.capture;
  2183. var whitespaceRule = lop.rules.tokenOfType("whitespace");
  2184. var freshRule = lop.rules.then(
  2185. lop.rules.optional(lop.rules.sequence(
  2186. lop.rules.tokenOfType("colon"),
  2187. lop.rules.token("identifier", "fresh")
  2188. )),
  2189. function(option) {
  2190. return option.map(function() {
  2191. return true;
  2192. }).valueOrElse(false);
  2193. }
  2194. );
  2195. var tagNamesRule = lop.rules.oneOrMoreWithSeparator(
  2196. identifierRule,
  2197. lop.rules.tokenOfType("choice")
  2198. );
  2199. var styleElementRule = lop.rules.sequence(
  2200. capture(tagNamesRule),
  2201. capture(lop.rules.zeroOrMore(classRule)),
  2202. capture(freshRule)
  2203. ).map(function(tagName, classNames, fresh) {
  2204. var attributes = {};
  2205. var options = {};
  2206. if (classNames.length > 0) {
  2207. attributes["class"] = classNames.join(" ");
  2208. }
  2209. if (fresh) {
  2210. options.fresh = true;
  2211. }
  2212. return htmlPaths.element(tagName, attributes, options);
  2213. });
  2214. return lop.rules.firstOf("html path",
  2215. lop.rules.then(lop.rules.tokenOfType("bang"), function() {
  2216. return htmlPaths.ignore;
  2217. }),
  2218. lop.rules.then(
  2219. lop.rules.zeroOrMoreWithSeparator(
  2220. styleElementRule,
  2221. lop.rules.sequence(
  2222. whitespaceRule,
  2223. lop.rules.tokenOfType("gt"),
  2224. whitespaceRule
  2225. )
  2226. ),
  2227. htmlPaths.elements
  2228. )
  2229. );
  2230. }
  2231. var identifierRule = lop.rules.tokenOfType("identifier");
  2232. var integerRule = lop.rules.tokenOfType("integer");
  2233. var classRule = lop.rules.sequence(
  2234. lop.rules.tokenOfType("dot"),
  2235. lop.rules.sequence.capture(identifierRule)
  2236. ).head();
  2237. function parseString(rule, string) {
  2238. var tokens = tokenise(string);
  2239. var parser = lop.Parser();
  2240. var parseResult = parser.parseTokens(rule, tokens);
  2241. if (parseResult.isSuccess()) {
  2242. return results.success(parseResult.value());
  2243. } else {
  2244. return new results.Result(null, [results.warning(describeFailure(string, parseResult))]);
  2245. }
  2246. }
  2247. function describeFailure(input, parseResult) {
  2248. return "Did not understand this style mapping, so ignored it: " + input + "\n" +
  2249. parseResult.errors().map(describeError).join("\n");
  2250. }
  2251. function describeError(error) {
  2252. return "Error was at character number " + error.characterNumber() + ": " +
  2253. "Expected " + error.expected + " but got " + error.actual;
  2254. }
  2255. function tokenise(string) {
  2256. var tokeniser = new RegexTokeniser([
  2257. {name: "identifier", regex: /([a-zA-Z][a-zA-Z0-9\-]*)/},
  2258. {name: "dot", regex: /\./},
  2259. {name: "colon", regex: /:/},
  2260. {name: "gt", regex: />/},
  2261. {name: "whitespace", regex: /\s+/},
  2262. {name: "arrow", regex: /=>/},
  2263. {name: "equals", regex: /=/},
  2264. {name: "open-paren", regex: /\(/},
  2265. {name: "close-paren", regex: /\)/},
  2266. {name: "open-square-bracket", regex: /\[/},
  2267. {name: "close-square-bracket", regex: /\]/},
  2268. {name: "string", regex: /'([^']*)'/},
  2269. {name: "integer", regex: /([0-9]+)/},
  2270. {name: "choice", regex: /\|/},
  2271. {name: "bang", regex: /(!)/}
  2272. ]);
  2273. return tokeniser.tokenise(string);
  2274. }
  2275. var styleRule = createStyleRule();
  2276. },{"../lib/results":25,"./document-matchers":3,"./html-paths":17,"lop":140,"underscore":154}],27:[function(require,module,exports){
  2277. var _ = require("underscore");
  2278. exports.paragraph = function(transform) {
  2279. function transformElement(element) {
  2280. if (element.children) {
  2281. var children = _.map(element.children, transformElement);
  2282. element = _.extend(element, {children: children});
  2283. }
  2284. if (element.type === "paragraph") {
  2285. element = transform(element);
  2286. }
  2287. return element;
  2288. }
  2289. return transformElement;
  2290. };
  2291. },{"underscore":154}],28:[function(require,module,exports){
  2292. var htmlPaths = require("./html-paths");
  2293. var Html = require("./html");
  2294. exports.element = element;
  2295. function element(name) {
  2296. return function(html) {
  2297. return Html.elementWithTag(htmlPaths.element(name), [html]);
  2298. };
  2299. }
  2300. },{"./html":19,"./html-paths":17}],29:[function(require,module,exports){
  2301. var util = require("util");
  2302. var _ = require("underscore");
  2303. exports.writer = writer;
  2304. function writer(options) {
  2305. options = options || {};
  2306. if (options.prettyPrint) {
  2307. return prettyWriter();
  2308. } else {
  2309. return simpleWriter();
  2310. }
  2311. }
  2312. var indentedElements = {
  2313. div: true,
  2314. p: true,
  2315. ul: true,
  2316. li: true
  2317. };
  2318. function prettyWriter() {
  2319. var indentationLevel = 0;
  2320. var indentation = " ";
  2321. var stack = [];
  2322. var start = true;
  2323. var inText = false;
  2324. var writer = simpleWriter();
  2325. function open(tagName, attributes) {
  2326. if (indentedElements[tagName]) {
  2327. indent();
  2328. }
  2329. stack.push(tagName);
  2330. writer.open(tagName, attributes);
  2331. if (indentedElements[tagName]) {
  2332. indentationLevel++;
  2333. }
  2334. start = false;
  2335. }
  2336. function close(tagName) {
  2337. if (indentedElements[tagName]) {
  2338. indentationLevel--;
  2339. indent();
  2340. }
  2341. stack.pop();
  2342. writer.close(tagName);
  2343. }
  2344. function text(value) {
  2345. startText();
  2346. writer.text(value.replace("\n", "\n" + indentation));
  2347. }
  2348. function selfClosing(tagName, attributes) {
  2349. indent();
  2350. writer.selfClosing(tagName, attributes);
  2351. }
  2352. function append(html) {
  2353. startText();
  2354. writer.append(html.replace("\n", "\n" + indentation));
  2355. }
  2356. function insideIndentedElement() {
  2357. return stack.length === 0 || indentedElements[stack[stack.length - 1]];
  2358. }
  2359. function startText() {
  2360. if (!inText) {
  2361. indent();
  2362. inText = true;
  2363. }
  2364. }
  2365. function indent() {
  2366. inText = false;
  2367. if (!start && insideIndentedElement()) {
  2368. writer.append("\n");
  2369. for (var i = 0; i < indentationLevel; i++) {
  2370. writer.append(indentation);
  2371. }
  2372. }
  2373. }
  2374. return {
  2375. asString: writer.asString,
  2376. open: open,
  2377. close: close,
  2378. text: text,
  2379. selfClosing: selfClosing,
  2380. append: append
  2381. };
  2382. }
  2383. function simpleWriter() {
  2384. var fragments = [];
  2385. function open(tagName, attributes) {
  2386. var attributeString = generateAttributeString(attributes);
  2387. fragments.push(util.format("<%s%s>", tagName, attributeString));
  2388. }
  2389. function close(tagName) {
  2390. fragments.push(util.format("</%s>", tagName));
  2391. }
  2392. function selfClosing(tagName, attributes) {
  2393. var attributeString = generateAttributeString(attributes);
  2394. fragments.push(util.format("<%s%s />", tagName, attributeString));
  2395. }
  2396. function generateAttributeString(attributes) {
  2397. return _.map(attributes, function(value, key) {
  2398. return util.format(' %s="%s"', key, escapeHtmlAttribute(value));
  2399. }).join("");
  2400. }
  2401. function text(value) {
  2402. fragments.push(escapeHtmlText(value));
  2403. }
  2404. function append(html) {
  2405. fragments.push(html);
  2406. }
  2407. function asString() {
  2408. return fragments.join("");
  2409. }
  2410. return {
  2411. asString: asString,
  2412. open: open,
  2413. close: close,
  2414. text: text,
  2415. selfClosing: selfClosing,
  2416. append: append
  2417. };
  2418. }
  2419. function escapeHtmlText(value) {
  2420. return value
  2421. .replace(/&/g, '&amp;')
  2422. .replace(/</g, '&lt;')
  2423. .replace(/>/g, '&gt;');
  2424. }
  2425. function escapeHtmlAttribute(value) {
  2426. return value
  2427. .replace(/&/g, '&amp;')
  2428. .replace(/"/g, '&quot;')
  2429. .replace(/</g, '&lt;')
  2430. .replace(/>/g, '&gt;');
  2431. }
  2432. },{"underscore":154,"util":100}],30:[function(require,module,exports){
  2433. var htmlWriter = require("./html-writer");
  2434. var markdownWriter = require("./markdown-writer");
  2435. exports.writer = writer;
  2436. function writer(options) {
  2437. options = options || {};
  2438. if (options.outputFormat === "markdown") {
  2439. return markdownWriter.writer();
  2440. } else {
  2441. return htmlWriter.writer(options);
  2442. }
  2443. }
  2444. },{"./html-writer":29,"./markdown-writer":31}],31:[function(require,module,exports){
  2445. var _ = require("underscore");
  2446. function symmetricMarkdownElement(end) {
  2447. return markdownElement(end, end);
  2448. }
  2449. function markdownElement(start, end) {
  2450. return function() {
  2451. return {start: start, end: end};
  2452. };
  2453. }
  2454. function markdownLink(attributes) {
  2455. var href = attributes.href || "";
  2456. if (href) {
  2457. return {
  2458. start: "[",
  2459. end: "](" + href + ")",
  2460. anchorPosition: "before"
  2461. };
  2462. } else {
  2463. return {};
  2464. }
  2465. }
  2466. function markdownImage(attributes) {
  2467. var src = attributes.src || "";
  2468. var altText = attributes.alt || "";
  2469. if (src || altText) {
  2470. return {start: "![" + altText + "](" + src + ")"};
  2471. } else {
  2472. return {};
  2473. }
  2474. }
  2475. function markdownList(options) {
  2476. return function(attributes, list) {
  2477. return {
  2478. start: list ? "\n" : "",
  2479. end: list ? "" : "\n",
  2480. list: {
  2481. isOrdered: options.isOrdered,
  2482. indent: list ? list.indent + 1 : 0,
  2483. count: 0
  2484. }
  2485. };
  2486. };
  2487. }
  2488. function markdownListItem(attributes, list, listItem) {
  2489. list = list || {indent: 0, isOrdered: false, count: 0};
  2490. list.count++;
  2491. listItem.hasClosed = false;
  2492. var bullet = list.isOrdered ? list.count + "." : "-";
  2493. var start = repeatString("\t", list.indent) + bullet + " ";
  2494. return {
  2495. start: start,
  2496. end: function() {
  2497. if (!listItem.hasClosed) {
  2498. listItem.hasClosed = true;
  2499. return "\n";
  2500. }
  2501. }
  2502. };
  2503. }
  2504. var htmlToMarkdown = {
  2505. "p": markdownElement("", "\n\n"),
  2506. "br": markdownElement("", " \n"),
  2507. "ul": markdownList({isOrdered: false}),
  2508. "ol": markdownList({isOrdered: true}),
  2509. "li": markdownListItem,
  2510. "strong": symmetricMarkdownElement("__"),
  2511. "em": symmetricMarkdownElement("*"),
  2512. "a": markdownLink,
  2513. "img": markdownImage
  2514. };
  2515. (function() {
  2516. for (var i = 1; i <= 6; i++) {
  2517. htmlToMarkdown["h" + i] = markdownElement(repeatString("#", i) + " ", "\n\n");
  2518. }
  2519. })();
  2520. function repeatString(value, count) {
  2521. return new Array(count + 1).join(value);
  2522. }
  2523. function markdownWriter() {
  2524. var fragments = [];
  2525. var elementStack = [];
  2526. var list = null;
  2527. var listItem = {};
  2528. function open(tagName, attributes) {
  2529. attributes = attributes || {};
  2530. var createElement = htmlToMarkdown[tagName] || function() {
  2531. return {};
  2532. };
  2533. var element = createElement(attributes, list, listItem);
  2534. elementStack.push({end: element.end, list: list});
  2535. if (element.list) {
  2536. list = element.list;
  2537. }
  2538. var anchorBeforeStart = element.anchorPosition === "before";
  2539. if (anchorBeforeStart) {
  2540. writeAnchor(attributes);
  2541. }
  2542. fragments.push(element.start || "");
  2543. if (!anchorBeforeStart) {
  2544. writeAnchor(attributes);
  2545. }
  2546. }
  2547. function writeAnchor(attributes) {
  2548. if (attributes.id) {
  2549. fragments.push('<a id="' + attributes.id + '"></a>');
  2550. }
  2551. }
  2552. function close(tagName) {
  2553. var element = elementStack.pop();
  2554. list = element.list;
  2555. var end = _.isFunction(element.end) ? element.end() : element.end;
  2556. fragments.push(end || "");
  2557. }
  2558. function selfClosing(tagName, attributes) {
  2559. open(tagName, attributes);
  2560. close(tagName);
  2561. }
  2562. function text(value) {
  2563. fragments.push(escapeMarkdown(value));
  2564. }
  2565. function append(html) {
  2566. fragments.push(html);
  2567. }
  2568. function asString() {
  2569. return fragments.join("");
  2570. }
  2571. return {
  2572. asString: asString,
  2573. open: open,
  2574. close: close,
  2575. text: text,
  2576. selfClosing: selfClosing,
  2577. append: append
  2578. };
  2579. }
  2580. exports.writer = markdownWriter;
  2581. function escapeMarkdown(value) {
  2582. return value
  2583. .replace(/\\/g, '\\\\')
  2584. .replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g, '\\$1');
  2585. }
  2586. },{"underscore":154}],32:[function(require,module,exports){
  2587. var nodes = require("./nodes");
  2588. exports.Element = nodes.Element;
  2589. exports.element = nodes.element;
  2590. exports.text = nodes.text;
  2591. exports.readString = require("./reader").readString;
  2592. exports.writeString = require("./writer").writeString;
  2593. },{"./nodes":33,"./reader":34,"./writer":35}],33:[function(require,module,exports){
  2594. var _ = require("underscore");
  2595. exports.Element = Element;
  2596. exports.element = function(name, attributes, children) {
  2597. return new Element(name, attributes, children);
  2598. };
  2599. exports.text = function(value) {
  2600. return {
  2601. type: "text",
  2602. value: value
  2603. };
  2604. };
  2605. var emptyElement = {
  2606. first: function() {
  2607. return null;
  2608. },
  2609. firstOrEmpty: function() {
  2610. return emptyElement;
  2611. },
  2612. attributes: {}
  2613. };
  2614. function Element(name, attributes, children) {
  2615. this.type = "element";
  2616. this.name = name;
  2617. this.attributes = attributes || {};
  2618. this.children = children || [];
  2619. }
  2620. Element.prototype.first = function(name) {
  2621. return _.find(this.children, function(child) {
  2622. return child.name === name;
  2623. });
  2624. };
  2625. Element.prototype.firstOrEmpty = function(name) {
  2626. return this.first(name) || emptyElement;
  2627. };
  2628. Element.prototype.getElementsByTagName = function(name) {
  2629. var elements = _.filter(this.children, function(child) {
  2630. return child.name === name;
  2631. });
  2632. return toElementList(elements);
  2633. };
  2634. Element.prototype.text = function() {
  2635. if (this.children.length === 0) {
  2636. return "";
  2637. } else if (this.children.length !== 1 || this.children[0].type !== "text") {
  2638. throw new Error("Not implemented");
  2639. }
  2640. return this.children[0].value;
  2641. };
  2642. var elementListPrototype = {
  2643. getElementsByTagName: function(name) {
  2644. return toElementList(_.flatten(this.map(function(element) {
  2645. return element.getElementsByTagName(name);
  2646. }, true)));
  2647. }
  2648. };
  2649. function toElementList(array) {
  2650. return _.extend(array, elementListPrototype);
  2651. }
  2652. },{"underscore":154}],34:[function(require,module,exports){
  2653. var promises = require("../promises");
  2654. var sax = require("sax");
  2655. var _ = require("underscore");
  2656. var nodes = require("./nodes");
  2657. var Element = nodes.Element;
  2658. exports.readString = readString;
  2659. function readString(xmlString, namespaceMap) {
  2660. namespaceMap = namespaceMap || {};
  2661. var finished = false;
  2662. var parser = sax.parser(true, {xmlns: true, position: false});
  2663. var rootElement = {children: []};
  2664. var currentElement = rootElement;
  2665. var stack = [];
  2666. var deferred = promises.defer();
  2667. parser.onopentag = function(node) {
  2668. var attributes = mapObject(node.attributes, function(attribute) {
  2669. return attribute.value;
  2670. }, mapName);
  2671. var element = new Element(mapName(node), attributes);
  2672. currentElement.children.push(element);
  2673. stack.push(currentElement);
  2674. currentElement = element;
  2675. };
  2676. function mapName(node) {
  2677. if (node.uri) {
  2678. var mappedPrefix = namespaceMap[node.uri];
  2679. var prefix;
  2680. if (mappedPrefix) {
  2681. prefix = mappedPrefix + ":";
  2682. } else {
  2683. prefix = "{" + node.uri + "}";
  2684. }
  2685. return prefix + node.local;
  2686. } else {
  2687. return node.local;
  2688. }
  2689. }
  2690. parser.onclosetag = function(node) {
  2691. currentElement = stack.pop();
  2692. };
  2693. parser.ontext = function(text) {
  2694. if (currentElement !== rootElement) {
  2695. currentElement.children.push(nodes.text(text));
  2696. }
  2697. };
  2698. parser.onend = function() {
  2699. if (!finished) {
  2700. finished = true;
  2701. deferred.resolve(rootElement.children[0]);
  2702. }
  2703. };
  2704. parser.onerror = function(error) {
  2705. if (!finished) {
  2706. finished = true;
  2707. deferred.reject(error);
  2708. }
  2709. };
  2710. parser.write(xmlString).close();
  2711. return deferred.promise;
  2712. }
  2713. function mapObject(input, valueFunc, keyFunc) {
  2714. return _.reduce(input, function(result, value, key) {
  2715. var mappedKey = keyFunc(value, key, input);
  2716. result[mappedKey] = valueFunc(value, key, input);
  2717. return result;
  2718. }, {});
  2719. }
  2720. },{"../promises":24,"./nodes":33,"sax":153,"underscore":154}],35:[function(require,module,exports){
  2721. var _ = require("underscore");
  2722. var xmlbuilder = require("xmlbuilder");
  2723. exports.writeString = writeString;
  2724. function writeString(root, namespaces) {
  2725. var uriToPrefix = _.invert(namespaces);
  2726. var nodeWriters = {
  2727. element: writeElement,
  2728. text: writeTextNode
  2729. };
  2730. function writeNode(builder, node) {
  2731. return nodeWriters[node.type](builder, node);
  2732. }
  2733. function writeElement(builder, element) {
  2734. var elementBuilder = builder.element(mapElementName(element.name), element.attributes);
  2735. element.children.forEach(function(child) {
  2736. writeNode(elementBuilder, child);
  2737. });
  2738. }
  2739. function mapElementName(name) {
  2740. var longFormMatch = /^\{(.*)\}(.*)$/.exec(name);
  2741. if (longFormMatch) {
  2742. var prefix = uriToPrefix[longFormMatch[1]];
  2743. return prefix + (prefix === "" ? "" : ":") + longFormMatch[2];
  2744. } else {
  2745. return name;
  2746. }
  2747. }
  2748. function writeDocument(root) {
  2749. var builder = xmlbuilder
  2750. .create(mapElementName(root.name), {
  2751. version: '1.0',
  2752. encoding: 'UTF-8',
  2753. standalone: true
  2754. });
  2755. _.forEach(namespaces, function(uri, prefix) {
  2756. var key = "xmlns" + (prefix === "" ? "" : ":" + prefix);
  2757. builder.attribute(key, uri);
  2758. });
  2759. root.children.forEach(function(child) {
  2760. writeNode(builder, child);
  2761. });
  2762. return builder.end();
  2763. }
  2764. return writeDocument(root);
  2765. }
  2766. function writeTextNode(builder, node) {
  2767. builder.text(node.value);
  2768. }
  2769. },{"underscore":154,"xmlbuilder":171}],36:[function(require,module,exports){
  2770. (function (Buffer){
  2771. var JSZip = require("jszip");
  2772. var promises = require("./promises");
  2773. exports.openArrayBuffer = openArrayBuffer;
  2774. function openArrayBuffer(arrayBuffer) {
  2775. var zipFile = new JSZip(arrayBuffer);
  2776. function exists(name) {
  2777. return zipFile.file(name) !== null;
  2778. }
  2779. function read(name, encoding) {
  2780. var array = zipFile.file(name).asUint8Array();
  2781. var buffer = new Buffer(array);
  2782. if (encoding) {
  2783. return promises.when(buffer.toString(encoding));
  2784. } else {
  2785. return promises.when(buffer);
  2786. }
  2787. }
  2788. function write(name, contents) {
  2789. zipFile.file(name, contents);
  2790. }
  2791. function toBuffer() {
  2792. return zipFile.generate({type: "nodebuffer"});
  2793. }
  2794. return {
  2795. exists: exists,
  2796. read: read,
  2797. write: write,
  2798. toBuffer: toBuffer
  2799. };
  2800. }
  2801. }).call(this,require("buffer").Buffer)
  2802. },{"./promises":24,"buffer":73,"jszip":109}],37:[function(require,module,exports){
  2803. "use strict";
  2804. module.exports = function(Promise) {
  2805. var SomePromiseArray = Promise._SomePromiseArray;
  2806. function any(promises) {
  2807. var ret = new SomePromiseArray(promises);
  2808. var promise = ret.promise();
  2809. ret.setHowMany(1);
  2810. ret.setUnwrap();
  2811. ret.init();
  2812. return promise;
  2813. }
  2814. Promise.any = function (promises) {
  2815. return any(promises);
  2816. };
  2817. Promise.prototype.any = function () {
  2818. return any(this);
  2819. };
  2820. };
  2821. },{}],38:[function(require,module,exports){
  2822. (function (process){
  2823. "use strict";
  2824. var firstLineError;
  2825. try {throw new Error(); } catch (e) {firstLineError = e;}
  2826. var schedule = require("./schedule");
  2827. var Queue = require("./queue");
  2828. var util = require("./util");
  2829. function Async() {
  2830. this._customScheduler = false;
  2831. this._isTickUsed = false;
  2832. this._lateQueue = new Queue(16);
  2833. this._normalQueue = new Queue(16);
  2834. this._haveDrainedQueues = false;
  2835. this._trampolineEnabled = true;
  2836. var self = this;
  2837. this.drainQueues = function () {
  2838. self._drainQueues();
  2839. };
  2840. this._schedule = schedule;
  2841. }
  2842. Async.prototype.setScheduler = function(fn) {
  2843. var prev = this._schedule;
  2844. this._schedule = fn;
  2845. this._customScheduler = true;
  2846. return prev;
  2847. };
  2848. Async.prototype.hasCustomScheduler = function() {
  2849. return this._customScheduler;
  2850. };
  2851. Async.prototype.enableTrampoline = function() {
  2852. this._trampolineEnabled = true;
  2853. };
  2854. Async.prototype.disableTrampolineIfNecessary = function() {
  2855. if (util.hasDevTools) {
  2856. this._trampolineEnabled = false;
  2857. }
  2858. };
  2859. Async.prototype.haveItemsQueued = function () {
  2860. return this._isTickUsed || this._haveDrainedQueues;
  2861. };
  2862. Async.prototype.fatalError = function(e, isNode) {
  2863. if (isNode) {
  2864. process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
  2865. "\n");
  2866. process.exit(2);
  2867. } else {
  2868. this.throwLater(e);
  2869. }
  2870. };
  2871. Async.prototype.throwLater = function(fn, arg) {
  2872. if (arguments.length === 1) {
  2873. arg = fn;
  2874. fn = function () { throw arg; };
  2875. }
  2876. if (typeof setTimeout !== "undefined") {
  2877. setTimeout(function() {
  2878. fn(arg);
  2879. }, 0);
  2880. } else try {
  2881. this._schedule(function() {
  2882. fn(arg);
  2883. });
  2884. } catch (e) {
  2885. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  2886. }
  2887. };
  2888. function AsyncInvokeLater(fn, receiver, arg) {
  2889. this._lateQueue.push(fn, receiver, arg);
  2890. this._queueTick();
  2891. }
  2892. function AsyncInvoke(fn, receiver, arg) {
  2893. this._normalQueue.push(fn, receiver, arg);
  2894. this._queueTick();
  2895. }
  2896. function AsyncSettlePromises(promise) {
  2897. this._normalQueue._pushOne(promise);
  2898. this._queueTick();
  2899. }
  2900. if (!util.hasDevTools) {
  2901. Async.prototype.invokeLater = AsyncInvokeLater;
  2902. Async.prototype.invoke = AsyncInvoke;
  2903. Async.prototype.settlePromises = AsyncSettlePromises;
  2904. } else {
  2905. Async.prototype.invokeLater = function (fn, receiver, arg) {
  2906. if (this._trampolineEnabled) {
  2907. AsyncInvokeLater.call(this, fn, receiver, arg);
  2908. } else {
  2909. this._schedule(function() {
  2910. setTimeout(function() {
  2911. fn.call(receiver, arg);
  2912. }, 100);
  2913. });
  2914. }
  2915. };
  2916. Async.prototype.invoke = function (fn, receiver, arg) {
  2917. if (this._trampolineEnabled) {
  2918. AsyncInvoke.call(this, fn, receiver, arg);
  2919. } else {
  2920. this._schedule(function() {
  2921. fn.call(receiver, arg);
  2922. });
  2923. }
  2924. };
  2925. Async.prototype.settlePromises = function(promise) {
  2926. if (this._trampolineEnabled) {
  2927. AsyncSettlePromises.call(this, promise);
  2928. } else {
  2929. this._schedule(function() {
  2930. promise._settlePromises();
  2931. });
  2932. }
  2933. };
  2934. }
  2935. Async.prototype.invokeFirst = function (fn, receiver, arg) {
  2936. this._normalQueue.unshift(fn, receiver, arg);
  2937. this._queueTick();
  2938. };
  2939. Async.prototype._drainQueue = function(queue) {
  2940. while (queue.length() > 0) {
  2941. var fn = queue.shift();
  2942. if (typeof fn !== "function") {
  2943. fn._settlePromises();
  2944. continue;
  2945. }
  2946. var receiver = queue.shift();
  2947. var arg = queue.shift();
  2948. fn.call(receiver, arg);
  2949. }
  2950. };
  2951. Async.prototype._drainQueues = function () {
  2952. this._drainQueue(this._normalQueue);
  2953. this._reset();
  2954. this._haveDrainedQueues = true;
  2955. this._drainQueue(this._lateQueue);
  2956. };
  2957. Async.prototype._queueTick = function () {
  2958. if (!this._isTickUsed) {
  2959. this._isTickUsed = true;
  2960. this._schedule(this.drainQueues);
  2961. }
  2962. };
  2963. Async.prototype._reset = function () {
  2964. this._isTickUsed = false;
  2965. };
  2966. module.exports = Async;
  2967. module.exports.firstLineError = firstLineError;
  2968. }).call(this,require('_process'))
  2969. },{"./queue":61,"./schedule":64,"./util":71,"_process":81}],39:[function(require,module,exports){
  2970. "use strict";
  2971. module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
  2972. var calledBind = false;
  2973. var rejectThis = function(_, e) {
  2974. this._reject(e);
  2975. };
  2976. var targetRejected = function(e, context) {
  2977. context.promiseRejectionQueued = true;
  2978. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  2979. };
  2980. var bindingResolved = function(thisArg, context) {
  2981. if (((this._bitField & 50397184) === 0)) {
  2982. this._resolveCallback(context.target);
  2983. }
  2984. };
  2985. var bindingRejected = function(e, context) {
  2986. if (!context.promiseRejectionQueued) this._reject(e);
  2987. };
  2988. Promise.prototype.bind = function (thisArg) {
  2989. if (!calledBind) {
  2990. calledBind = true;
  2991. Promise.prototype._propagateFrom = debug.propagateFromFunction();
  2992. Promise.prototype._boundValue = debug.boundValueFunction();
  2993. }
  2994. var maybePromise = tryConvertToPromise(thisArg);
  2995. var ret = new Promise(INTERNAL);
  2996. ret._propagateFrom(this, 1);
  2997. var target = this._target();
  2998. ret._setBoundTo(maybePromise);
  2999. if (maybePromise instanceof Promise) {
  3000. var context = {
  3001. promiseRejectionQueued: false,
  3002. promise: ret,
  3003. target: target,
  3004. bindingPromise: maybePromise
  3005. };
  3006. target._then(INTERNAL, targetRejected, undefined, ret, context);
  3007. maybePromise._then(
  3008. bindingResolved, bindingRejected, undefined, ret, context);
  3009. ret._setOnCancel(maybePromise);
  3010. } else {
  3011. ret._resolveCallback(target);
  3012. }
  3013. return ret;
  3014. };
  3015. Promise.prototype._setBoundTo = function (obj) {
  3016. if (obj !== undefined) {
  3017. this._bitField = this._bitField | 2097152;
  3018. this._boundTo = obj;
  3019. } else {
  3020. this._bitField = this._bitField & (~2097152);
  3021. }
  3022. };
  3023. Promise.prototype._isBound = function () {
  3024. return (this._bitField & 2097152) === 2097152;
  3025. };
  3026. Promise.bind = function (thisArg, value) {
  3027. return Promise.resolve(value).bind(thisArg);
  3028. };
  3029. };
  3030. },{}],40:[function(require,module,exports){
  3031. "use strict";
  3032. var cr = Object.create;
  3033. if (cr) {
  3034. var callerCache = cr(null);
  3035. var getterCache = cr(null);
  3036. callerCache[" size"] = getterCache[" size"] = 0;
  3037. }
  3038. module.exports = function(Promise) {
  3039. var util = require("./util");
  3040. var canEvaluate = util.canEvaluate;
  3041. var isIdentifier = util.isIdentifier;
  3042. var getMethodCaller;
  3043. var getGetter;
  3044. if (!false) {
  3045. var makeMethodCaller = function (methodName) {
  3046. return new Function("ensureMethod", " \n\
  3047. return function(obj) { \n\
  3048. 'use strict' \n\
  3049. var len = this.length; \n\
  3050. ensureMethod(obj, 'methodName'); \n\
  3051. switch(len) { \n\
  3052. case 1: return obj.methodName(this[0]); \n\
  3053. case 2: return obj.methodName(this[0], this[1]); \n\
  3054. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  3055. case 0: return obj.methodName(); \n\
  3056. default: \n\
  3057. return obj.methodName.apply(obj, this); \n\
  3058. } \n\
  3059. }; \n\
  3060. ".replace(/methodName/g, methodName))(ensureMethod);
  3061. };
  3062. var makeGetter = function (propertyName) {
  3063. return new Function("obj", " \n\
  3064. 'use strict'; \n\
  3065. return obj.propertyName; \n\
  3066. ".replace("propertyName", propertyName));
  3067. };
  3068. var getCompiled = function(name, compiler, cache) {
  3069. var ret = cache[name];
  3070. if (typeof ret !== "function") {
  3071. if (!isIdentifier(name)) {
  3072. return null;
  3073. }
  3074. ret = compiler(name);
  3075. cache[name] = ret;
  3076. cache[" size"]++;
  3077. if (cache[" size"] > 512) {
  3078. var keys = Object.keys(cache);
  3079. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  3080. cache[" size"] = keys.length - 256;
  3081. }
  3082. }
  3083. return ret;
  3084. };
  3085. getMethodCaller = function(name) {
  3086. return getCompiled(name, makeMethodCaller, callerCache);
  3087. };
  3088. getGetter = function(name) {
  3089. return getCompiled(name, makeGetter, getterCache);
  3090. };
  3091. }
  3092. function ensureMethod(obj, methodName) {
  3093. var fn;
  3094. if (obj != null) fn = obj[methodName];
  3095. if (typeof fn !== "function") {
  3096. var message = "Object " + util.classString(obj) + " has no method '" +
  3097. util.toString(methodName) + "'";
  3098. throw new Promise.TypeError(message);
  3099. }
  3100. return fn;
  3101. }
  3102. function caller(obj) {
  3103. var methodName = this.pop();
  3104. var fn = ensureMethod(obj, methodName);
  3105. return fn.apply(obj, this);
  3106. }
  3107. Promise.prototype.call = function (methodName) {
  3108. var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
  3109. if (!false) {
  3110. if (canEvaluate) {
  3111. var maybeCaller = getMethodCaller(methodName);
  3112. if (maybeCaller !== null) {
  3113. return this._then(
  3114. maybeCaller, undefined, undefined, args, undefined);
  3115. }
  3116. }
  3117. }
  3118. args.push(methodName);
  3119. return this._then(caller, undefined, undefined, args, undefined);
  3120. };
  3121. function namedGetter(obj) {
  3122. return obj[this];
  3123. }
  3124. function indexedGetter(obj) {
  3125. var index = +this;
  3126. if (index < 0) index = Math.max(0, index + obj.length);
  3127. return obj[index];
  3128. }
  3129. Promise.prototype.get = function (propertyName) {
  3130. var isIndex = (typeof propertyName === "number");
  3131. var getter;
  3132. if (!isIndex) {
  3133. if (canEvaluate) {
  3134. var maybeGetter = getGetter(propertyName);
  3135. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  3136. } else {
  3137. getter = namedGetter;
  3138. }
  3139. } else {
  3140. getter = indexedGetter;
  3141. }
  3142. return this._then(getter, undefined, undefined, propertyName, undefined);
  3143. };
  3144. };
  3145. },{"./util":71}],41:[function(require,module,exports){
  3146. "use strict";
  3147. module.exports = function(Promise, PromiseArray, apiRejection, debug) {
  3148. var util = require("./util");
  3149. var tryCatch = util.tryCatch;
  3150. var errorObj = util.errorObj;
  3151. var async = Promise._async;
  3152. Promise.prototype["break"] = Promise.prototype.cancel = function() {
  3153. if (!debug.cancellation()) return this._warn("cancellation is disabled");
  3154. var promise = this;
  3155. var child = promise;
  3156. while (promise.isCancellable()) {
  3157. if (!promise._cancelBy(child)) {
  3158. if (child._isFollowing()) {
  3159. child._followee().cancel();
  3160. } else {
  3161. child._cancelBranched();
  3162. }
  3163. break;
  3164. }
  3165. var parent = promise._cancellationParent;
  3166. if (parent == null || !parent.isCancellable()) {
  3167. if (promise._isFollowing()) {
  3168. promise._followee().cancel();
  3169. } else {
  3170. promise._cancelBranched();
  3171. }
  3172. break;
  3173. } else {
  3174. if (promise._isFollowing()) promise._followee().cancel();
  3175. child = promise;
  3176. promise = parent;
  3177. }
  3178. }
  3179. };
  3180. Promise.prototype._branchHasCancelled = function() {
  3181. this._branchesRemainingToCancel--;
  3182. };
  3183. Promise.prototype._enoughBranchesHaveCancelled = function() {
  3184. return this._branchesRemainingToCancel === undefined ||
  3185. this._branchesRemainingToCancel <= 0;
  3186. };
  3187. Promise.prototype._cancelBy = function(canceller) {
  3188. if (canceller === this) {
  3189. this._branchesRemainingToCancel = 0;
  3190. this._invokeOnCancel();
  3191. return true;
  3192. } else {
  3193. this._branchHasCancelled();
  3194. if (this._enoughBranchesHaveCancelled()) {
  3195. this._invokeOnCancel();
  3196. return true;
  3197. }
  3198. }
  3199. return false;
  3200. };
  3201. Promise.prototype._cancelBranched = function() {
  3202. if (this._enoughBranchesHaveCancelled()) {
  3203. this._cancel();
  3204. }
  3205. };
  3206. Promise.prototype._cancel = function() {
  3207. if (!this.isCancellable()) return;
  3208. this._setCancelled();
  3209. async.invoke(this._cancelPromises, this, undefined);
  3210. };
  3211. Promise.prototype._cancelPromises = function() {
  3212. if (this._length() > 0) this._settlePromises();
  3213. };
  3214. Promise.prototype._unsetOnCancel = function() {
  3215. this._onCancelField = undefined;
  3216. };
  3217. Promise.prototype.isCancellable = function() {
  3218. return this.isPending() && !this.isCancelled();
  3219. };
  3220. Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
  3221. if (util.isArray(onCancelCallback)) {
  3222. for (var i = 0; i < onCancelCallback.length; ++i) {
  3223. this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
  3224. }
  3225. } else if (onCancelCallback !== undefined) {
  3226. if (typeof onCancelCallback === "function") {
  3227. if (!internalOnly) {
  3228. var e = tryCatch(onCancelCallback).call(this._boundValue());
  3229. if (e === errorObj) {
  3230. this._attachExtraTrace(e.e);
  3231. async.throwLater(e.e);
  3232. }
  3233. }
  3234. } else {
  3235. onCancelCallback._resultCancelled(this);
  3236. }
  3237. }
  3238. };
  3239. Promise.prototype._invokeOnCancel = function() {
  3240. var onCancelCallback = this._onCancel();
  3241. this._unsetOnCancel();
  3242. async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
  3243. };
  3244. Promise.prototype._invokeInternalOnCancel = function() {
  3245. if (this.isCancellable()) {
  3246. this._doInvokeOnCancel(this._onCancel(), true);
  3247. this._unsetOnCancel();
  3248. }
  3249. };
  3250. Promise.prototype._resultCancelled = function() {
  3251. this.cancel();
  3252. };
  3253. };
  3254. },{"./util":71}],42:[function(require,module,exports){
  3255. "use strict";
  3256. module.exports = function(NEXT_FILTER) {
  3257. var util = require("./util");
  3258. var getKeys = require("./es5").keys;
  3259. var tryCatch = util.tryCatch;
  3260. var errorObj = util.errorObj;
  3261. function catchFilter(instances, cb, promise) {
  3262. return function(e) {
  3263. var boundTo = promise._boundValue();
  3264. predicateLoop: for (var i = 0; i < instances.length; ++i) {
  3265. var item = instances[i];
  3266. if (item === Error ||
  3267. (item != null && item.prototype instanceof Error)) {
  3268. if (e instanceof item) {
  3269. return tryCatch(cb).call(boundTo, e);
  3270. }
  3271. } else if (typeof item === "function") {
  3272. var matchesPredicate = tryCatch(item).call(boundTo, e);
  3273. if (matchesPredicate === errorObj) {
  3274. return matchesPredicate;
  3275. } else if (matchesPredicate) {
  3276. return tryCatch(cb).call(boundTo, e);
  3277. }
  3278. } else if (util.isObject(e)) {
  3279. var keys = getKeys(item);
  3280. for (var j = 0; j < keys.length; ++j) {
  3281. var key = keys[j];
  3282. if (item[key] != e[key]) {
  3283. continue predicateLoop;
  3284. }
  3285. }
  3286. return tryCatch(cb).call(boundTo, e);
  3287. }
  3288. }
  3289. return NEXT_FILTER;
  3290. };
  3291. }
  3292. return catchFilter;
  3293. };
  3294. },{"./es5":48,"./util":71}],43:[function(require,module,exports){
  3295. "use strict";
  3296. module.exports = function(Promise) {
  3297. var longStackTraces = false;
  3298. var contextStack = [];
  3299. Promise.prototype._promiseCreated = function() {};
  3300. Promise.prototype._pushContext = function() {};
  3301. Promise.prototype._popContext = function() {return null;};
  3302. Promise._peekContext = Promise.prototype._peekContext = function() {};
  3303. function Context() {
  3304. this._trace = new Context.CapturedTrace(peekContext());
  3305. }
  3306. Context.prototype._pushContext = function () {
  3307. if (this._trace !== undefined) {
  3308. this._trace._promiseCreated = null;
  3309. contextStack.push(this._trace);
  3310. }
  3311. };
  3312. Context.prototype._popContext = function () {
  3313. if (this._trace !== undefined) {
  3314. var trace = contextStack.pop();
  3315. var ret = trace._promiseCreated;
  3316. trace._promiseCreated = null;
  3317. return ret;
  3318. }
  3319. return null;
  3320. };
  3321. function createContext() {
  3322. if (longStackTraces) return new Context();
  3323. }
  3324. function peekContext() {
  3325. var lastIndex = contextStack.length - 1;
  3326. if (lastIndex >= 0) {
  3327. return contextStack[lastIndex];
  3328. }
  3329. return undefined;
  3330. }
  3331. Context.CapturedTrace = null;
  3332. Context.create = createContext;
  3333. Context.deactivateLongStackTraces = function() {};
  3334. Context.activateLongStackTraces = function() {
  3335. var Promise_pushContext = Promise.prototype._pushContext;
  3336. var Promise_popContext = Promise.prototype._popContext;
  3337. var Promise_PeekContext = Promise._peekContext;
  3338. var Promise_peekContext = Promise.prototype._peekContext;
  3339. var Promise_promiseCreated = Promise.prototype._promiseCreated;
  3340. Context.deactivateLongStackTraces = function() {
  3341. Promise.prototype._pushContext = Promise_pushContext;
  3342. Promise.prototype._popContext = Promise_popContext;
  3343. Promise._peekContext = Promise_PeekContext;
  3344. Promise.prototype._peekContext = Promise_peekContext;
  3345. Promise.prototype._promiseCreated = Promise_promiseCreated;
  3346. longStackTraces = false;
  3347. };
  3348. longStackTraces = true;
  3349. Promise.prototype._pushContext = Context.prototype._pushContext;
  3350. Promise.prototype._popContext = Context.prototype._popContext;
  3351. Promise._peekContext = Promise.prototype._peekContext = peekContext;
  3352. Promise.prototype._promiseCreated = function() {
  3353. var ctx = this._peekContext();
  3354. if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
  3355. };
  3356. };
  3357. return Context;
  3358. };
  3359. },{}],44:[function(require,module,exports){
  3360. (function (process){
  3361. "use strict";
  3362. module.exports = function(Promise, Context) {
  3363. var getDomain = Promise._getDomain;
  3364. var async = Promise._async;
  3365. var Warning = require("./errors").Warning;
  3366. var util = require("./util");
  3367. var canAttachTrace = util.canAttachTrace;
  3368. var unhandledRejectionHandled;
  3369. var possiblyUnhandledRejection;
  3370. var bluebirdFramePattern =
  3371. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  3372. var stackFramePattern = null;
  3373. var formatStack = null;
  3374. var indentStackFrames = false;
  3375. var printWarning;
  3376. var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
  3377. (false ||
  3378. util.env("BLUEBIRD_DEBUG") ||
  3379. util.env("NODE_ENV") === "development"));
  3380. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  3381. (debugging || util.env("BLUEBIRD_WARNINGS")));
  3382. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  3383. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  3384. var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
  3385. (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
  3386. Promise.prototype.suppressUnhandledRejections = function() {
  3387. var target = this._target();
  3388. target._bitField = ((target._bitField & (~1048576)) |
  3389. 524288);
  3390. };
  3391. Promise.prototype._ensurePossibleRejectionHandled = function () {
  3392. if ((this._bitField & 524288) !== 0) return;
  3393. this._setRejectionIsUnhandled();
  3394. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  3395. };
  3396. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  3397. fireRejectionEvent("rejectionHandled",
  3398. unhandledRejectionHandled, undefined, this);
  3399. };
  3400. Promise.prototype._setReturnedNonUndefined = function() {
  3401. this._bitField = this._bitField | 268435456;
  3402. };
  3403. Promise.prototype._returnedNonUndefined = function() {
  3404. return (this._bitField & 268435456) !== 0;
  3405. };
  3406. Promise.prototype._notifyUnhandledRejection = function () {
  3407. if (this._isRejectionUnhandled()) {
  3408. var reason = this._settledValue();
  3409. this._setUnhandledRejectionIsNotified();
  3410. fireRejectionEvent("unhandledRejection",
  3411. possiblyUnhandledRejection, reason, this);
  3412. }
  3413. };
  3414. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  3415. this._bitField = this._bitField | 262144;
  3416. };
  3417. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  3418. this._bitField = this._bitField & (~262144);
  3419. };
  3420. Promise.prototype._isUnhandledRejectionNotified = function () {
  3421. return (this._bitField & 262144) > 0;
  3422. };
  3423. Promise.prototype._setRejectionIsUnhandled = function () {
  3424. this._bitField = this._bitField | 1048576;
  3425. };
  3426. Promise.prototype._unsetRejectionIsUnhandled = function () {
  3427. this._bitField = this._bitField & (~1048576);
  3428. if (this._isUnhandledRejectionNotified()) {
  3429. this._unsetUnhandledRejectionIsNotified();
  3430. this._notifyUnhandledRejectionIsHandled();
  3431. }
  3432. };
  3433. Promise.prototype._isRejectionUnhandled = function () {
  3434. return (this._bitField & 1048576) > 0;
  3435. };
  3436. Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
  3437. return warn(message, shouldUseOwnTrace, promise || this);
  3438. };
  3439. Promise.onPossiblyUnhandledRejection = function (fn) {
  3440. var domain = getDomain();
  3441. possiblyUnhandledRejection =
  3442. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  3443. : undefined;
  3444. };
  3445. Promise.onUnhandledRejectionHandled = function (fn) {
  3446. var domain = getDomain();
  3447. unhandledRejectionHandled =
  3448. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  3449. : undefined;
  3450. };
  3451. var disableLongStackTraces = function() {};
  3452. Promise.longStackTraces = function () {
  3453. if (async.haveItemsQueued() && !config.longStackTraces) {
  3454. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3455. }
  3456. if (!config.longStackTraces && longStackTracesIsSupported()) {
  3457. var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
  3458. var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
  3459. config.longStackTraces = true;
  3460. disableLongStackTraces = function() {
  3461. if (async.haveItemsQueued() && !config.longStackTraces) {
  3462. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3463. }
  3464. Promise.prototype._captureStackTrace = Promise_captureStackTrace;
  3465. Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
  3466. Context.deactivateLongStackTraces();
  3467. async.enableTrampoline();
  3468. config.longStackTraces = false;
  3469. };
  3470. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  3471. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  3472. Context.activateLongStackTraces();
  3473. async.disableTrampolineIfNecessary();
  3474. }
  3475. };
  3476. Promise.hasLongStackTraces = function () {
  3477. return config.longStackTraces && longStackTracesIsSupported();
  3478. };
  3479. var fireDomEvent = (function() {
  3480. try {
  3481. var event = document.createEvent("CustomEvent");
  3482. event.initCustomEvent("testingtheevent", false, true, {});
  3483. util.global.dispatchEvent(event);
  3484. return function(name, event) {
  3485. var domEvent = document.createEvent("CustomEvent");
  3486. domEvent.initCustomEvent(name.toLowerCase(), false, true, event);
  3487. return !util.global.dispatchEvent(domEvent);
  3488. };
  3489. } catch (e) {}
  3490. return function() {
  3491. return false;
  3492. };
  3493. })();
  3494. var fireGlobalEvent = (function() {
  3495. if (util.isNode) {
  3496. return function() {
  3497. return process.emit.apply(process, arguments);
  3498. };
  3499. } else {
  3500. if (!util.global) {
  3501. return function() {
  3502. return false;
  3503. };
  3504. }
  3505. return function(name) {
  3506. var methodName = "on" + name.toLowerCase();
  3507. var method = util.global[methodName];
  3508. if (!method) return false;
  3509. method.apply(util.global, [].slice.call(arguments, 1));
  3510. return true;
  3511. };
  3512. }
  3513. })();
  3514. function generatePromiseLifecycleEventObject(name, promise) {
  3515. return {promise: promise};
  3516. }
  3517. var eventToObjectGenerator = {
  3518. promiseCreated: generatePromiseLifecycleEventObject,
  3519. promiseFulfilled: generatePromiseLifecycleEventObject,
  3520. promiseRejected: generatePromiseLifecycleEventObject,
  3521. promiseResolved: generatePromiseLifecycleEventObject,
  3522. promiseCancelled: generatePromiseLifecycleEventObject,
  3523. promiseChained: function(name, promise, child) {
  3524. return {promise: promise, child: child};
  3525. },
  3526. warning: function(name, warning) {
  3527. return {warning: warning};
  3528. },
  3529. unhandledRejection: function (name, reason, promise) {
  3530. return {reason: reason, promise: promise};
  3531. },
  3532. rejectionHandled: generatePromiseLifecycleEventObject
  3533. };
  3534. var activeFireEvent = function (name) {
  3535. var globalEventFired = false;
  3536. try {
  3537. globalEventFired = fireGlobalEvent.apply(null, arguments);
  3538. } catch (e) {
  3539. async.throwLater(e);
  3540. globalEventFired = true;
  3541. }
  3542. var domEventFired = false;
  3543. try {
  3544. domEventFired = fireDomEvent(name,
  3545. eventToObjectGenerator[name].apply(null, arguments));
  3546. } catch (e) {
  3547. async.throwLater(e);
  3548. domEventFired = true;
  3549. }
  3550. return domEventFired || globalEventFired;
  3551. };
  3552. Promise.config = function(opts) {
  3553. opts = Object(opts);
  3554. if ("longStackTraces" in opts) {
  3555. if (opts.longStackTraces) {
  3556. Promise.longStackTraces();
  3557. } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
  3558. disableLongStackTraces();
  3559. }
  3560. }
  3561. if ("warnings" in opts) {
  3562. var warningsOption = opts.warnings;
  3563. config.warnings = !!warningsOption;
  3564. wForgottenReturn = config.warnings;
  3565. if (util.isObject(warningsOption)) {
  3566. if ("wForgottenReturn" in warningsOption) {
  3567. wForgottenReturn = !!warningsOption.wForgottenReturn;
  3568. }
  3569. }
  3570. }
  3571. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  3572. if (async.haveItemsQueued()) {
  3573. throw new Error(
  3574. "cannot enable cancellation after promises are in use");
  3575. }
  3576. Promise.prototype._clearCancellationData =
  3577. cancellationClearCancellationData;
  3578. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  3579. Promise.prototype._onCancel = cancellationOnCancel;
  3580. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  3581. Promise.prototype._attachCancellationCallback =
  3582. cancellationAttachCancellationCallback;
  3583. Promise.prototype._execute = cancellationExecute;
  3584. propagateFromFunction = cancellationPropagateFrom;
  3585. config.cancellation = true;
  3586. }
  3587. if ("monitoring" in opts) {
  3588. if (opts.monitoring && !config.monitoring) {
  3589. config.monitoring = true;
  3590. Promise.prototype._fireEvent = activeFireEvent;
  3591. } else if (!opts.monitoring && config.monitoring) {
  3592. config.monitoring = false;
  3593. Promise.prototype._fireEvent = defaultFireEvent;
  3594. }
  3595. }
  3596. };
  3597. function defaultFireEvent() { return false; }
  3598. Promise.prototype._fireEvent = defaultFireEvent;
  3599. Promise.prototype._execute = function(executor, resolve, reject) {
  3600. try {
  3601. executor(resolve, reject);
  3602. } catch (e) {
  3603. return e;
  3604. }
  3605. };
  3606. Promise.prototype._onCancel = function () {};
  3607. Promise.prototype._setOnCancel = function (handler) { ; };
  3608. Promise.prototype._attachCancellationCallback = function(onCancel) {
  3609. ;
  3610. };
  3611. Promise.prototype._captureStackTrace = function () {};
  3612. Promise.prototype._attachExtraTrace = function () {};
  3613. Promise.prototype._clearCancellationData = function() {};
  3614. Promise.prototype._propagateFrom = function (parent, flags) {
  3615. ;
  3616. ;
  3617. };
  3618. function cancellationExecute(executor, resolve, reject) {
  3619. var promise = this;
  3620. try {
  3621. executor(resolve, reject, function(onCancel) {
  3622. if (typeof onCancel !== "function") {
  3623. throw new TypeError("onCancel must be a function, got: " +
  3624. util.toString(onCancel));
  3625. }
  3626. promise._attachCancellationCallback(onCancel);
  3627. });
  3628. } catch (e) {
  3629. return e;
  3630. }
  3631. }
  3632. function cancellationAttachCancellationCallback(onCancel) {
  3633. if (!this.isCancellable()) return this;
  3634. var previousOnCancel = this._onCancel();
  3635. if (previousOnCancel !== undefined) {
  3636. if (util.isArray(previousOnCancel)) {
  3637. previousOnCancel.push(onCancel);
  3638. } else {
  3639. this._setOnCancel([previousOnCancel, onCancel]);
  3640. }
  3641. } else {
  3642. this._setOnCancel(onCancel);
  3643. }
  3644. }
  3645. function cancellationOnCancel() {
  3646. return this._onCancelField;
  3647. }
  3648. function cancellationSetOnCancel(onCancel) {
  3649. this._onCancelField = onCancel;
  3650. }
  3651. function cancellationClearCancellationData() {
  3652. this._cancellationParent = undefined;
  3653. this._onCancelField = undefined;
  3654. }
  3655. function cancellationPropagateFrom(parent, flags) {
  3656. if ((flags & 1) !== 0) {
  3657. this._cancellationParent = parent;
  3658. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  3659. if (branchesRemainingToCancel === undefined) {
  3660. branchesRemainingToCancel = 0;
  3661. }
  3662. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  3663. }
  3664. if ((flags & 2) !== 0 && parent._isBound()) {
  3665. this._setBoundTo(parent._boundTo);
  3666. }
  3667. }
  3668. function bindingPropagateFrom(parent, flags) {
  3669. if ((flags & 2) !== 0 && parent._isBound()) {
  3670. this._setBoundTo(parent._boundTo);
  3671. }
  3672. }
  3673. var propagateFromFunction = bindingPropagateFrom;
  3674. function boundValueFunction() {
  3675. var ret = this._boundTo;
  3676. if (ret !== undefined) {
  3677. if (ret instanceof Promise) {
  3678. if (ret.isFulfilled()) {
  3679. return ret.value();
  3680. } else {
  3681. return undefined;
  3682. }
  3683. }
  3684. }
  3685. return ret;
  3686. }
  3687. function longStackTracesCaptureStackTrace() {
  3688. this._trace = new CapturedTrace(this._peekContext());
  3689. }
  3690. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  3691. if (canAttachTrace(error)) {
  3692. var trace = this._trace;
  3693. if (trace !== undefined) {
  3694. if (ignoreSelf) trace = trace._parent;
  3695. }
  3696. if (trace !== undefined) {
  3697. trace.attachExtraTrace(error);
  3698. } else if (!error.__stackCleaned__) {
  3699. var parsed = parseStackAndMessage(error);
  3700. util.notEnumerableProp(error, "stack",
  3701. parsed.message + "\n" + parsed.stack.join("\n"));
  3702. util.notEnumerableProp(error, "__stackCleaned__", true);
  3703. }
  3704. }
  3705. }
  3706. function checkForgottenReturns(returnValue, promiseCreated, name, promise,
  3707. parent) {
  3708. if (returnValue === undefined && promiseCreated !== null &&
  3709. wForgottenReturn) {
  3710. if (parent !== undefined && parent._returnedNonUndefined()) return;
  3711. if ((promise._bitField & 65535) === 0) return;
  3712. if (name) name = name + " ";
  3713. var msg = "a promise was created in a " + name +
  3714. "handler but was not returned from it";
  3715. promise._warn(msg, true, promiseCreated);
  3716. }
  3717. }
  3718. function deprecated(name, replacement) {
  3719. var message = name +
  3720. " is deprecated and will be removed in a future version.";
  3721. if (replacement) message += " Use " + replacement + " instead.";
  3722. return warn(message);
  3723. }
  3724. function warn(message, shouldUseOwnTrace, promise) {
  3725. if (!config.warnings) return;
  3726. var warning = new Warning(message);
  3727. var ctx;
  3728. if (shouldUseOwnTrace) {
  3729. promise._attachExtraTrace(warning);
  3730. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  3731. ctx.attachExtraTrace(warning);
  3732. } else {
  3733. var parsed = parseStackAndMessage(warning);
  3734. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  3735. }
  3736. if (!activeFireEvent("warning", warning)) {
  3737. formatAndLogError(warning, "", true);
  3738. }
  3739. }
  3740. function reconstructStack(message, stacks) {
  3741. for (var i = 0; i < stacks.length - 1; ++i) {
  3742. stacks[i].push("From previous event:");
  3743. stacks[i] = stacks[i].join("\n");
  3744. }
  3745. if (i < stacks.length) {
  3746. stacks[i] = stacks[i].join("\n");
  3747. }
  3748. return message + "\n" + stacks.join("\n");
  3749. }
  3750. function removeDuplicateOrEmptyJumps(stacks) {
  3751. for (var i = 0; i < stacks.length; ++i) {
  3752. if (stacks[i].length === 0 ||
  3753. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  3754. stacks.splice(i, 1);
  3755. i--;
  3756. }
  3757. }
  3758. }
  3759. function removeCommonRoots(stacks) {
  3760. var current = stacks[0];
  3761. for (var i = 1; i < stacks.length; ++i) {
  3762. var prev = stacks[i];
  3763. var currentLastIndex = current.length - 1;
  3764. var currentLastLine = current[currentLastIndex];
  3765. var commonRootMeetPoint = -1;
  3766. for (var j = prev.length - 1; j >= 0; --j) {
  3767. if (prev[j] === currentLastLine) {
  3768. commonRootMeetPoint = j;
  3769. break;
  3770. }
  3771. }
  3772. for (var j = commonRootMeetPoint; j >= 0; --j) {
  3773. var line = prev[j];
  3774. if (current[currentLastIndex] === line) {
  3775. current.pop();
  3776. currentLastIndex--;
  3777. } else {
  3778. break;
  3779. }
  3780. }
  3781. current = prev;
  3782. }
  3783. }
  3784. function cleanStack(stack) {
  3785. var ret = [];
  3786. for (var i = 0; i < stack.length; ++i) {
  3787. var line = stack[i];
  3788. var isTraceLine = " (No stack trace)" === line ||
  3789. stackFramePattern.test(line);
  3790. var isInternalFrame = isTraceLine && shouldIgnore(line);
  3791. if (isTraceLine && !isInternalFrame) {
  3792. if (indentStackFrames && line.charAt(0) !== " ") {
  3793. line = " " + line;
  3794. }
  3795. ret.push(line);
  3796. }
  3797. }
  3798. return ret;
  3799. }
  3800. function stackFramesAsArray(error) {
  3801. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  3802. for (var i = 0; i < stack.length; ++i) {
  3803. var line = stack[i];
  3804. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  3805. break;
  3806. }
  3807. }
  3808. if (i > 0) {
  3809. stack = stack.slice(i);
  3810. }
  3811. return stack;
  3812. }
  3813. function parseStackAndMessage(error) {
  3814. var stack = error.stack;
  3815. var message = error.toString();
  3816. stack = typeof stack === "string" && stack.length > 0
  3817. ? stackFramesAsArray(error) : [" (No stack trace)"];
  3818. return {
  3819. message: message,
  3820. stack: cleanStack(stack)
  3821. };
  3822. }
  3823. function formatAndLogError(error, title, isSoft) {
  3824. if (typeof console !== "undefined") {
  3825. var message;
  3826. if (util.isObject(error)) {
  3827. var stack = error.stack;
  3828. message = title + formatStack(stack, error);
  3829. } else {
  3830. message = title + String(error);
  3831. }
  3832. if (typeof printWarning === "function") {
  3833. printWarning(message, isSoft);
  3834. } else if (typeof console.log === "function" ||
  3835. typeof console.log === "object") {
  3836. console.log(message);
  3837. }
  3838. }
  3839. }
  3840. function fireRejectionEvent(name, localHandler, reason, promise) {
  3841. var localEventFired = false;
  3842. try {
  3843. if (typeof localHandler === "function") {
  3844. localEventFired = true;
  3845. if (name === "rejectionHandled") {
  3846. localHandler(promise);
  3847. } else {
  3848. localHandler(reason, promise);
  3849. }
  3850. }
  3851. } catch (e) {
  3852. async.throwLater(e);
  3853. }
  3854. if (name === "unhandledRejection") {
  3855. if (!activeFireEvent(name, reason, promise) && !localEventFired) {
  3856. formatAndLogError(reason, "Unhandled rejection ");
  3857. }
  3858. } else {
  3859. activeFireEvent(name, promise);
  3860. }
  3861. }
  3862. function formatNonError(obj) {
  3863. var str;
  3864. if (typeof obj === "function") {
  3865. str = "[function " +
  3866. (obj.name || "anonymous") +
  3867. "]";
  3868. } else {
  3869. str = obj && typeof obj.toString === "function"
  3870. ? obj.toString() : util.toString(obj);
  3871. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  3872. if (ruselessToString.test(str)) {
  3873. try {
  3874. var newStr = JSON.stringify(obj);
  3875. str = newStr;
  3876. }
  3877. catch(e) {
  3878. }
  3879. }
  3880. if (str.length === 0) {
  3881. str = "(empty array)";
  3882. }
  3883. }
  3884. return ("(<" + snip(str) + ">, no stack trace)");
  3885. }
  3886. function snip(str) {
  3887. var maxChars = 41;
  3888. if (str.length < maxChars) {
  3889. return str;
  3890. }
  3891. return str.substr(0, maxChars - 3) + "...";
  3892. }
  3893. function longStackTracesIsSupported() {
  3894. return typeof captureStackTrace === "function";
  3895. }
  3896. var shouldIgnore = function() { return false; };
  3897. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  3898. function parseLineInfo(line) {
  3899. var matches = line.match(parseLineInfoRegex);
  3900. if (matches) {
  3901. return {
  3902. fileName: matches[1],
  3903. line: parseInt(matches[2], 10)
  3904. };
  3905. }
  3906. }
  3907. function setBounds(firstLineError, lastLineError) {
  3908. if (!longStackTracesIsSupported()) return;
  3909. var firstStackLines = firstLineError.stack.split("\n");
  3910. var lastStackLines = lastLineError.stack.split("\n");
  3911. var firstIndex = -1;
  3912. var lastIndex = -1;
  3913. var firstFileName;
  3914. var lastFileName;
  3915. for (var i = 0; i < firstStackLines.length; ++i) {
  3916. var result = parseLineInfo(firstStackLines[i]);
  3917. if (result) {
  3918. firstFileName = result.fileName;
  3919. firstIndex = result.line;
  3920. break;
  3921. }
  3922. }
  3923. for (var i = 0; i < lastStackLines.length; ++i) {
  3924. var result = parseLineInfo(lastStackLines[i]);
  3925. if (result) {
  3926. lastFileName = result.fileName;
  3927. lastIndex = result.line;
  3928. break;
  3929. }
  3930. }
  3931. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  3932. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  3933. return;
  3934. }
  3935. shouldIgnore = function(line) {
  3936. if (bluebirdFramePattern.test(line)) return true;
  3937. var info = parseLineInfo(line);
  3938. if (info) {
  3939. if (info.fileName === firstFileName &&
  3940. (firstIndex <= info.line && info.line <= lastIndex)) {
  3941. return true;
  3942. }
  3943. }
  3944. return false;
  3945. };
  3946. }
  3947. function CapturedTrace(parent) {
  3948. this._parent = parent;
  3949. this._promisesCreated = 0;
  3950. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  3951. captureStackTrace(this, CapturedTrace);
  3952. if (length > 32) this.uncycle();
  3953. }
  3954. util.inherits(CapturedTrace, Error);
  3955. Context.CapturedTrace = CapturedTrace;
  3956. CapturedTrace.prototype.uncycle = function() {
  3957. var length = this._length;
  3958. if (length < 2) return;
  3959. var nodes = [];
  3960. var stackToIndex = {};
  3961. for (var i = 0, node = this; node !== undefined; ++i) {
  3962. nodes.push(node);
  3963. node = node._parent;
  3964. }
  3965. length = this._length = i;
  3966. for (var i = length - 1; i >= 0; --i) {
  3967. var stack = nodes[i].stack;
  3968. if (stackToIndex[stack] === undefined) {
  3969. stackToIndex[stack] = i;
  3970. }
  3971. }
  3972. for (var i = 0; i < length; ++i) {
  3973. var currentStack = nodes[i].stack;
  3974. var index = stackToIndex[currentStack];
  3975. if (index !== undefined && index !== i) {
  3976. if (index > 0) {
  3977. nodes[index - 1]._parent = undefined;
  3978. nodes[index - 1]._length = 1;
  3979. }
  3980. nodes[i]._parent = undefined;
  3981. nodes[i]._length = 1;
  3982. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  3983. if (index < length - 1) {
  3984. cycleEdgeNode._parent = nodes[index + 1];
  3985. cycleEdgeNode._parent.uncycle();
  3986. cycleEdgeNode._length =
  3987. cycleEdgeNode._parent._length + 1;
  3988. } else {
  3989. cycleEdgeNode._parent = undefined;
  3990. cycleEdgeNode._length = 1;
  3991. }
  3992. var currentChildLength = cycleEdgeNode._length + 1;
  3993. for (var j = i - 2; j >= 0; --j) {
  3994. nodes[j]._length = currentChildLength;
  3995. currentChildLength++;
  3996. }
  3997. return;
  3998. }
  3999. }
  4000. };
  4001. CapturedTrace.prototype.attachExtraTrace = function(error) {
  4002. if (error.__stackCleaned__) return;
  4003. this.uncycle();
  4004. var parsed = parseStackAndMessage(error);
  4005. var message = parsed.message;
  4006. var stacks = [parsed.stack];
  4007. var trace = this;
  4008. while (trace !== undefined) {
  4009. stacks.push(cleanStack(trace.stack.split("\n")));
  4010. trace = trace._parent;
  4011. }
  4012. removeCommonRoots(stacks);
  4013. removeDuplicateOrEmptyJumps(stacks);
  4014. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  4015. util.notEnumerableProp(error, "__stackCleaned__", true);
  4016. };
  4017. var captureStackTrace = (function stackDetection() {
  4018. var v8stackFramePattern = /^\s*at\s*/;
  4019. var v8stackFormatter = function(stack, error) {
  4020. if (typeof stack === "string") return stack;
  4021. if (error.name !== undefined &&
  4022. error.message !== undefined) {
  4023. return error.toString();
  4024. }
  4025. return formatNonError(error);
  4026. };
  4027. if (typeof Error.stackTraceLimit === "number" &&
  4028. typeof Error.captureStackTrace === "function") {
  4029. Error.stackTraceLimit += 6;
  4030. stackFramePattern = v8stackFramePattern;
  4031. formatStack = v8stackFormatter;
  4032. var captureStackTrace = Error.captureStackTrace;
  4033. shouldIgnore = function(line) {
  4034. return bluebirdFramePattern.test(line);
  4035. };
  4036. return function(receiver, ignoreUntil) {
  4037. Error.stackTraceLimit += 6;
  4038. captureStackTrace(receiver, ignoreUntil);
  4039. Error.stackTraceLimit -= 6;
  4040. };
  4041. }
  4042. var err = new Error();
  4043. if (typeof err.stack === "string" &&
  4044. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  4045. stackFramePattern = /@/;
  4046. formatStack = v8stackFormatter;
  4047. indentStackFrames = true;
  4048. return function captureStackTrace(o) {
  4049. o.stack = new Error().stack;
  4050. };
  4051. }
  4052. var hasStackAfterThrow;
  4053. try { throw new Error(); }
  4054. catch(e) {
  4055. hasStackAfterThrow = ("stack" in e);
  4056. }
  4057. if (!("stack" in err) && hasStackAfterThrow &&
  4058. typeof Error.stackTraceLimit === "number") {
  4059. stackFramePattern = v8stackFramePattern;
  4060. formatStack = v8stackFormatter;
  4061. return function captureStackTrace(o) {
  4062. Error.stackTraceLimit += 6;
  4063. try { throw new Error(); }
  4064. catch(e) { o.stack = e.stack; }
  4065. Error.stackTraceLimit -= 6;
  4066. };
  4067. }
  4068. formatStack = function(stack, error) {
  4069. if (typeof stack === "string") return stack;
  4070. if ((typeof error === "object" ||
  4071. typeof error === "function") &&
  4072. error.name !== undefined &&
  4073. error.message !== undefined) {
  4074. return error.toString();
  4075. }
  4076. return formatNonError(error);
  4077. };
  4078. return null;
  4079. })([]);
  4080. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  4081. printWarning = function (message) {
  4082. console.warn(message);
  4083. };
  4084. if (util.isNode && process.stderr.isTTY) {
  4085. printWarning = function(message, isSoft) {
  4086. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  4087. console.warn(color + message + "\u001b[0m\n");
  4088. };
  4089. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  4090. printWarning = function(message, isSoft) {
  4091. console.warn("%c" + message,
  4092. isSoft ? "color: darkorange" : "color: red");
  4093. };
  4094. }
  4095. }
  4096. var config = {
  4097. warnings: warnings,
  4098. longStackTraces: false,
  4099. cancellation: false,
  4100. monitoring: false
  4101. };
  4102. if (longStackTraces) Promise.longStackTraces();
  4103. return {
  4104. longStackTraces: function() {
  4105. return config.longStackTraces;
  4106. },
  4107. warnings: function() {
  4108. return config.warnings;
  4109. },
  4110. cancellation: function() {
  4111. return config.cancellation;
  4112. },
  4113. monitoring: function() {
  4114. return config.monitoring;
  4115. },
  4116. propagateFromFunction: function() {
  4117. return propagateFromFunction;
  4118. },
  4119. boundValueFunction: function() {
  4120. return boundValueFunction;
  4121. },
  4122. checkForgottenReturns: checkForgottenReturns,
  4123. setBounds: setBounds,
  4124. warn: warn,
  4125. deprecated: deprecated,
  4126. CapturedTrace: CapturedTrace,
  4127. fireDomEvent: fireDomEvent,
  4128. fireGlobalEvent: fireGlobalEvent
  4129. };
  4130. };
  4131. }).call(this,require('_process'))
  4132. },{"./errors":47,"./util":71,"_process":81}],45:[function(require,module,exports){
  4133. "use strict";
  4134. module.exports = function(Promise) {
  4135. function returner() {
  4136. return this.value;
  4137. }
  4138. function thrower() {
  4139. throw this.reason;
  4140. }
  4141. Promise.prototype["return"] =
  4142. Promise.prototype.thenReturn = function (value) {
  4143. if (value instanceof Promise) value.suppressUnhandledRejections();
  4144. return this._then(
  4145. returner, undefined, undefined, {value: value}, undefined);
  4146. };
  4147. Promise.prototype["throw"] =
  4148. Promise.prototype.thenThrow = function (reason) {
  4149. return this._then(
  4150. thrower, undefined, undefined, {reason: reason}, undefined);
  4151. };
  4152. Promise.prototype.catchThrow = function (reason) {
  4153. if (arguments.length <= 1) {
  4154. return this._then(
  4155. undefined, thrower, undefined, {reason: reason}, undefined);
  4156. } else {
  4157. var _reason = arguments[1];
  4158. var handler = function() {throw _reason;};
  4159. return this.caught(reason, handler);
  4160. }
  4161. };
  4162. Promise.prototype.catchReturn = function (value) {
  4163. if (arguments.length <= 1) {
  4164. if (value instanceof Promise) value.suppressUnhandledRejections();
  4165. return this._then(
  4166. undefined, returner, undefined, {value: value}, undefined);
  4167. } else {
  4168. var _value = arguments[1];
  4169. if (_value instanceof Promise) _value.suppressUnhandledRejections();
  4170. var handler = function() {return _value;};
  4171. return this.caught(value, handler);
  4172. }
  4173. };
  4174. };
  4175. },{}],46:[function(require,module,exports){
  4176. "use strict";
  4177. module.exports = function(Promise, INTERNAL) {
  4178. var PromiseReduce = Promise.reduce;
  4179. var PromiseAll = Promise.all;
  4180. function promiseAllThis() {
  4181. return PromiseAll(this);
  4182. }
  4183. function PromiseMapSeries(promises, fn) {
  4184. return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
  4185. }
  4186. Promise.prototype.each = function (fn) {
  4187. return this.mapSeries(fn)
  4188. ._then(promiseAllThis, undefined, undefined, this, undefined);
  4189. };
  4190. Promise.prototype.mapSeries = function (fn) {
  4191. return PromiseReduce(this, fn, INTERNAL, INTERNAL);
  4192. };
  4193. Promise.each = function (promises, fn) {
  4194. return PromiseMapSeries(promises, fn)
  4195. ._then(promiseAllThis, undefined, undefined, promises, undefined);
  4196. };
  4197. Promise.mapSeries = PromiseMapSeries;
  4198. };
  4199. },{}],47:[function(require,module,exports){
  4200. "use strict";
  4201. var es5 = require("./es5");
  4202. var Objectfreeze = es5.freeze;
  4203. var util = require("./util");
  4204. var inherits = util.inherits;
  4205. var notEnumerableProp = util.notEnumerableProp;
  4206. function subError(nameProperty, defaultMessage) {
  4207. function SubError(message) {
  4208. if (!(this instanceof SubError)) return new SubError(message);
  4209. notEnumerableProp(this, "message",
  4210. typeof message === "string" ? message : defaultMessage);
  4211. notEnumerableProp(this, "name", nameProperty);
  4212. if (Error.captureStackTrace) {
  4213. Error.captureStackTrace(this, this.constructor);
  4214. } else {
  4215. Error.call(this);
  4216. }
  4217. }
  4218. inherits(SubError, Error);
  4219. return SubError;
  4220. }
  4221. var _TypeError, _RangeError;
  4222. var Warning = subError("Warning", "warning");
  4223. var CancellationError = subError("CancellationError", "cancellation error");
  4224. var TimeoutError = subError("TimeoutError", "timeout error");
  4225. var AggregateError = subError("AggregateError", "aggregate error");
  4226. try {
  4227. _TypeError = TypeError;
  4228. _RangeError = RangeError;
  4229. } catch(e) {
  4230. _TypeError = subError("TypeError", "type error");
  4231. _RangeError = subError("RangeError", "range error");
  4232. }
  4233. var methods = ("join pop push shift unshift slice filter forEach some " +
  4234. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  4235. for (var i = 0; i < methods.length; ++i) {
  4236. if (typeof Array.prototype[methods[i]] === "function") {
  4237. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  4238. }
  4239. }
  4240. es5.defineProperty(AggregateError.prototype, "length", {
  4241. value: 0,
  4242. configurable: false,
  4243. writable: true,
  4244. enumerable: true
  4245. });
  4246. AggregateError.prototype["isOperational"] = true;
  4247. var level = 0;
  4248. AggregateError.prototype.toString = function() {
  4249. var indent = Array(level * 4 + 1).join(" ");
  4250. var ret = "\n" + indent + "AggregateError of:" + "\n";
  4251. level++;
  4252. indent = Array(level * 4 + 1).join(" ");
  4253. for (var i = 0; i < this.length; ++i) {
  4254. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  4255. var lines = str.split("\n");
  4256. for (var j = 0; j < lines.length; ++j) {
  4257. lines[j] = indent + lines[j];
  4258. }
  4259. str = lines.join("\n");
  4260. ret += str + "\n";
  4261. }
  4262. level--;
  4263. return ret;
  4264. };
  4265. function OperationalError(message) {
  4266. if (!(this instanceof OperationalError))
  4267. return new OperationalError(message);
  4268. notEnumerableProp(this, "name", "OperationalError");
  4269. notEnumerableProp(this, "message", message);
  4270. this.cause = message;
  4271. this["isOperational"] = true;
  4272. if (message instanceof Error) {
  4273. notEnumerableProp(this, "message", message.message);
  4274. notEnumerableProp(this, "stack", message.stack);
  4275. } else if (Error.captureStackTrace) {
  4276. Error.captureStackTrace(this, this.constructor);
  4277. }
  4278. }
  4279. inherits(OperationalError, Error);
  4280. var errorTypes = Error["__BluebirdErrorTypes__"];
  4281. if (!errorTypes) {
  4282. errorTypes = Objectfreeze({
  4283. CancellationError: CancellationError,
  4284. TimeoutError: TimeoutError,
  4285. OperationalError: OperationalError,
  4286. RejectionError: OperationalError,
  4287. AggregateError: AggregateError
  4288. });
  4289. es5.defineProperty(Error, "__BluebirdErrorTypes__", {
  4290. value: errorTypes,
  4291. writable: false,
  4292. enumerable: false,
  4293. configurable: false
  4294. });
  4295. }
  4296. module.exports = {
  4297. Error: Error,
  4298. TypeError: _TypeError,
  4299. RangeError: _RangeError,
  4300. CancellationError: errorTypes.CancellationError,
  4301. OperationalError: errorTypes.OperationalError,
  4302. TimeoutError: errorTypes.TimeoutError,
  4303. AggregateError: errorTypes.AggregateError,
  4304. Warning: Warning
  4305. };
  4306. },{"./es5":48,"./util":71}],48:[function(require,module,exports){
  4307. var isES5 = (function(){
  4308. "use strict";
  4309. return this === undefined;
  4310. })();
  4311. if (isES5) {
  4312. module.exports = {
  4313. freeze: Object.freeze,
  4314. defineProperty: Object.defineProperty,
  4315. getDescriptor: Object.getOwnPropertyDescriptor,
  4316. keys: Object.keys,
  4317. names: Object.getOwnPropertyNames,
  4318. getPrototypeOf: Object.getPrototypeOf,
  4319. isArray: Array.isArray,
  4320. isES5: isES5,
  4321. propertyIsWritable: function(obj, prop) {
  4322. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  4323. return !!(!descriptor || descriptor.writable || descriptor.set);
  4324. }
  4325. };
  4326. } else {
  4327. var has = {}.hasOwnProperty;
  4328. var str = {}.toString;
  4329. var proto = {}.constructor.prototype;
  4330. var ObjectKeys = function (o) {
  4331. var ret = [];
  4332. for (var key in o) {
  4333. if (has.call(o, key)) {
  4334. ret.push(key);
  4335. }
  4336. }
  4337. return ret;
  4338. };
  4339. var ObjectGetDescriptor = function(o, key) {
  4340. return {value: o[key]};
  4341. };
  4342. var ObjectDefineProperty = function (o, key, desc) {
  4343. o[key] = desc.value;
  4344. return o;
  4345. };
  4346. var ObjectFreeze = function (obj) {
  4347. return obj;
  4348. };
  4349. var ObjectGetPrototypeOf = function (obj) {
  4350. try {
  4351. return Object(obj).constructor.prototype;
  4352. }
  4353. catch (e) {
  4354. return proto;
  4355. }
  4356. };
  4357. var ArrayIsArray = function (obj) {
  4358. try {
  4359. return str.call(obj) === "[object Array]";
  4360. }
  4361. catch(e) {
  4362. return false;
  4363. }
  4364. };
  4365. module.exports = {
  4366. isArray: ArrayIsArray,
  4367. keys: ObjectKeys,
  4368. names: ObjectKeys,
  4369. defineProperty: ObjectDefineProperty,
  4370. getDescriptor: ObjectGetDescriptor,
  4371. freeze: ObjectFreeze,
  4372. getPrototypeOf: ObjectGetPrototypeOf,
  4373. isES5: isES5,
  4374. propertyIsWritable: function() {
  4375. return true;
  4376. }
  4377. };
  4378. }
  4379. },{}],49:[function(require,module,exports){
  4380. "use strict";
  4381. module.exports = function(Promise, INTERNAL) {
  4382. var PromiseMap = Promise.map;
  4383. Promise.prototype.filter = function (fn, options) {
  4384. return PromiseMap(this, fn, options, INTERNAL);
  4385. };
  4386. Promise.filter = function (promises, fn, options) {
  4387. return PromiseMap(promises, fn, options, INTERNAL);
  4388. };
  4389. };
  4390. },{}],50:[function(require,module,exports){
  4391. "use strict";
  4392. module.exports = function(Promise, tryConvertToPromise) {
  4393. var util = require("./util");
  4394. var CancellationError = Promise.CancellationError;
  4395. var errorObj = util.errorObj;
  4396. function PassThroughHandlerContext(promise, type, handler) {
  4397. this.promise = promise;
  4398. this.type = type;
  4399. this.handler = handler;
  4400. this.called = false;
  4401. this.cancelPromise = null;
  4402. }
  4403. PassThroughHandlerContext.prototype.isFinallyHandler = function() {
  4404. return this.type === 0;
  4405. };
  4406. function FinallyHandlerCancelReaction(finallyHandler) {
  4407. this.finallyHandler = finallyHandler;
  4408. }
  4409. FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
  4410. checkCancel(this.finallyHandler);
  4411. };
  4412. function checkCancel(ctx, reason) {
  4413. if (ctx.cancelPromise != null) {
  4414. if (arguments.length > 1) {
  4415. ctx.cancelPromise._reject(reason);
  4416. } else {
  4417. ctx.cancelPromise._cancel();
  4418. }
  4419. ctx.cancelPromise = null;
  4420. return true;
  4421. }
  4422. return false;
  4423. }
  4424. function succeed() {
  4425. return finallyHandler.call(this, this.promise._target()._settledValue());
  4426. }
  4427. function fail(reason) {
  4428. if (checkCancel(this, reason)) return;
  4429. errorObj.e = reason;
  4430. return errorObj;
  4431. }
  4432. function finallyHandler(reasonOrValue) {
  4433. var promise = this.promise;
  4434. var handler = this.handler;
  4435. if (!this.called) {
  4436. this.called = true;
  4437. var ret = this.isFinallyHandler()
  4438. ? handler.call(promise._boundValue())
  4439. : handler.call(promise._boundValue(), reasonOrValue);
  4440. if (ret !== undefined) {
  4441. promise._setReturnedNonUndefined();
  4442. var maybePromise = tryConvertToPromise(ret, promise);
  4443. if (maybePromise instanceof Promise) {
  4444. if (this.cancelPromise != null) {
  4445. if (maybePromise.isCancelled()) {
  4446. var reason =
  4447. new CancellationError("late cancellation observer");
  4448. promise._attachExtraTrace(reason);
  4449. errorObj.e = reason;
  4450. return errorObj;
  4451. } else if (maybePromise.isPending()) {
  4452. maybePromise._attachCancellationCallback(
  4453. new FinallyHandlerCancelReaction(this));
  4454. }
  4455. }
  4456. return maybePromise._then(
  4457. succeed, fail, undefined, this, undefined);
  4458. }
  4459. }
  4460. }
  4461. if (promise.isRejected()) {
  4462. checkCancel(this);
  4463. errorObj.e = reasonOrValue;
  4464. return errorObj;
  4465. } else {
  4466. checkCancel(this);
  4467. return reasonOrValue;
  4468. }
  4469. }
  4470. Promise.prototype._passThrough = function(handler, type, success, fail) {
  4471. if (typeof handler !== "function") return this.then();
  4472. return this._then(success,
  4473. fail,
  4474. undefined,
  4475. new PassThroughHandlerContext(this, type, handler),
  4476. undefined);
  4477. };
  4478. Promise.prototype.lastly =
  4479. Promise.prototype["finally"] = function (handler) {
  4480. return this._passThrough(handler,
  4481. 0,
  4482. finallyHandler,
  4483. finallyHandler);
  4484. };
  4485. Promise.prototype.tap = function (handler) {
  4486. return this._passThrough(handler, 1, finallyHandler);
  4487. };
  4488. return PassThroughHandlerContext;
  4489. };
  4490. },{"./util":71}],51:[function(require,module,exports){
  4491. "use strict";
  4492. module.exports = function(Promise,
  4493. apiRejection,
  4494. INTERNAL,
  4495. tryConvertToPromise,
  4496. Proxyable,
  4497. debug) {
  4498. var errors = require("./errors");
  4499. var TypeError = errors.TypeError;
  4500. var util = require("./util");
  4501. var errorObj = util.errorObj;
  4502. var tryCatch = util.tryCatch;
  4503. var yieldHandlers = [];
  4504. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  4505. for (var i = 0; i < yieldHandlers.length; ++i) {
  4506. traceParent._pushContext();
  4507. var result = tryCatch(yieldHandlers[i])(value);
  4508. traceParent._popContext();
  4509. if (result === errorObj) {
  4510. traceParent._pushContext();
  4511. var ret = Promise.reject(errorObj.e);
  4512. traceParent._popContext();
  4513. return ret;
  4514. }
  4515. var maybePromise = tryConvertToPromise(result, traceParent);
  4516. if (maybePromise instanceof Promise) return maybePromise;
  4517. }
  4518. return null;
  4519. }
  4520. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  4521. if (debug.cancellation()) {
  4522. var internal = new Promise(INTERNAL);
  4523. var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
  4524. this._promise = internal.lastly(function() {
  4525. return _finallyPromise;
  4526. });
  4527. internal._captureStackTrace();
  4528. internal._setOnCancel(this);
  4529. } else {
  4530. var promise = this._promise = new Promise(INTERNAL);
  4531. promise._captureStackTrace();
  4532. }
  4533. this._stack = stack;
  4534. this._generatorFunction = generatorFunction;
  4535. this._receiver = receiver;
  4536. this._generator = undefined;
  4537. this._yieldHandlers = typeof yieldHandler === "function"
  4538. ? [yieldHandler].concat(yieldHandlers)
  4539. : yieldHandlers;
  4540. this._yieldedPromise = null;
  4541. this._cancellationPhase = false;
  4542. }
  4543. util.inherits(PromiseSpawn, Proxyable);
  4544. PromiseSpawn.prototype._isResolved = function() {
  4545. return this._promise === null;
  4546. };
  4547. PromiseSpawn.prototype._cleanup = function() {
  4548. this._promise = this._generator = null;
  4549. if (debug.cancellation() && this._finallyPromise !== null) {
  4550. this._finallyPromise._fulfill();
  4551. this._finallyPromise = null;
  4552. }
  4553. };
  4554. PromiseSpawn.prototype._promiseCancelled = function() {
  4555. if (this._isResolved()) return;
  4556. var implementsReturn = typeof this._generator["return"] !== "undefined";
  4557. var result;
  4558. if (!implementsReturn) {
  4559. var reason = new Promise.CancellationError(
  4560. "generator .return() sentinel");
  4561. Promise.coroutine.returnSentinel = reason;
  4562. this._promise._attachExtraTrace(reason);
  4563. this._promise._pushContext();
  4564. result = tryCatch(this._generator["throw"]).call(this._generator,
  4565. reason);
  4566. this._promise._popContext();
  4567. } else {
  4568. this._promise._pushContext();
  4569. result = tryCatch(this._generator["return"]).call(this._generator,
  4570. undefined);
  4571. this._promise._popContext();
  4572. }
  4573. this._cancellationPhase = true;
  4574. this._yieldedPromise = null;
  4575. this._continue(result);
  4576. };
  4577. PromiseSpawn.prototype._promiseFulfilled = function(value) {
  4578. this._yieldedPromise = null;
  4579. this._promise._pushContext();
  4580. var result = tryCatch(this._generator.next).call(this._generator, value);
  4581. this._promise._popContext();
  4582. this._continue(result);
  4583. };
  4584. PromiseSpawn.prototype._promiseRejected = function(reason) {
  4585. this._yieldedPromise = null;
  4586. this._promise._attachExtraTrace(reason);
  4587. this._promise._pushContext();
  4588. var result = tryCatch(this._generator["throw"])
  4589. .call(this._generator, reason);
  4590. this._promise._popContext();
  4591. this._continue(result);
  4592. };
  4593. PromiseSpawn.prototype._resultCancelled = function() {
  4594. if (this._yieldedPromise instanceof Promise) {
  4595. var promise = this._yieldedPromise;
  4596. this._yieldedPromise = null;
  4597. promise.cancel();
  4598. }
  4599. };
  4600. PromiseSpawn.prototype.promise = function () {
  4601. return this._promise;
  4602. };
  4603. PromiseSpawn.prototype._run = function () {
  4604. this._generator = this._generatorFunction.call(this._receiver);
  4605. this._receiver =
  4606. this._generatorFunction = undefined;
  4607. this._promiseFulfilled(undefined);
  4608. };
  4609. PromiseSpawn.prototype._continue = function (result) {
  4610. var promise = this._promise;
  4611. if (result === errorObj) {
  4612. this._cleanup();
  4613. if (this._cancellationPhase) {
  4614. return promise.cancel();
  4615. } else {
  4616. return promise._rejectCallback(result.e, false);
  4617. }
  4618. }
  4619. var value = result.value;
  4620. if (result.done === true) {
  4621. this._cleanup();
  4622. if (this._cancellationPhase) {
  4623. return promise.cancel();
  4624. } else {
  4625. return promise._resolveCallback(value);
  4626. }
  4627. } else {
  4628. var maybePromise = tryConvertToPromise(value, this._promise);
  4629. if (!(maybePromise instanceof Promise)) {
  4630. maybePromise =
  4631. promiseFromYieldHandler(maybePromise,
  4632. this._yieldHandlers,
  4633. this._promise);
  4634. if (maybePromise === null) {
  4635. this._promiseRejected(
  4636. new TypeError(
  4637. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
  4638. "From coroutine:\u000a" +
  4639. this._stack.split("\n").slice(1, -7).join("\n")
  4640. )
  4641. );
  4642. return;
  4643. }
  4644. }
  4645. maybePromise = maybePromise._target();
  4646. var bitField = maybePromise._bitField;
  4647. ;
  4648. if (((bitField & 50397184) === 0)) {
  4649. this._yieldedPromise = maybePromise;
  4650. maybePromise._proxy(this, null);
  4651. } else if (((bitField & 33554432) !== 0)) {
  4652. this._promiseFulfilled(maybePromise._value());
  4653. } else if (((bitField & 16777216) !== 0)) {
  4654. this._promiseRejected(maybePromise._reason());
  4655. } else {
  4656. this._promiseCancelled();
  4657. }
  4658. }
  4659. };
  4660. Promise.coroutine = function (generatorFunction, options) {
  4661. if (typeof generatorFunction !== "function") {
  4662. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4663. }
  4664. var yieldHandler = Object(options).yieldHandler;
  4665. var PromiseSpawn$ = PromiseSpawn;
  4666. var stack = new Error().stack;
  4667. return function () {
  4668. var generator = generatorFunction.apply(this, arguments);
  4669. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  4670. stack);
  4671. var ret = spawn.promise();
  4672. spawn._generator = generator;
  4673. spawn._promiseFulfilled(undefined);
  4674. return ret;
  4675. };
  4676. };
  4677. Promise.coroutine.addYieldHandler = function(fn) {
  4678. if (typeof fn !== "function") {
  4679. throw new TypeError("expecting a function but got " + util.classString(fn));
  4680. }
  4681. yieldHandlers.push(fn);
  4682. };
  4683. Promise.spawn = function (generatorFunction) {
  4684. debug.deprecated("Promise.spawn()", "Promise.coroutine()");
  4685. if (typeof generatorFunction !== "function") {
  4686. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4687. }
  4688. var spawn = new PromiseSpawn(generatorFunction, this);
  4689. var ret = spawn.promise();
  4690. spawn._run(Promise.spawn);
  4691. return ret;
  4692. };
  4693. };
  4694. },{"./errors":47,"./util":71}],52:[function(require,module,exports){
  4695. "use strict";
  4696. module.exports =
  4697. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
  4698. var util = require("./util");
  4699. var canEvaluate = util.canEvaluate;
  4700. var tryCatch = util.tryCatch;
  4701. var errorObj = util.errorObj;
  4702. var reject;
  4703. if (!false) {
  4704. if (canEvaluate) {
  4705. var thenCallback = function(i) {
  4706. return new Function("value", "holder", " \n\
  4707. 'use strict'; \n\
  4708. holder.pIndex = value; \n\
  4709. holder.checkFulfillment(this); \n\
  4710. ".replace(/Index/g, i));
  4711. };
  4712. var promiseSetter = function(i) {
  4713. return new Function("promise", "holder", " \n\
  4714. 'use strict'; \n\
  4715. holder.pIndex = promise; \n\
  4716. ".replace(/Index/g, i));
  4717. };
  4718. var generateHolderClass = function(total) {
  4719. var props = new Array(total);
  4720. for (var i = 0; i < props.length; ++i) {
  4721. props[i] = "this.p" + (i+1);
  4722. }
  4723. var assignment = props.join(" = ") + " = null;";
  4724. var cancellationCode= "var promise;\n" + props.map(function(prop) {
  4725. return " \n\
  4726. promise = " + prop + "; \n\
  4727. if (promise instanceof Promise) { \n\
  4728. promise.cancel(); \n\
  4729. } \n\
  4730. ";
  4731. }).join("\n");
  4732. var passedArguments = props.join(", ");
  4733. var name = "Holder$" + total;
  4734. var code = "return function(tryCatch, errorObj, Promise) { \n\
  4735. 'use strict'; \n\
  4736. function [TheName](fn) { \n\
  4737. [TheProperties] \n\
  4738. this.fn = fn; \n\
  4739. this.now = 0; \n\
  4740. } \n\
  4741. [TheName].prototype.checkFulfillment = function(promise) { \n\
  4742. var now = ++this.now; \n\
  4743. if (now === [TheTotal]) { \n\
  4744. promise._pushContext(); \n\
  4745. var callback = this.fn; \n\
  4746. var ret = tryCatch(callback)([ThePassedArguments]); \n\
  4747. promise._popContext(); \n\
  4748. if (ret === errorObj) { \n\
  4749. promise._rejectCallback(ret.e, false); \n\
  4750. } else { \n\
  4751. promise._resolveCallback(ret); \n\
  4752. } \n\
  4753. } \n\
  4754. }; \n\
  4755. \n\
  4756. [TheName].prototype._resultCancelled = function() { \n\
  4757. [CancellationCode] \n\
  4758. }; \n\
  4759. \n\
  4760. return [TheName]; \n\
  4761. }(tryCatch, errorObj, Promise); \n\
  4762. ";
  4763. code = code.replace(/\[TheName\]/g, name)
  4764. .replace(/\[TheTotal\]/g, total)
  4765. .replace(/\[ThePassedArguments\]/g, passedArguments)
  4766. .replace(/\[TheProperties\]/g, assignment)
  4767. .replace(/\[CancellationCode\]/g, cancellationCode);
  4768. return new Function("tryCatch", "errorObj", "Promise", code)
  4769. (tryCatch, errorObj, Promise);
  4770. };
  4771. var holderClasses = [];
  4772. var thenCallbacks = [];
  4773. var promiseSetters = [];
  4774. for (var i = 0; i < 8; ++i) {
  4775. holderClasses.push(generateHolderClass(i + 1));
  4776. thenCallbacks.push(thenCallback(i + 1));
  4777. promiseSetters.push(promiseSetter(i + 1));
  4778. }
  4779. reject = function (reason) {
  4780. this._reject(reason);
  4781. };
  4782. }}
  4783. Promise.join = function () {
  4784. var last = arguments.length - 1;
  4785. var fn;
  4786. if (last > 0 && typeof arguments[last] === "function") {
  4787. fn = arguments[last];
  4788. if (!false) {
  4789. if (last <= 8 && canEvaluate) {
  4790. var ret = new Promise(INTERNAL);
  4791. ret._captureStackTrace();
  4792. var HolderClass = holderClasses[last - 1];
  4793. var holder = new HolderClass(fn);
  4794. var callbacks = thenCallbacks;
  4795. for (var i = 0; i < last; ++i) {
  4796. var maybePromise = tryConvertToPromise(arguments[i], ret);
  4797. if (maybePromise instanceof Promise) {
  4798. maybePromise = maybePromise._target();
  4799. var bitField = maybePromise._bitField;
  4800. ;
  4801. if (((bitField & 50397184) === 0)) {
  4802. maybePromise._then(callbacks[i], reject,
  4803. undefined, ret, holder);
  4804. promiseSetters[i](maybePromise, holder);
  4805. } else if (((bitField & 33554432) !== 0)) {
  4806. callbacks[i].call(ret,
  4807. maybePromise._value(), holder);
  4808. } else if (((bitField & 16777216) !== 0)) {
  4809. ret._reject(maybePromise._reason());
  4810. } else {
  4811. ret._cancel();
  4812. }
  4813. } else {
  4814. callbacks[i].call(ret, maybePromise, holder);
  4815. }
  4816. }
  4817. if (!ret._isFateSealed()) {
  4818. ret._setAsyncGuaranteed();
  4819. ret._setOnCancel(holder);
  4820. }
  4821. return ret;
  4822. }
  4823. }
  4824. }
  4825. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
  4826. if (fn) args.pop();
  4827. var ret = new PromiseArray(args).promise();
  4828. return fn !== undefined ? ret.spread(fn) : ret;
  4829. };
  4830. };
  4831. },{"./util":71}],53:[function(require,module,exports){
  4832. "use strict";
  4833. module.exports = function(Promise,
  4834. PromiseArray,
  4835. apiRejection,
  4836. tryConvertToPromise,
  4837. INTERNAL,
  4838. debug) {
  4839. var getDomain = Promise._getDomain;
  4840. var util = require("./util");
  4841. var tryCatch = util.tryCatch;
  4842. var errorObj = util.errorObj;
  4843. var EMPTY_ARRAY = [];
  4844. function MappingPromiseArray(promises, fn, limit, _filter) {
  4845. this.constructor$(promises);
  4846. this._promise._captureStackTrace();
  4847. var domain = getDomain();
  4848. this._callback = domain === null ? fn : domain.bind(fn);
  4849. this._preservedValues = _filter === INTERNAL
  4850. ? new Array(this.length())
  4851. : null;
  4852. this._limit = limit;
  4853. this._inFlight = 0;
  4854. this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
  4855. this._init$(undefined, -2);
  4856. }
  4857. util.inherits(MappingPromiseArray, PromiseArray);
  4858. MappingPromiseArray.prototype._init = function () {};
  4859. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  4860. var values = this._values;
  4861. var length = this.length();
  4862. var preservedValues = this._preservedValues;
  4863. var limit = this._limit;
  4864. if (index < 0) {
  4865. index = (index * -1) - 1;
  4866. values[index] = value;
  4867. if (limit >= 1) {
  4868. this._inFlight--;
  4869. this._drainQueue();
  4870. if (this._isResolved()) return true;
  4871. }
  4872. } else {
  4873. if (limit >= 1 && this._inFlight >= limit) {
  4874. values[index] = value;
  4875. this._queue.push(index);
  4876. return false;
  4877. }
  4878. if (preservedValues !== null) preservedValues[index] = value;
  4879. var promise = this._promise;
  4880. var callback = this._callback;
  4881. var receiver = promise._boundValue();
  4882. promise._pushContext();
  4883. var ret = tryCatch(callback).call(receiver, value, index, length);
  4884. var promiseCreated = promise._popContext();
  4885. debug.checkForgottenReturns(
  4886. ret,
  4887. promiseCreated,
  4888. preservedValues !== null ? "Promise.filter" : "Promise.map",
  4889. promise
  4890. );
  4891. if (ret === errorObj) {
  4892. this._reject(ret.e);
  4893. return true;
  4894. }
  4895. var maybePromise = tryConvertToPromise(ret, this._promise);
  4896. if (maybePromise instanceof Promise) {
  4897. maybePromise = maybePromise._target();
  4898. var bitField = maybePromise._bitField;
  4899. ;
  4900. if (((bitField & 50397184) === 0)) {
  4901. if (limit >= 1) this._inFlight++;
  4902. values[index] = maybePromise;
  4903. maybePromise._proxy(this, (index + 1) * -1);
  4904. return false;
  4905. } else if (((bitField & 33554432) !== 0)) {
  4906. ret = maybePromise._value();
  4907. } else if (((bitField & 16777216) !== 0)) {
  4908. this._reject(maybePromise._reason());
  4909. return true;
  4910. } else {
  4911. this._cancel();
  4912. return true;
  4913. }
  4914. }
  4915. values[index] = ret;
  4916. }
  4917. var totalResolved = ++this._totalResolved;
  4918. if (totalResolved >= length) {
  4919. if (preservedValues !== null) {
  4920. this._filter(values, preservedValues);
  4921. } else {
  4922. this._resolve(values);
  4923. }
  4924. return true;
  4925. }
  4926. return false;
  4927. };
  4928. MappingPromiseArray.prototype._drainQueue = function () {
  4929. var queue = this._queue;
  4930. var limit = this._limit;
  4931. var values = this._values;
  4932. while (queue.length > 0 && this._inFlight < limit) {
  4933. if (this._isResolved()) return;
  4934. var index = queue.pop();
  4935. this._promiseFulfilled(values[index], index);
  4936. }
  4937. };
  4938. MappingPromiseArray.prototype._filter = function (booleans, values) {
  4939. var len = values.length;
  4940. var ret = new Array(len);
  4941. var j = 0;
  4942. for (var i = 0; i < len; ++i) {
  4943. if (booleans[i]) ret[j++] = values[i];
  4944. }
  4945. ret.length = j;
  4946. this._resolve(ret);
  4947. };
  4948. MappingPromiseArray.prototype.preservedValues = function () {
  4949. return this._preservedValues;
  4950. };
  4951. function map(promises, fn, options, _filter) {
  4952. if (typeof fn !== "function") {
  4953. return apiRejection("expecting a function but got " + util.classString(fn));
  4954. }
  4955. var limit = 0;
  4956. if (options !== undefined) {
  4957. if (typeof options === "object" && options !== null) {
  4958. if (typeof options.concurrency !== "number") {
  4959. return Promise.reject(
  4960. new TypeError("'concurrency' must be a number but it is " +
  4961. util.classString(options.concurrency)));
  4962. }
  4963. limit = options.concurrency;
  4964. } else {
  4965. return Promise.reject(new TypeError(
  4966. "options argument must be an object but it is " +
  4967. util.classString(options)));
  4968. }
  4969. }
  4970. limit = typeof limit === "number" &&
  4971. isFinite(limit) && limit >= 1 ? limit : 0;
  4972. return new MappingPromiseArray(promises, fn, limit, _filter).promise();
  4973. }
  4974. Promise.prototype.map = function (fn, options) {
  4975. return map(this, fn, options, null);
  4976. };
  4977. Promise.map = function (promises, fn, options, _filter) {
  4978. return map(promises, fn, options, _filter);
  4979. };
  4980. };
  4981. },{"./util":71}],54:[function(require,module,exports){
  4982. "use strict";
  4983. module.exports =
  4984. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  4985. var util = require("./util");
  4986. var tryCatch = util.tryCatch;
  4987. Promise.method = function (fn) {
  4988. if (typeof fn !== "function") {
  4989. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  4990. }
  4991. return function () {
  4992. var ret = new Promise(INTERNAL);
  4993. ret._captureStackTrace();
  4994. ret._pushContext();
  4995. var value = tryCatch(fn).apply(this, arguments);
  4996. var promiseCreated = ret._popContext();
  4997. debug.checkForgottenReturns(
  4998. value, promiseCreated, "Promise.method", ret);
  4999. ret._resolveFromSyncValue(value);
  5000. return ret;
  5001. };
  5002. };
  5003. Promise.attempt = Promise["try"] = function (fn) {
  5004. if (typeof fn !== "function") {
  5005. return apiRejection("expecting a function but got " + util.classString(fn));
  5006. }
  5007. var ret = new Promise(INTERNAL);
  5008. ret._captureStackTrace();
  5009. ret._pushContext();
  5010. var value;
  5011. if (arguments.length > 1) {
  5012. debug.deprecated("calling Promise.try with more than 1 argument");
  5013. var arg = arguments[1];
  5014. var ctx = arguments[2];
  5015. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  5016. : tryCatch(fn).call(ctx, arg);
  5017. } else {
  5018. value = tryCatch(fn)();
  5019. }
  5020. var promiseCreated = ret._popContext();
  5021. debug.checkForgottenReturns(
  5022. value, promiseCreated, "Promise.try", ret);
  5023. ret._resolveFromSyncValue(value);
  5024. return ret;
  5025. };
  5026. Promise.prototype._resolveFromSyncValue = function (value) {
  5027. if (value === util.errorObj) {
  5028. this._rejectCallback(value.e, false);
  5029. } else {
  5030. this._resolveCallback(value, true);
  5031. }
  5032. };
  5033. };
  5034. },{"./util":71}],55:[function(require,module,exports){
  5035. "use strict";
  5036. var util = require("./util");
  5037. var maybeWrapAsError = util.maybeWrapAsError;
  5038. var errors = require("./errors");
  5039. var OperationalError = errors.OperationalError;
  5040. var es5 = require("./es5");
  5041. function isUntypedError(obj) {
  5042. return obj instanceof Error &&
  5043. es5.getPrototypeOf(obj) === Error.prototype;
  5044. }
  5045. var rErrorKey = /^(?:name|message|stack|cause)$/;
  5046. function wrapAsOperationalError(obj) {
  5047. var ret;
  5048. if (isUntypedError(obj)) {
  5049. ret = new OperationalError(obj);
  5050. ret.name = obj.name;
  5051. ret.message = obj.message;
  5052. ret.stack = obj.stack;
  5053. var keys = es5.keys(obj);
  5054. for (var i = 0; i < keys.length; ++i) {
  5055. var key = keys[i];
  5056. if (!rErrorKey.test(key)) {
  5057. ret[key] = obj[key];
  5058. }
  5059. }
  5060. return ret;
  5061. }
  5062. util.markAsOriginatingFromRejection(obj);
  5063. return obj;
  5064. }
  5065. function nodebackForPromise(promise, multiArgs) {
  5066. return function(err, value) {
  5067. if (promise === null) return;
  5068. if (err) {
  5069. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  5070. promise._attachExtraTrace(wrapped);
  5071. promise._reject(wrapped);
  5072. } else if (!multiArgs) {
  5073. promise._fulfill(value);
  5074. } else {
  5075. var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
  5076. promise._fulfill(args);
  5077. }
  5078. promise = null;
  5079. };
  5080. }
  5081. module.exports = nodebackForPromise;
  5082. },{"./errors":47,"./es5":48,"./util":71}],56:[function(require,module,exports){
  5083. "use strict";
  5084. module.exports = function(Promise) {
  5085. var util = require("./util");
  5086. var async = Promise._async;
  5087. var tryCatch = util.tryCatch;
  5088. var errorObj = util.errorObj;
  5089. function spreadAdapter(val, nodeback) {
  5090. var promise = this;
  5091. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  5092. var ret =
  5093. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  5094. if (ret === errorObj) {
  5095. async.throwLater(ret.e);
  5096. }
  5097. }
  5098. function successAdapter(val, nodeback) {
  5099. var promise = this;
  5100. var receiver = promise._boundValue();
  5101. var ret = val === undefined
  5102. ? tryCatch(nodeback).call(receiver, null)
  5103. : tryCatch(nodeback).call(receiver, null, val);
  5104. if (ret === errorObj) {
  5105. async.throwLater(ret.e);
  5106. }
  5107. }
  5108. function errorAdapter(reason, nodeback) {
  5109. var promise = this;
  5110. if (!reason) {
  5111. var newReason = new Error(reason + "");
  5112. newReason.cause = reason;
  5113. reason = newReason;
  5114. }
  5115. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  5116. if (ret === errorObj) {
  5117. async.throwLater(ret.e);
  5118. }
  5119. }
  5120. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  5121. options) {
  5122. if (typeof nodeback == "function") {
  5123. var adapter = successAdapter;
  5124. if (options !== undefined && Object(options).spread) {
  5125. adapter = spreadAdapter;
  5126. }
  5127. this._then(
  5128. adapter,
  5129. errorAdapter,
  5130. undefined,
  5131. this,
  5132. nodeback
  5133. );
  5134. }
  5135. return this;
  5136. };
  5137. };
  5138. },{"./util":71}],57:[function(require,module,exports){
  5139. (function (process){
  5140. "use strict";
  5141. module.exports = function() {
  5142. var makeSelfResolutionError = function () {
  5143. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5144. };
  5145. var reflectHandler = function() {
  5146. return new Promise.PromiseInspection(this._target());
  5147. };
  5148. var apiRejection = function(msg) {
  5149. return Promise.reject(new TypeError(msg));
  5150. };
  5151. function Proxyable() {}
  5152. var UNDEFINED_BINDING = {};
  5153. var util = require("./util");
  5154. var getDomain;
  5155. if (util.isNode) {
  5156. getDomain = function() {
  5157. var ret = process.domain;
  5158. if (ret === undefined) ret = null;
  5159. return ret;
  5160. };
  5161. } else {
  5162. getDomain = function() {
  5163. return null;
  5164. };
  5165. }
  5166. util.notEnumerableProp(Promise, "_getDomain", getDomain);
  5167. var es5 = require("./es5");
  5168. var Async = require("./async");
  5169. var async = new Async();
  5170. es5.defineProperty(Promise, "_async", {value: async});
  5171. var errors = require("./errors");
  5172. var TypeError = Promise.TypeError = errors.TypeError;
  5173. Promise.RangeError = errors.RangeError;
  5174. var CancellationError = Promise.CancellationError = errors.CancellationError;
  5175. Promise.TimeoutError = errors.TimeoutError;
  5176. Promise.OperationalError = errors.OperationalError;
  5177. Promise.RejectionError = errors.OperationalError;
  5178. Promise.AggregateError = errors.AggregateError;
  5179. var INTERNAL = function(){};
  5180. var APPLY = {};
  5181. var NEXT_FILTER = {};
  5182. var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
  5183. var PromiseArray =
  5184. require("./promise_array")(Promise, INTERNAL,
  5185. tryConvertToPromise, apiRejection, Proxyable);
  5186. var Context = require("./context")(Promise);
  5187. /*jshint unused:false*/
  5188. var createContext = Context.create;
  5189. var debug = require("./debuggability")(Promise, Context);
  5190. var CapturedTrace = debug.CapturedTrace;
  5191. var PassThroughHandlerContext =
  5192. require("./finally")(Promise, tryConvertToPromise);
  5193. var catchFilter = require("./catch_filter")(NEXT_FILTER);
  5194. var nodebackForPromise = require("./nodeback");
  5195. var errorObj = util.errorObj;
  5196. var tryCatch = util.tryCatch;
  5197. function check(self, executor) {
  5198. if (typeof executor !== "function") {
  5199. throw new TypeError("expecting a function but got " + util.classString(executor));
  5200. }
  5201. if (self.constructor !== Promise) {
  5202. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5203. }
  5204. }
  5205. function Promise(executor) {
  5206. this._bitField = 0;
  5207. this._fulfillmentHandler0 = undefined;
  5208. this._rejectionHandler0 = undefined;
  5209. this._promise0 = undefined;
  5210. this._receiver0 = undefined;
  5211. if (executor !== INTERNAL) {
  5212. check(this, executor);
  5213. this._resolveFromExecutor(executor);
  5214. }
  5215. this._promiseCreated();
  5216. this._fireEvent("promiseCreated", this);
  5217. }
  5218. Promise.prototype.toString = function () {
  5219. return "[object Promise]";
  5220. };
  5221. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  5222. var len = arguments.length;
  5223. if (len > 1) {
  5224. var catchInstances = new Array(len - 1),
  5225. j = 0, i;
  5226. for (i = 0; i < len - 1; ++i) {
  5227. var item = arguments[i];
  5228. if (util.isObject(item)) {
  5229. catchInstances[j++] = item;
  5230. } else {
  5231. return apiRejection("expecting an object but got " + util.classString(item));
  5232. }
  5233. }
  5234. catchInstances.length = j;
  5235. fn = arguments[i];
  5236. return this.then(undefined, catchFilter(catchInstances, fn, this));
  5237. }
  5238. return this.then(undefined, fn);
  5239. };
  5240. Promise.prototype.reflect = function () {
  5241. return this._then(reflectHandler,
  5242. reflectHandler, undefined, this, undefined);
  5243. };
  5244. Promise.prototype.then = function (didFulfill, didReject) {
  5245. if (debug.warnings() && arguments.length > 0 &&
  5246. typeof didFulfill !== "function" &&
  5247. typeof didReject !== "function") {
  5248. var msg = ".then() only accepts functions but was passed: " +
  5249. util.classString(didFulfill);
  5250. if (arguments.length > 1) {
  5251. msg += ", " + util.classString(didReject);
  5252. }
  5253. this._warn(msg);
  5254. }
  5255. return this._then(didFulfill, didReject, undefined, undefined, undefined);
  5256. };
  5257. Promise.prototype.done = function (didFulfill, didReject) {
  5258. var promise =
  5259. this._then(didFulfill, didReject, undefined, undefined, undefined);
  5260. promise._setIsFinal();
  5261. };
  5262. Promise.prototype.spread = function (fn) {
  5263. if (typeof fn !== "function") {
  5264. return apiRejection("expecting a function but got " + util.classString(fn));
  5265. }
  5266. return this.all()._then(fn, undefined, undefined, APPLY, undefined);
  5267. };
  5268. Promise.prototype.toJSON = function () {
  5269. var ret = {
  5270. isFulfilled: false,
  5271. isRejected: false,
  5272. fulfillmentValue: undefined,
  5273. rejectionReason: undefined
  5274. };
  5275. if (this.isFulfilled()) {
  5276. ret.fulfillmentValue = this.value();
  5277. ret.isFulfilled = true;
  5278. } else if (this.isRejected()) {
  5279. ret.rejectionReason = this.reason();
  5280. ret.isRejected = true;
  5281. }
  5282. return ret;
  5283. };
  5284. Promise.prototype.all = function () {
  5285. if (arguments.length > 0) {
  5286. this._warn(".all() was passed arguments but it does not take any");
  5287. }
  5288. return new PromiseArray(this).promise();
  5289. };
  5290. Promise.prototype.error = function (fn) {
  5291. return this.caught(util.originatesFromRejection, fn);
  5292. };
  5293. Promise.getNewLibraryCopy = module.exports;
  5294. Promise.is = function (val) {
  5295. return val instanceof Promise;
  5296. };
  5297. Promise.fromNode = Promise.fromCallback = function(fn) {
  5298. var ret = new Promise(INTERNAL);
  5299. ret._captureStackTrace();
  5300. var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
  5301. : false;
  5302. var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
  5303. if (result === errorObj) {
  5304. ret._rejectCallback(result.e, true);
  5305. }
  5306. if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
  5307. return ret;
  5308. };
  5309. Promise.all = function (promises) {
  5310. return new PromiseArray(promises).promise();
  5311. };
  5312. Promise.cast = function (obj) {
  5313. var ret = tryConvertToPromise(obj);
  5314. if (!(ret instanceof Promise)) {
  5315. ret = new Promise(INTERNAL);
  5316. ret._captureStackTrace();
  5317. ret._setFulfilled();
  5318. ret._rejectionHandler0 = obj;
  5319. }
  5320. return ret;
  5321. };
  5322. Promise.resolve = Promise.fulfilled = Promise.cast;
  5323. Promise.reject = Promise.rejected = function (reason) {
  5324. var ret = new Promise(INTERNAL);
  5325. ret._captureStackTrace();
  5326. ret._rejectCallback(reason, true);
  5327. return ret;
  5328. };
  5329. Promise.setScheduler = function(fn) {
  5330. if (typeof fn !== "function") {
  5331. throw new TypeError("expecting a function but got " + util.classString(fn));
  5332. }
  5333. return async.setScheduler(fn);
  5334. };
  5335. Promise.prototype._then = function (
  5336. didFulfill,
  5337. didReject,
  5338. _, receiver,
  5339. internalData
  5340. ) {
  5341. var haveInternalData = internalData !== undefined;
  5342. var promise = haveInternalData ? internalData : new Promise(INTERNAL);
  5343. var target = this._target();
  5344. var bitField = target._bitField;
  5345. if (!haveInternalData) {
  5346. promise._propagateFrom(this, 3);
  5347. promise._captureStackTrace();
  5348. if (receiver === undefined &&
  5349. ((this._bitField & 2097152) !== 0)) {
  5350. if (!((bitField & 50397184) === 0)) {
  5351. receiver = this._boundValue();
  5352. } else {
  5353. receiver = target === this ? undefined : this._boundTo;
  5354. }
  5355. }
  5356. this._fireEvent("promiseChained", this, promise);
  5357. }
  5358. var domain = getDomain();
  5359. if (!((bitField & 50397184) === 0)) {
  5360. var handler, value, settler = target._settlePromiseCtx;
  5361. if (((bitField & 33554432) !== 0)) {
  5362. value = target._rejectionHandler0;
  5363. handler = didFulfill;
  5364. } else if (((bitField & 16777216) !== 0)) {
  5365. value = target._fulfillmentHandler0;
  5366. handler = didReject;
  5367. target._unsetRejectionIsUnhandled();
  5368. } else {
  5369. settler = target._settlePromiseLateCancellationObserver;
  5370. value = new CancellationError("late cancellation observer");
  5371. target._attachExtraTrace(value);
  5372. handler = didReject;
  5373. }
  5374. async.invoke(settler, target, {
  5375. handler: domain === null ? handler
  5376. : (typeof handler === "function" && domain.bind(handler)),
  5377. promise: promise,
  5378. receiver: receiver,
  5379. value: value
  5380. });
  5381. } else {
  5382. target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
  5383. }
  5384. return promise;
  5385. };
  5386. Promise.prototype._length = function () {
  5387. return this._bitField & 65535;
  5388. };
  5389. Promise.prototype._isFateSealed = function () {
  5390. return (this._bitField & 117506048) !== 0;
  5391. };
  5392. Promise.prototype._isFollowing = function () {
  5393. return (this._bitField & 67108864) === 67108864;
  5394. };
  5395. Promise.prototype._setLength = function (len) {
  5396. this._bitField = (this._bitField & -65536) |
  5397. (len & 65535);
  5398. };
  5399. Promise.prototype._setFulfilled = function () {
  5400. this._bitField = this._bitField | 33554432;
  5401. this._fireEvent("promiseFulfilled", this);
  5402. };
  5403. Promise.prototype._setRejected = function () {
  5404. this._bitField = this._bitField | 16777216;
  5405. this._fireEvent("promiseRejected", this);
  5406. };
  5407. Promise.prototype._setFollowing = function () {
  5408. this._bitField = this._bitField | 67108864;
  5409. this._fireEvent("promiseResolved", this);
  5410. };
  5411. Promise.prototype._setIsFinal = function () {
  5412. this._bitField = this._bitField | 4194304;
  5413. };
  5414. Promise.prototype._isFinal = function () {
  5415. return (this._bitField & 4194304) > 0;
  5416. };
  5417. Promise.prototype._unsetCancelled = function() {
  5418. this._bitField = this._bitField & (~65536);
  5419. };
  5420. Promise.prototype._setCancelled = function() {
  5421. this._bitField = this._bitField | 65536;
  5422. this._fireEvent("promiseCancelled", this);
  5423. };
  5424. Promise.prototype._setAsyncGuaranteed = function() {
  5425. if (async.hasCustomScheduler()) return;
  5426. this._bitField = this._bitField | 134217728;
  5427. };
  5428. Promise.prototype._receiverAt = function (index) {
  5429. var ret = index === 0 ? this._receiver0 : this[
  5430. index * 4 - 4 + 3];
  5431. if (ret === UNDEFINED_BINDING) {
  5432. return undefined;
  5433. } else if (ret === undefined && this._isBound()) {
  5434. return this._boundValue();
  5435. }
  5436. return ret;
  5437. };
  5438. Promise.prototype._promiseAt = function (index) {
  5439. return this[
  5440. index * 4 - 4 + 2];
  5441. };
  5442. Promise.prototype._fulfillmentHandlerAt = function (index) {
  5443. return this[
  5444. index * 4 - 4 + 0];
  5445. };
  5446. Promise.prototype._rejectionHandlerAt = function (index) {
  5447. return this[
  5448. index * 4 - 4 + 1];
  5449. };
  5450. Promise.prototype._boundValue = function() {};
  5451. Promise.prototype._migrateCallback0 = function (follower) {
  5452. var bitField = follower._bitField;
  5453. var fulfill = follower._fulfillmentHandler0;
  5454. var reject = follower._rejectionHandler0;
  5455. var promise = follower._promise0;
  5456. var receiver = follower._receiverAt(0);
  5457. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  5458. this._addCallbacks(fulfill, reject, promise, receiver, null);
  5459. };
  5460. Promise.prototype._migrateCallbackAt = function (follower, index) {
  5461. var fulfill = follower._fulfillmentHandlerAt(index);
  5462. var reject = follower._rejectionHandlerAt(index);
  5463. var promise = follower._promiseAt(index);
  5464. var receiver = follower._receiverAt(index);
  5465. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  5466. this._addCallbacks(fulfill, reject, promise, receiver, null);
  5467. };
  5468. Promise.prototype._addCallbacks = function (
  5469. fulfill,
  5470. reject,
  5471. promise,
  5472. receiver,
  5473. domain
  5474. ) {
  5475. var index = this._length();
  5476. if (index >= 65535 - 4) {
  5477. index = 0;
  5478. this._setLength(0);
  5479. }
  5480. if (index === 0) {
  5481. this._promise0 = promise;
  5482. this._receiver0 = receiver;
  5483. if (typeof fulfill === "function") {
  5484. this._fulfillmentHandler0 =
  5485. domain === null ? fulfill : domain.bind(fulfill);
  5486. }
  5487. if (typeof reject === "function") {
  5488. this._rejectionHandler0 =
  5489. domain === null ? reject : domain.bind(reject);
  5490. }
  5491. } else {
  5492. var base = index * 4 - 4;
  5493. this[base + 2] = promise;
  5494. this[base + 3] = receiver;
  5495. if (typeof fulfill === "function") {
  5496. this[base + 0] =
  5497. domain === null ? fulfill : domain.bind(fulfill);
  5498. }
  5499. if (typeof reject === "function") {
  5500. this[base + 1] =
  5501. domain === null ? reject : domain.bind(reject);
  5502. }
  5503. }
  5504. this._setLength(index + 1);
  5505. return index;
  5506. };
  5507. Promise.prototype._proxy = function (proxyable, arg) {
  5508. this._addCallbacks(undefined, undefined, arg, proxyable, null);
  5509. };
  5510. Promise.prototype._resolveCallback = function(value, shouldBind) {
  5511. if (((this._bitField & 117506048) !== 0)) return;
  5512. if (value === this)
  5513. return this._rejectCallback(makeSelfResolutionError(), false);
  5514. var maybePromise = tryConvertToPromise(value, this);
  5515. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  5516. if (shouldBind) this._propagateFrom(maybePromise, 2);
  5517. var promise = maybePromise._target();
  5518. if (promise === this) {
  5519. this._reject(makeSelfResolutionError());
  5520. return;
  5521. }
  5522. var bitField = promise._bitField;
  5523. if (((bitField & 50397184) === 0)) {
  5524. var len = this._length();
  5525. if (len > 0) promise._migrateCallback0(this);
  5526. for (var i = 1; i < len; ++i) {
  5527. promise._migrateCallbackAt(this, i);
  5528. }
  5529. this._setFollowing();
  5530. this._setLength(0);
  5531. this._setFollowee(promise);
  5532. } else if (((bitField & 33554432) !== 0)) {
  5533. this._fulfill(promise._value());
  5534. } else if (((bitField & 16777216) !== 0)) {
  5535. this._reject(promise._reason());
  5536. } else {
  5537. var reason = new CancellationError("late cancellation observer");
  5538. promise._attachExtraTrace(reason);
  5539. this._reject(reason);
  5540. }
  5541. };
  5542. Promise.prototype._rejectCallback =
  5543. function(reason, synchronous, ignoreNonErrorWarnings) {
  5544. var trace = util.ensureErrorObject(reason);
  5545. var hasStack = trace === reason;
  5546. if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
  5547. var message = "a promise was rejected with a non-error: " +
  5548. util.classString(reason);
  5549. this._warn(message, true);
  5550. }
  5551. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  5552. this._reject(reason);
  5553. };
  5554. Promise.prototype._resolveFromExecutor = function (executor) {
  5555. var promise = this;
  5556. this._captureStackTrace();
  5557. this._pushContext();
  5558. var synchronous = true;
  5559. var r = this._execute(executor, function(value) {
  5560. promise._resolveCallback(value);
  5561. }, function (reason) {
  5562. promise._rejectCallback(reason, synchronous);
  5563. });
  5564. synchronous = false;
  5565. this._popContext();
  5566. if (r !== undefined) {
  5567. promise._rejectCallback(r, true);
  5568. }
  5569. };
  5570. Promise.prototype._settlePromiseFromHandler = function (
  5571. handler, receiver, value, promise
  5572. ) {
  5573. var bitField = promise._bitField;
  5574. if (((bitField & 65536) !== 0)) return;
  5575. promise._pushContext();
  5576. var x;
  5577. if (receiver === APPLY) {
  5578. if (!value || typeof value.length !== "number") {
  5579. x = errorObj;
  5580. x.e = new TypeError("cannot .spread() a non-array: " +
  5581. util.classString(value));
  5582. } else {
  5583. x = tryCatch(handler).apply(this._boundValue(), value);
  5584. }
  5585. } else {
  5586. x = tryCatch(handler).call(receiver, value);
  5587. }
  5588. var promiseCreated = promise._popContext();
  5589. bitField = promise._bitField;
  5590. if (((bitField & 65536) !== 0)) return;
  5591. if (x === NEXT_FILTER) {
  5592. promise._reject(value);
  5593. } else if (x === errorObj) {
  5594. promise._rejectCallback(x.e, false);
  5595. } else {
  5596. debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
  5597. promise._resolveCallback(x);
  5598. }
  5599. };
  5600. Promise.prototype._target = function() {
  5601. var ret = this;
  5602. while (ret._isFollowing()) ret = ret._followee();
  5603. return ret;
  5604. };
  5605. Promise.prototype._followee = function() {
  5606. return this._rejectionHandler0;
  5607. };
  5608. Promise.prototype._setFollowee = function(promise) {
  5609. this._rejectionHandler0 = promise;
  5610. };
  5611. Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
  5612. var isPromise = promise instanceof Promise;
  5613. var bitField = this._bitField;
  5614. var asyncGuaranteed = ((bitField & 134217728) !== 0);
  5615. if (((bitField & 65536) !== 0)) {
  5616. if (isPromise) promise._invokeInternalOnCancel();
  5617. if (receiver instanceof PassThroughHandlerContext &&
  5618. receiver.isFinallyHandler()) {
  5619. receiver.cancelPromise = promise;
  5620. if (tryCatch(handler).call(receiver, value) === errorObj) {
  5621. promise._reject(errorObj.e);
  5622. }
  5623. } else if (handler === reflectHandler) {
  5624. promise._fulfill(reflectHandler.call(receiver));
  5625. } else if (receiver instanceof Proxyable) {
  5626. receiver._promiseCancelled(promise);
  5627. } else if (isPromise || promise instanceof PromiseArray) {
  5628. promise._cancel();
  5629. } else {
  5630. receiver.cancel();
  5631. }
  5632. } else if (typeof handler === "function") {
  5633. if (!isPromise) {
  5634. handler.call(receiver, value, promise);
  5635. } else {
  5636. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  5637. this._settlePromiseFromHandler(handler, receiver, value, promise);
  5638. }
  5639. } else if (receiver instanceof Proxyable) {
  5640. if (!receiver._isResolved()) {
  5641. if (((bitField & 33554432) !== 0)) {
  5642. receiver._promiseFulfilled(value, promise);
  5643. } else {
  5644. receiver._promiseRejected(value, promise);
  5645. }
  5646. }
  5647. } else if (isPromise) {
  5648. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  5649. if (((bitField & 33554432) !== 0)) {
  5650. promise._fulfill(value);
  5651. } else {
  5652. promise._reject(value);
  5653. }
  5654. }
  5655. };
  5656. Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
  5657. var handler = ctx.handler;
  5658. var promise = ctx.promise;
  5659. var receiver = ctx.receiver;
  5660. var value = ctx.value;
  5661. if (typeof handler === "function") {
  5662. if (!(promise instanceof Promise)) {
  5663. handler.call(receiver, value, promise);
  5664. } else {
  5665. this._settlePromiseFromHandler(handler, receiver, value, promise);
  5666. }
  5667. } else if (promise instanceof Promise) {
  5668. promise._reject(value);
  5669. }
  5670. };
  5671. Promise.prototype._settlePromiseCtx = function(ctx) {
  5672. this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
  5673. };
  5674. Promise.prototype._settlePromise0 = function(handler, value, bitField) {
  5675. var promise = this._promise0;
  5676. var receiver = this._receiverAt(0);
  5677. this._promise0 = undefined;
  5678. this._receiver0 = undefined;
  5679. this._settlePromise(promise, handler, receiver, value);
  5680. };
  5681. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  5682. var base = index * 4 - 4;
  5683. this[base + 2] =
  5684. this[base + 3] =
  5685. this[base + 0] =
  5686. this[base + 1] = undefined;
  5687. };
  5688. Promise.prototype._fulfill = function (value) {
  5689. var bitField = this._bitField;
  5690. if (((bitField & 117506048) >>> 16)) return;
  5691. if (value === this) {
  5692. var err = makeSelfResolutionError();
  5693. this._attachExtraTrace(err);
  5694. return this._reject(err);
  5695. }
  5696. this._setFulfilled();
  5697. this._rejectionHandler0 = value;
  5698. if ((bitField & 65535) > 0) {
  5699. if (((bitField & 134217728) !== 0)) {
  5700. this._settlePromises();
  5701. } else {
  5702. async.settlePromises(this);
  5703. }
  5704. }
  5705. };
  5706. Promise.prototype._reject = function (reason) {
  5707. var bitField = this._bitField;
  5708. if (((bitField & 117506048) >>> 16)) return;
  5709. this._setRejected();
  5710. this._fulfillmentHandler0 = reason;
  5711. if (this._isFinal()) {
  5712. return async.fatalError(reason, util.isNode);
  5713. }
  5714. if ((bitField & 65535) > 0) {
  5715. async.settlePromises(this);
  5716. } else {
  5717. this._ensurePossibleRejectionHandled();
  5718. }
  5719. };
  5720. Promise.prototype._fulfillPromises = function (len, value) {
  5721. for (var i = 1; i < len; i++) {
  5722. var handler = this._fulfillmentHandlerAt(i);
  5723. var promise = this._promiseAt(i);
  5724. var receiver = this._receiverAt(i);
  5725. this._clearCallbackDataAtIndex(i);
  5726. this._settlePromise(promise, handler, receiver, value);
  5727. }
  5728. };
  5729. Promise.prototype._rejectPromises = function (len, reason) {
  5730. for (var i = 1; i < len; i++) {
  5731. var handler = this._rejectionHandlerAt(i);
  5732. var promise = this._promiseAt(i);
  5733. var receiver = this._receiverAt(i);
  5734. this._clearCallbackDataAtIndex(i);
  5735. this._settlePromise(promise, handler, receiver, reason);
  5736. }
  5737. };
  5738. Promise.prototype._settlePromises = function () {
  5739. var bitField = this._bitField;
  5740. var len = (bitField & 65535);
  5741. if (len > 0) {
  5742. if (((bitField & 16842752) !== 0)) {
  5743. var reason = this._fulfillmentHandler0;
  5744. this._settlePromise0(this._rejectionHandler0, reason, bitField);
  5745. this._rejectPromises(len, reason);
  5746. } else {
  5747. var value = this._rejectionHandler0;
  5748. this._settlePromise0(this._fulfillmentHandler0, value, bitField);
  5749. this._fulfillPromises(len, value);
  5750. }
  5751. this._setLength(0);
  5752. }
  5753. this._clearCancellationData();
  5754. };
  5755. Promise.prototype._settledValue = function() {
  5756. var bitField = this._bitField;
  5757. if (((bitField & 33554432) !== 0)) {
  5758. return this._rejectionHandler0;
  5759. } else if (((bitField & 16777216) !== 0)) {
  5760. return this._fulfillmentHandler0;
  5761. }
  5762. };
  5763. function deferResolve(v) {this.promise._resolveCallback(v);}
  5764. function deferReject(v) {this.promise._rejectCallback(v, false);}
  5765. Promise.defer = Promise.pending = function() {
  5766. debug.deprecated("Promise.defer", "new Promise");
  5767. var promise = new Promise(INTERNAL);
  5768. return {
  5769. promise: promise,
  5770. resolve: deferResolve,
  5771. reject: deferReject
  5772. };
  5773. };
  5774. util.notEnumerableProp(Promise,
  5775. "_makeSelfResolutionError",
  5776. makeSelfResolutionError);
  5777. require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
  5778. debug);
  5779. require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
  5780. require("./cancel")(Promise, PromiseArray, apiRejection, debug);
  5781. require("./direct_resolve")(Promise);
  5782. require("./synchronous_inspection")(Promise);
  5783. require("./join")(
  5784. Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
  5785. Promise.Promise = Promise;
  5786. Promise.version = "3.4.0";
  5787. require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  5788. require('./call_get.js')(Promise);
  5789. require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
  5790. require('./timers.js')(Promise, INTERNAL, debug);
  5791. require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
  5792. require('./nodeify.js')(Promise);
  5793. require('./promisify.js')(Promise, INTERNAL);
  5794. require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  5795. require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  5796. require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  5797. require('./settle.js')(Promise, PromiseArray, debug);
  5798. require('./some.js')(Promise, PromiseArray, apiRejection);
  5799. require('./filter.js')(Promise, INTERNAL);
  5800. require('./each.js')(Promise, INTERNAL);
  5801. require('./any.js')(Promise);
  5802. util.toFastProperties(Promise);
  5803. util.toFastProperties(Promise.prototype);
  5804. function fillTypes(value) {
  5805. var p = new Promise(INTERNAL);
  5806. p._fulfillmentHandler0 = value;
  5807. p._rejectionHandler0 = value;
  5808. p._promise0 = value;
  5809. p._receiver0 = value;
  5810. }
  5811. // Complete slack tracking, opt out of field-type tracking and
  5812. // stabilize map
  5813. fillTypes({a: 1});
  5814. fillTypes({b: 2});
  5815. fillTypes({c: 3});
  5816. fillTypes(1);
  5817. fillTypes(function(){});
  5818. fillTypes(undefined);
  5819. fillTypes(false);
  5820. fillTypes(new Promise(INTERNAL));
  5821. debug.setBounds(Async.firstLineError, util.lastLineError);
  5822. return Promise;
  5823. };
  5824. }).call(this,require('_process'))
  5825. },{"./any.js":37,"./async":38,"./bind":39,"./call_get.js":40,"./cancel":41,"./catch_filter":42,"./context":43,"./debuggability":44,"./direct_resolve":45,"./each.js":46,"./errors":47,"./es5":48,"./filter.js":49,"./finally":50,"./generators.js":51,"./join":52,"./map.js":53,"./method":54,"./nodeback":55,"./nodeify.js":56,"./promise_array":58,"./promisify.js":59,"./props.js":60,"./race.js":62,"./reduce.js":63,"./settle.js":65,"./some.js":66,"./synchronous_inspection":67,"./thenables":68,"./timers.js":69,"./using.js":70,"./util":71,"_process":81}],58:[function(require,module,exports){
  5826. "use strict";
  5827. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  5828. apiRejection, Proxyable) {
  5829. var util = require("./util");
  5830. var isArray = util.isArray;
  5831. function toResolutionValue(val) {
  5832. switch(val) {
  5833. case -2: return [];
  5834. case -3: return {};
  5835. }
  5836. }
  5837. function PromiseArray(values) {
  5838. var promise = this._promise = new Promise(INTERNAL);
  5839. if (values instanceof Promise) {
  5840. promise._propagateFrom(values, 3);
  5841. }
  5842. promise._setOnCancel(this);
  5843. this._values = values;
  5844. this._length = 0;
  5845. this._totalResolved = 0;
  5846. this._init(undefined, -2);
  5847. }
  5848. util.inherits(PromiseArray, Proxyable);
  5849. PromiseArray.prototype.length = function () {
  5850. return this._length;
  5851. };
  5852. PromiseArray.prototype.promise = function () {
  5853. return this._promise;
  5854. };
  5855. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  5856. var values = tryConvertToPromise(this._values, this._promise);
  5857. if (values instanceof Promise) {
  5858. values = values._target();
  5859. var bitField = values._bitField;
  5860. ;
  5861. this._values = values;
  5862. if (((bitField & 50397184) === 0)) {
  5863. this._promise._setAsyncGuaranteed();
  5864. return values._then(
  5865. init,
  5866. this._reject,
  5867. undefined,
  5868. this,
  5869. resolveValueIfEmpty
  5870. );
  5871. } else if (((bitField & 33554432) !== 0)) {
  5872. values = values._value();
  5873. } else if (((bitField & 16777216) !== 0)) {
  5874. return this._reject(values._reason());
  5875. } else {
  5876. return this._cancel();
  5877. }
  5878. }
  5879. values = util.asArray(values);
  5880. if (values === null) {
  5881. var err = apiRejection(
  5882. "expecting an array or an iterable object but got " + util.classString(values)).reason();
  5883. this._promise._rejectCallback(err, false);
  5884. return;
  5885. }
  5886. if (values.length === 0) {
  5887. if (resolveValueIfEmpty === -5) {
  5888. this._resolveEmptyArray();
  5889. }
  5890. else {
  5891. this._resolve(toResolutionValue(resolveValueIfEmpty));
  5892. }
  5893. return;
  5894. }
  5895. this._iterate(values);
  5896. };
  5897. PromiseArray.prototype._iterate = function(values) {
  5898. var len = this.getActualLength(values.length);
  5899. this._length = len;
  5900. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  5901. var result = this._promise;
  5902. var isResolved = false;
  5903. var bitField = null;
  5904. for (var i = 0; i < len; ++i) {
  5905. var maybePromise = tryConvertToPromise(values[i], result);
  5906. if (maybePromise instanceof Promise) {
  5907. maybePromise = maybePromise._target();
  5908. bitField = maybePromise._bitField;
  5909. } else {
  5910. bitField = null;
  5911. }
  5912. if (isResolved) {
  5913. if (bitField !== null) {
  5914. maybePromise.suppressUnhandledRejections();
  5915. }
  5916. } else if (bitField !== null) {
  5917. if (((bitField & 50397184) === 0)) {
  5918. maybePromise._proxy(this, i);
  5919. this._values[i] = maybePromise;
  5920. } else if (((bitField & 33554432) !== 0)) {
  5921. isResolved = this._promiseFulfilled(maybePromise._value(), i);
  5922. } else if (((bitField & 16777216) !== 0)) {
  5923. isResolved = this._promiseRejected(maybePromise._reason(), i);
  5924. } else {
  5925. isResolved = this._promiseCancelled(i);
  5926. }
  5927. } else {
  5928. isResolved = this._promiseFulfilled(maybePromise, i);
  5929. }
  5930. }
  5931. if (!isResolved) result._setAsyncGuaranteed();
  5932. };
  5933. PromiseArray.prototype._isResolved = function () {
  5934. return this._values === null;
  5935. };
  5936. PromiseArray.prototype._resolve = function (value) {
  5937. this._values = null;
  5938. this._promise._fulfill(value);
  5939. };
  5940. PromiseArray.prototype._cancel = function() {
  5941. if (this._isResolved() || !this._promise.isCancellable()) return;
  5942. this._values = null;
  5943. this._promise._cancel();
  5944. };
  5945. PromiseArray.prototype._reject = function (reason) {
  5946. this._values = null;
  5947. this._promise._rejectCallback(reason, false);
  5948. };
  5949. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  5950. this._values[index] = value;
  5951. var totalResolved = ++this._totalResolved;
  5952. if (totalResolved >= this._length) {
  5953. this._resolve(this._values);
  5954. return true;
  5955. }
  5956. return false;
  5957. };
  5958. PromiseArray.prototype._promiseCancelled = function() {
  5959. this._cancel();
  5960. return true;
  5961. };
  5962. PromiseArray.prototype._promiseRejected = function (reason) {
  5963. this._totalResolved++;
  5964. this._reject(reason);
  5965. return true;
  5966. };
  5967. PromiseArray.prototype._resultCancelled = function() {
  5968. if (this._isResolved()) return;
  5969. var values = this._values;
  5970. this._cancel();
  5971. if (values instanceof Promise) {
  5972. values.cancel();
  5973. } else {
  5974. for (var i = 0; i < values.length; ++i) {
  5975. if (values[i] instanceof Promise) {
  5976. values[i].cancel();
  5977. }
  5978. }
  5979. }
  5980. };
  5981. PromiseArray.prototype.shouldCopyValues = function () {
  5982. return true;
  5983. };
  5984. PromiseArray.prototype.getActualLength = function (len) {
  5985. return len;
  5986. };
  5987. return PromiseArray;
  5988. };
  5989. },{"./util":71}],59:[function(require,module,exports){
  5990. "use strict";
  5991. module.exports = function(Promise, INTERNAL) {
  5992. var THIS = {};
  5993. var util = require("./util");
  5994. var nodebackForPromise = require("./nodeback");
  5995. var withAppended = util.withAppended;
  5996. var maybeWrapAsError = util.maybeWrapAsError;
  5997. var canEvaluate = util.canEvaluate;
  5998. var TypeError = require("./errors").TypeError;
  5999. var defaultSuffix = "Async";
  6000. var defaultPromisified = {__isPromisified__: true};
  6001. var noCopyProps = [
  6002. "arity", "length",
  6003. "name",
  6004. "arguments",
  6005. "caller",
  6006. "callee",
  6007. "prototype",
  6008. "__isPromisified__"
  6009. ];
  6010. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  6011. var defaultFilter = function(name) {
  6012. return util.isIdentifier(name) &&
  6013. name.charAt(0) !== "_" &&
  6014. name !== "constructor";
  6015. };
  6016. function propsFilter(key) {
  6017. return !noCopyPropsPattern.test(key);
  6018. }
  6019. function isPromisified(fn) {
  6020. try {
  6021. return fn.__isPromisified__ === true;
  6022. }
  6023. catch (e) {
  6024. return false;
  6025. }
  6026. }
  6027. function hasPromisified(obj, key, suffix) {
  6028. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  6029. defaultPromisified);
  6030. return val ? isPromisified(val) : false;
  6031. }
  6032. function checkValid(ret, suffix, suffixRegexp) {
  6033. for (var i = 0; i < ret.length; i += 2) {
  6034. var key = ret[i];
  6035. if (suffixRegexp.test(key)) {
  6036. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  6037. for (var j = 0; j < ret.length; j += 2) {
  6038. if (ret[j] === keyWithoutAsyncSuffix) {
  6039. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
  6040. .replace("%s", suffix));
  6041. }
  6042. }
  6043. }
  6044. }
  6045. }
  6046. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  6047. var keys = util.inheritedDataKeys(obj);
  6048. var ret = [];
  6049. for (var i = 0; i < keys.length; ++i) {
  6050. var key = keys[i];
  6051. var value = obj[key];
  6052. var passesDefaultFilter = filter === defaultFilter
  6053. ? true : defaultFilter(key, value, obj);
  6054. if (typeof value === "function" &&
  6055. !isPromisified(value) &&
  6056. !hasPromisified(obj, key, suffix) &&
  6057. filter(key, value, obj, passesDefaultFilter)) {
  6058. ret.push(key, value);
  6059. }
  6060. }
  6061. checkValid(ret, suffix, suffixRegexp);
  6062. return ret;
  6063. }
  6064. var escapeIdentRegex = function(str) {
  6065. return str.replace(/([$])/, "\\$");
  6066. };
  6067. var makeNodePromisifiedEval;
  6068. if (!false) {
  6069. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  6070. var ret = [likelyArgumentCount];
  6071. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  6072. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  6073. ret.push(i);
  6074. }
  6075. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  6076. ret.push(i);
  6077. }
  6078. return ret;
  6079. };
  6080. var argumentSequence = function(argumentCount) {
  6081. return util.filledRange(argumentCount, "_arg", "");
  6082. };
  6083. var parameterDeclaration = function(parameterCount) {
  6084. return util.filledRange(
  6085. Math.max(parameterCount, 3), "_arg", "");
  6086. };
  6087. var parameterCount = function(fn) {
  6088. if (typeof fn.length === "number") {
  6089. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  6090. }
  6091. return 0;
  6092. };
  6093. makeNodePromisifiedEval =
  6094. function(callback, receiver, originalName, fn, _, multiArgs) {
  6095. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  6096. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  6097. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  6098. function generateCallForArgumentCount(count) {
  6099. var args = argumentSequence(count).join(", ");
  6100. var comma = count > 0 ? ", " : "";
  6101. var ret;
  6102. if (shouldProxyThis) {
  6103. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  6104. } else {
  6105. ret = receiver === undefined
  6106. ? "ret = callback({{args}}, nodeback); break;\n"
  6107. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  6108. }
  6109. return ret.replace("{{args}}", args).replace(", ", comma);
  6110. }
  6111. function generateArgumentSwitchCase() {
  6112. var ret = "";
  6113. for (var i = 0; i < argumentOrder.length; ++i) {
  6114. ret += "case " + argumentOrder[i] +":" +
  6115. generateCallForArgumentCount(argumentOrder[i]);
  6116. }
  6117. ret += " \n\
  6118. default: \n\
  6119. var args = new Array(len + 1); \n\
  6120. var i = 0; \n\
  6121. for (var i = 0; i < len; ++i) { \n\
  6122. args[i] = arguments[i]; \n\
  6123. } \n\
  6124. args[i] = nodeback; \n\
  6125. [CodeForCall] \n\
  6126. break; \n\
  6127. ".replace("[CodeForCall]", (shouldProxyThis
  6128. ? "ret = callback.apply(this, args);\n"
  6129. : "ret = callback.apply(receiver, args);\n"));
  6130. return ret;
  6131. }
  6132. var getFunctionCode = typeof callback === "string"
  6133. ? ("this != null ? this['"+callback+"'] : fn")
  6134. : "fn";
  6135. var body = "'use strict'; \n\
  6136. var ret = function (Parameters) { \n\
  6137. 'use strict'; \n\
  6138. var len = arguments.length; \n\
  6139. var promise = new Promise(INTERNAL); \n\
  6140. promise._captureStackTrace(); \n\
  6141. var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
  6142. var ret; \n\
  6143. var callback = tryCatch([GetFunctionCode]); \n\
  6144. switch(len) { \n\
  6145. [CodeForSwitchCase] \n\
  6146. } \n\
  6147. if (ret === errorObj) { \n\
  6148. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  6149. } \n\
  6150. if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
  6151. return promise; \n\
  6152. }; \n\
  6153. notEnumerableProp(ret, '__isPromisified__', true); \n\
  6154. return ret; \n\
  6155. ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  6156. .replace("[GetFunctionCode]", getFunctionCode);
  6157. body = body.replace("Parameters", parameterDeclaration(newParameterCount));
  6158. return new Function("Promise",
  6159. "fn",
  6160. "receiver",
  6161. "withAppended",
  6162. "maybeWrapAsError",
  6163. "nodebackForPromise",
  6164. "tryCatch",
  6165. "errorObj",
  6166. "notEnumerableProp",
  6167. "INTERNAL",
  6168. body)(
  6169. Promise,
  6170. fn,
  6171. receiver,
  6172. withAppended,
  6173. maybeWrapAsError,
  6174. nodebackForPromise,
  6175. util.tryCatch,
  6176. util.errorObj,
  6177. util.notEnumerableProp,
  6178. INTERNAL);
  6179. };
  6180. }
  6181. function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
  6182. var defaultThis = (function() {return this;})();
  6183. var method = callback;
  6184. if (typeof method === "string") {
  6185. callback = fn;
  6186. }
  6187. function promisified() {
  6188. var _receiver = receiver;
  6189. if (receiver === THIS) _receiver = this;
  6190. var promise = new Promise(INTERNAL);
  6191. promise._captureStackTrace();
  6192. var cb = typeof method === "string" && this !== defaultThis
  6193. ? this[method] : callback;
  6194. var fn = nodebackForPromise(promise, multiArgs);
  6195. try {
  6196. cb.apply(_receiver, withAppended(arguments, fn));
  6197. } catch(e) {
  6198. promise._rejectCallback(maybeWrapAsError(e), true, true);
  6199. }
  6200. if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
  6201. return promise;
  6202. }
  6203. util.notEnumerableProp(promisified, "__isPromisified__", true);
  6204. return promisified;
  6205. }
  6206. var makeNodePromisified = canEvaluate
  6207. ? makeNodePromisifiedEval
  6208. : makeNodePromisifiedClosure;
  6209. function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
  6210. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  6211. var methods =
  6212. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  6213. for (var i = 0, len = methods.length; i < len; i+= 2) {
  6214. var key = methods[i];
  6215. var fn = methods[i+1];
  6216. var promisifiedKey = key + suffix;
  6217. if (promisifier === makeNodePromisified) {
  6218. obj[promisifiedKey] =
  6219. makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
  6220. } else {
  6221. var promisified = promisifier(fn, function() {
  6222. return makeNodePromisified(key, THIS, key,
  6223. fn, suffix, multiArgs);
  6224. });
  6225. util.notEnumerableProp(promisified, "__isPromisified__", true);
  6226. obj[promisifiedKey] = promisified;
  6227. }
  6228. }
  6229. util.toFastProperties(obj);
  6230. return obj;
  6231. }
  6232. function promisify(callback, receiver, multiArgs) {
  6233. return makeNodePromisified(callback, receiver, undefined,
  6234. callback, null, multiArgs);
  6235. }
  6236. Promise.promisify = function (fn, options) {
  6237. if (typeof fn !== "function") {
  6238. throw new TypeError("expecting a function but got " + util.classString(fn));
  6239. }
  6240. if (isPromisified(fn)) {
  6241. return fn;
  6242. }
  6243. options = Object(options);
  6244. var receiver = options.context === undefined ? THIS : options.context;
  6245. var multiArgs = !!options.multiArgs;
  6246. var ret = promisify(fn, receiver, multiArgs);
  6247. util.copyDescriptors(fn, ret, propsFilter);
  6248. return ret;
  6249. };
  6250. Promise.promisifyAll = function (target, options) {
  6251. if (typeof target !== "function" && typeof target !== "object") {
  6252. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6253. }
  6254. options = Object(options);
  6255. var multiArgs = !!options.multiArgs;
  6256. var suffix = options.suffix;
  6257. if (typeof suffix !== "string") suffix = defaultSuffix;
  6258. var filter = options.filter;
  6259. if (typeof filter !== "function") filter = defaultFilter;
  6260. var promisifier = options.promisifier;
  6261. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  6262. if (!util.isIdentifier(suffix)) {
  6263. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6264. }
  6265. var keys = util.inheritedDataKeys(target);
  6266. for (var i = 0; i < keys.length; ++i) {
  6267. var value = target[keys[i]];
  6268. if (keys[i] !== "constructor" &&
  6269. util.isClass(value)) {
  6270. promisifyAll(value.prototype, suffix, filter, promisifier,
  6271. multiArgs);
  6272. promisifyAll(value, suffix, filter, promisifier, multiArgs);
  6273. }
  6274. }
  6275. return promisifyAll(target, suffix, filter, promisifier, multiArgs);
  6276. };
  6277. };
  6278. },{"./errors":47,"./nodeback":55,"./util":71}],60:[function(require,module,exports){
  6279. "use strict";
  6280. module.exports = function(
  6281. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  6282. var util = require("./util");
  6283. var isObject = util.isObject;
  6284. var es5 = require("./es5");
  6285. var Es6Map;
  6286. if (typeof Map === "function") Es6Map = Map;
  6287. var mapToEntries = (function() {
  6288. var index = 0;
  6289. var size = 0;
  6290. function extractEntry(value, key) {
  6291. this[index] = value;
  6292. this[index + size] = key;
  6293. index++;
  6294. }
  6295. return function mapToEntries(map) {
  6296. size = map.size;
  6297. index = 0;
  6298. var ret = new Array(map.size * 2);
  6299. map.forEach(extractEntry, ret);
  6300. return ret;
  6301. };
  6302. })();
  6303. var entriesToMap = function(entries) {
  6304. var ret = new Es6Map();
  6305. var length = entries.length / 2 | 0;
  6306. for (var i = 0; i < length; ++i) {
  6307. var key = entries[length + i];
  6308. var value = entries[i];
  6309. ret.set(key, value);
  6310. }
  6311. return ret;
  6312. };
  6313. function PropertiesPromiseArray(obj) {
  6314. var isMap = false;
  6315. var entries;
  6316. if (Es6Map !== undefined && obj instanceof Es6Map) {
  6317. entries = mapToEntries(obj);
  6318. isMap = true;
  6319. } else {
  6320. var keys = es5.keys(obj);
  6321. var len = keys.length;
  6322. entries = new Array(len * 2);
  6323. for (var i = 0; i < len; ++i) {
  6324. var key = keys[i];
  6325. entries[i] = obj[key];
  6326. entries[i + len] = key;
  6327. }
  6328. }
  6329. this.constructor$(entries);
  6330. this._isMap = isMap;
  6331. this._init$(undefined, -3);
  6332. }
  6333. util.inherits(PropertiesPromiseArray, PromiseArray);
  6334. PropertiesPromiseArray.prototype._init = function () {};
  6335. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  6336. this._values[index] = value;
  6337. var totalResolved = ++this._totalResolved;
  6338. if (totalResolved >= this._length) {
  6339. var val;
  6340. if (this._isMap) {
  6341. val = entriesToMap(this._values);
  6342. } else {
  6343. val = {};
  6344. var keyOffset = this.length();
  6345. for (var i = 0, len = this.length(); i < len; ++i) {
  6346. val[this._values[i + keyOffset]] = this._values[i];
  6347. }
  6348. }
  6349. this._resolve(val);
  6350. return true;
  6351. }
  6352. return false;
  6353. };
  6354. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  6355. return false;
  6356. };
  6357. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  6358. return len >> 1;
  6359. };
  6360. function props(promises) {
  6361. var ret;
  6362. var castValue = tryConvertToPromise(promises);
  6363. if (!isObject(castValue)) {
  6364. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6365. } else if (castValue instanceof Promise) {
  6366. ret = castValue._then(
  6367. Promise.props, undefined, undefined, undefined, undefined);
  6368. } else {
  6369. ret = new PropertiesPromiseArray(castValue).promise();
  6370. }
  6371. if (castValue instanceof Promise) {
  6372. ret._propagateFrom(castValue, 2);
  6373. }
  6374. return ret;
  6375. }
  6376. Promise.prototype.props = function () {
  6377. return props(this);
  6378. };
  6379. Promise.props = function (promises) {
  6380. return props(promises);
  6381. };
  6382. };
  6383. },{"./es5":48,"./util":71}],61:[function(require,module,exports){
  6384. "use strict";
  6385. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  6386. for (var j = 0; j < len; ++j) {
  6387. dst[j + dstIndex] = src[j + srcIndex];
  6388. src[j + srcIndex] = void 0;
  6389. }
  6390. }
  6391. function Queue(capacity) {
  6392. this._capacity = capacity;
  6393. this._length = 0;
  6394. this._front = 0;
  6395. }
  6396. Queue.prototype._willBeOverCapacity = function (size) {
  6397. return this._capacity < size;
  6398. };
  6399. Queue.prototype._pushOne = function (arg) {
  6400. var length = this.length();
  6401. this._checkCapacity(length + 1);
  6402. var i = (this._front + length) & (this._capacity - 1);
  6403. this[i] = arg;
  6404. this._length = length + 1;
  6405. };
  6406. Queue.prototype._unshiftOne = function(value) {
  6407. var capacity = this._capacity;
  6408. this._checkCapacity(this.length() + 1);
  6409. var front = this._front;
  6410. var i = (((( front - 1 ) &
  6411. ( capacity - 1) ) ^ capacity ) - capacity );
  6412. this[i] = value;
  6413. this._front = i;
  6414. this._length = this.length() + 1;
  6415. };
  6416. Queue.prototype.unshift = function(fn, receiver, arg) {
  6417. this._unshiftOne(arg);
  6418. this._unshiftOne(receiver);
  6419. this._unshiftOne(fn);
  6420. };
  6421. Queue.prototype.push = function (fn, receiver, arg) {
  6422. var length = this.length() + 3;
  6423. if (this._willBeOverCapacity(length)) {
  6424. this._pushOne(fn);
  6425. this._pushOne(receiver);
  6426. this._pushOne(arg);
  6427. return;
  6428. }
  6429. var j = this._front + length - 3;
  6430. this._checkCapacity(length);
  6431. var wrapMask = this._capacity - 1;
  6432. this[(j + 0) & wrapMask] = fn;
  6433. this[(j + 1) & wrapMask] = receiver;
  6434. this[(j + 2) & wrapMask] = arg;
  6435. this._length = length;
  6436. };
  6437. Queue.prototype.shift = function () {
  6438. var front = this._front,
  6439. ret = this[front];
  6440. this[front] = undefined;
  6441. this._front = (front + 1) & (this._capacity - 1);
  6442. this._length--;
  6443. return ret;
  6444. };
  6445. Queue.prototype.length = function () {
  6446. return this._length;
  6447. };
  6448. Queue.prototype._checkCapacity = function (size) {
  6449. if (this._capacity < size) {
  6450. this._resizeTo(this._capacity << 1);
  6451. }
  6452. };
  6453. Queue.prototype._resizeTo = function (capacity) {
  6454. var oldCapacity = this._capacity;
  6455. this._capacity = capacity;
  6456. var front = this._front;
  6457. var length = this._length;
  6458. var moveItemsCount = (front + length) & (oldCapacity - 1);
  6459. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  6460. };
  6461. module.exports = Queue;
  6462. },{}],62:[function(require,module,exports){
  6463. "use strict";
  6464. module.exports = function(
  6465. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  6466. var util = require("./util");
  6467. var raceLater = function (promise) {
  6468. return promise.then(function(array) {
  6469. return race(array, promise);
  6470. });
  6471. };
  6472. function race(promises, parent) {
  6473. var maybePromise = tryConvertToPromise(promises);
  6474. if (maybePromise instanceof Promise) {
  6475. return raceLater(maybePromise);
  6476. } else {
  6477. promises = util.asArray(promises);
  6478. if (promises === null)
  6479. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  6480. }
  6481. var ret = new Promise(INTERNAL);
  6482. if (parent !== undefined) {
  6483. ret._propagateFrom(parent, 3);
  6484. }
  6485. var fulfill = ret._fulfill;
  6486. var reject = ret._reject;
  6487. for (var i = 0, len = promises.length; i < len; ++i) {
  6488. var val = promises[i];
  6489. if (val === undefined && !(i in promises)) {
  6490. continue;
  6491. }
  6492. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  6493. }
  6494. return ret;
  6495. }
  6496. Promise.race = function (promises) {
  6497. return race(promises, undefined);
  6498. };
  6499. Promise.prototype.race = function () {
  6500. return race(this, undefined);
  6501. };
  6502. };
  6503. },{"./util":71}],63:[function(require,module,exports){
  6504. "use strict";
  6505. module.exports = function(Promise,
  6506. PromiseArray,
  6507. apiRejection,
  6508. tryConvertToPromise,
  6509. INTERNAL,
  6510. debug) {
  6511. var getDomain = Promise._getDomain;
  6512. var util = require("./util");
  6513. var tryCatch = util.tryCatch;
  6514. function ReductionPromiseArray(promises, fn, initialValue, _each) {
  6515. this.constructor$(promises);
  6516. var domain = getDomain();
  6517. this._fn = domain === null ? fn : domain.bind(fn);
  6518. if (initialValue !== undefined) {
  6519. initialValue = Promise.resolve(initialValue);
  6520. initialValue._attachCancellationCallback(this);
  6521. }
  6522. this._initialValue = initialValue;
  6523. this._currentCancellable = null;
  6524. this._eachValues = _each === INTERNAL ? [] : undefined;
  6525. this._promise._captureStackTrace();
  6526. this._init$(undefined, -5);
  6527. }
  6528. util.inherits(ReductionPromiseArray, PromiseArray);
  6529. ReductionPromiseArray.prototype._gotAccum = function(accum) {
  6530. if (this._eachValues !== undefined && accum !== INTERNAL) {
  6531. this._eachValues.push(accum);
  6532. }
  6533. };
  6534. ReductionPromiseArray.prototype._eachComplete = function(value) {
  6535. this._eachValues.push(value);
  6536. return this._eachValues;
  6537. };
  6538. ReductionPromiseArray.prototype._init = function() {};
  6539. ReductionPromiseArray.prototype._resolveEmptyArray = function() {
  6540. this._resolve(this._eachValues !== undefined ? this._eachValues
  6541. : this._initialValue);
  6542. };
  6543. ReductionPromiseArray.prototype.shouldCopyValues = function () {
  6544. return false;
  6545. };
  6546. ReductionPromiseArray.prototype._resolve = function(value) {
  6547. this._promise._resolveCallback(value);
  6548. this._values = null;
  6549. };
  6550. ReductionPromiseArray.prototype._resultCancelled = function(sender) {
  6551. if (sender === this._initialValue) return this._cancel();
  6552. if (this._isResolved()) return;
  6553. this._resultCancelled$();
  6554. if (this._currentCancellable instanceof Promise) {
  6555. this._currentCancellable.cancel();
  6556. }
  6557. if (this._initialValue instanceof Promise) {
  6558. this._initialValue.cancel();
  6559. }
  6560. };
  6561. ReductionPromiseArray.prototype._iterate = function (values) {
  6562. this._values = values;
  6563. var value;
  6564. var i;
  6565. var length = values.length;
  6566. if (this._initialValue !== undefined) {
  6567. value = this._initialValue;
  6568. i = 0;
  6569. } else {
  6570. value = Promise.resolve(values[0]);
  6571. i = 1;
  6572. }
  6573. this._currentCancellable = value;
  6574. if (!value.isRejected()) {
  6575. for (; i < length; ++i) {
  6576. var ctx = {
  6577. accum: null,
  6578. value: values[i],
  6579. index: i,
  6580. length: length,
  6581. array: this
  6582. };
  6583. value = value._then(gotAccum, undefined, undefined, ctx, undefined);
  6584. }
  6585. }
  6586. if (this._eachValues !== undefined) {
  6587. value = value
  6588. ._then(this._eachComplete, undefined, undefined, this, undefined);
  6589. }
  6590. value._then(completed, completed, undefined, value, this);
  6591. };
  6592. Promise.prototype.reduce = function (fn, initialValue) {
  6593. return reduce(this, fn, initialValue, null);
  6594. };
  6595. Promise.reduce = function (promises, fn, initialValue, _each) {
  6596. return reduce(promises, fn, initialValue, _each);
  6597. };
  6598. function completed(valueOrReason, array) {
  6599. if (this.isFulfilled()) {
  6600. array._resolve(valueOrReason);
  6601. } else {
  6602. array._reject(valueOrReason);
  6603. }
  6604. }
  6605. function reduce(promises, fn, initialValue, _each) {
  6606. if (typeof fn !== "function") {
  6607. return apiRejection("expecting a function but got " + util.classString(fn));
  6608. }
  6609. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  6610. return array.promise();
  6611. }
  6612. function gotAccum(accum) {
  6613. this.accum = accum;
  6614. this.array._gotAccum(accum);
  6615. var value = tryConvertToPromise(this.value, this.array._promise);
  6616. if (value instanceof Promise) {
  6617. this.array._currentCancellable = value;
  6618. return value._then(gotValue, undefined, undefined, this, undefined);
  6619. } else {
  6620. return gotValue.call(this, value);
  6621. }
  6622. }
  6623. function gotValue(value) {
  6624. var array = this.array;
  6625. var promise = array._promise;
  6626. var fn = tryCatch(array._fn);
  6627. promise._pushContext();
  6628. var ret;
  6629. if (array._eachValues !== undefined) {
  6630. ret = fn.call(promise._boundValue(), value, this.index, this.length);
  6631. } else {
  6632. ret = fn.call(promise._boundValue(),
  6633. this.accum, value, this.index, this.length);
  6634. }
  6635. if (ret instanceof Promise) {
  6636. array._currentCancellable = ret;
  6637. }
  6638. var promiseCreated = promise._popContext();
  6639. debug.checkForgottenReturns(
  6640. ret,
  6641. promiseCreated,
  6642. array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
  6643. promise
  6644. );
  6645. return ret;
  6646. }
  6647. };
  6648. },{"./util":71}],64:[function(require,module,exports){
  6649. (function (process,global){
  6650. "use strict";
  6651. var util = require("./util");
  6652. var schedule;
  6653. var noAsyncScheduler = function() {
  6654. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6655. };
  6656. var NativePromise = util.getNativePromise();
  6657. if (util.isNode && typeof MutationObserver === "undefined") {
  6658. var GlobalSetImmediate = global.setImmediate;
  6659. var ProcessNextTick = process.nextTick;
  6660. schedule = util.isRecentNode
  6661. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  6662. : function(fn) { ProcessNextTick.call(process, fn); };
  6663. } else if (typeof NativePromise === "function") {
  6664. var nativePromise = NativePromise.resolve();
  6665. schedule = function(fn) {
  6666. nativePromise.then(fn);
  6667. };
  6668. } else if ((typeof MutationObserver !== "undefined") &&
  6669. !(typeof window !== "undefined" &&
  6670. window.navigator &&
  6671. window.navigator.standalone)) {
  6672. schedule = (function() {
  6673. var div = document.createElement("div");
  6674. var opts = {attributes: true};
  6675. var toggleScheduled = false;
  6676. var div2 = document.createElement("div");
  6677. var o2 = new MutationObserver(function() {
  6678. div.classList.toggle("foo");
  6679. toggleScheduled = false;
  6680. });
  6681. o2.observe(div2, opts);
  6682. var scheduleToggle = function() {
  6683. if (toggleScheduled) return;
  6684. toggleScheduled = true;
  6685. div2.classList.toggle("foo");
  6686. };
  6687. return function schedule(fn) {
  6688. var o = new MutationObserver(function() {
  6689. o.disconnect();
  6690. fn();
  6691. });
  6692. o.observe(div, opts);
  6693. scheduleToggle();
  6694. };
  6695. })();
  6696. } else if (typeof setImmediate !== "undefined") {
  6697. schedule = function (fn) {
  6698. setImmediate(fn);
  6699. };
  6700. } else if (typeof setTimeout !== "undefined") {
  6701. schedule = function (fn) {
  6702. setTimeout(fn, 0);
  6703. };
  6704. } else {
  6705. schedule = noAsyncScheduler;
  6706. }
  6707. module.exports = schedule;
  6708. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  6709. },{"./util":71,"_process":81}],65:[function(require,module,exports){
  6710. "use strict";
  6711. module.exports =
  6712. function(Promise, PromiseArray, debug) {
  6713. var PromiseInspection = Promise.PromiseInspection;
  6714. var util = require("./util");
  6715. function SettledPromiseArray(values) {
  6716. this.constructor$(values);
  6717. }
  6718. util.inherits(SettledPromiseArray, PromiseArray);
  6719. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  6720. this._values[index] = inspection;
  6721. var totalResolved = ++this._totalResolved;
  6722. if (totalResolved >= this._length) {
  6723. this._resolve(this._values);
  6724. return true;
  6725. }
  6726. return false;
  6727. };
  6728. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  6729. var ret = new PromiseInspection();
  6730. ret._bitField = 33554432;
  6731. ret._settledValueField = value;
  6732. return this._promiseResolved(index, ret);
  6733. };
  6734. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  6735. var ret = new PromiseInspection();
  6736. ret._bitField = 16777216;
  6737. ret._settledValueField = reason;
  6738. return this._promiseResolved(index, ret);
  6739. };
  6740. Promise.settle = function (promises) {
  6741. debug.deprecated(".settle()", ".reflect()");
  6742. return new SettledPromiseArray(promises).promise();
  6743. };
  6744. Promise.prototype.settle = function () {
  6745. return Promise.settle(this);
  6746. };
  6747. };
  6748. },{"./util":71}],66:[function(require,module,exports){
  6749. "use strict";
  6750. module.exports =
  6751. function(Promise, PromiseArray, apiRejection) {
  6752. var util = require("./util");
  6753. var RangeError = require("./errors").RangeError;
  6754. var AggregateError = require("./errors").AggregateError;
  6755. var isArray = util.isArray;
  6756. var CANCELLATION = {};
  6757. function SomePromiseArray(values) {
  6758. this.constructor$(values);
  6759. this._howMany = 0;
  6760. this._unwrap = false;
  6761. this._initialized = false;
  6762. }
  6763. util.inherits(SomePromiseArray, PromiseArray);
  6764. SomePromiseArray.prototype._init = function () {
  6765. if (!this._initialized) {
  6766. return;
  6767. }
  6768. if (this._howMany === 0) {
  6769. this._resolve([]);
  6770. return;
  6771. }
  6772. this._init$(undefined, -5);
  6773. var isArrayResolved = isArray(this._values);
  6774. if (!this._isResolved() &&
  6775. isArrayResolved &&
  6776. this._howMany > this._canPossiblyFulfill()) {
  6777. this._reject(this._getRangeError(this.length()));
  6778. }
  6779. };
  6780. SomePromiseArray.prototype.init = function () {
  6781. this._initialized = true;
  6782. this._init();
  6783. };
  6784. SomePromiseArray.prototype.setUnwrap = function () {
  6785. this._unwrap = true;
  6786. };
  6787. SomePromiseArray.prototype.howMany = function () {
  6788. return this._howMany;
  6789. };
  6790. SomePromiseArray.prototype.setHowMany = function (count) {
  6791. this._howMany = count;
  6792. };
  6793. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  6794. this._addFulfilled(value);
  6795. if (this._fulfilled() === this.howMany()) {
  6796. this._values.length = this.howMany();
  6797. if (this.howMany() === 1 && this._unwrap) {
  6798. this._resolve(this._values[0]);
  6799. } else {
  6800. this._resolve(this._values);
  6801. }
  6802. return true;
  6803. }
  6804. return false;
  6805. };
  6806. SomePromiseArray.prototype._promiseRejected = function (reason) {
  6807. this._addRejected(reason);
  6808. return this._checkOutcome();
  6809. };
  6810. SomePromiseArray.prototype._promiseCancelled = function () {
  6811. if (this._values instanceof Promise || this._values == null) {
  6812. return this._cancel();
  6813. }
  6814. this._addRejected(CANCELLATION);
  6815. return this._checkOutcome();
  6816. };
  6817. SomePromiseArray.prototype._checkOutcome = function() {
  6818. if (this.howMany() > this._canPossiblyFulfill()) {
  6819. var e = new AggregateError();
  6820. for (var i = this.length(); i < this._values.length; ++i) {
  6821. if (this._values[i] !== CANCELLATION) {
  6822. e.push(this._values[i]);
  6823. }
  6824. }
  6825. if (e.length > 0) {
  6826. this._reject(e);
  6827. } else {
  6828. this._cancel();
  6829. }
  6830. return true;
  6831. }
  6832. return false;
  6833. };
  6834. SomePromiseArray.prototype._fulfilled = function () {
  6835. return this._totalResolved;
  6836. };
  6837. SomePromiseArray.prototype._rejected = function () {
  6838. return this._values.length - this.length();
  6839. };
  6840. SomePromiseArray.prototype._addRejected = function (reason) {
  6841. this._values.push(reason);
  6842. };
  6843. SomePromiseArray.prototype._addFulfilled = function (value) {
  6844. this._values[this._totalResolved++] = value;
  6845. };
  6846. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  6847. return this.length() - this._rejected();
  6848. };
  6849. SomePromiseArray.prototype._getRangeError = function (count) {
  6850. var message = "Input array must contain at least " +
  6851. this._howMany + " items but contains only " + count + " items";
  6852. return new RangeError(message);
  6853. };
  6854. SomePromiseArray.prototype._resolveEmptyArray = function () {
  6855. this._reject(this._getRangeError(0));
  6856. };
  6857. function some(promises, howMany) {
  6858. if ((howMany | 0) !== howMany || howMany < 0) {
  6859. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6860. }
  6861. var ret = new SomePromiseArray(promises);
  6862. var promise = ret.promise();
  6863. ret.setHowMany(howMany);
  6864. ret.init();
  6865. return promise;
  6866. }
  6867. Promise.some = function (promises, howMany) {
  6868. return some(promises, howMany);
  6869. };
  6870. Promise.prototype.some = function (howMany) {
  6871. return some(this, howMany);
  6872. };
  6873. Promise._SomePromiseArray = SomePromiseArray;
  6874. };
  6875. },{"./errors":47,"./util":71}],67:[function(require,module,exports){
  6876. "use strict";
  6877. module.exports = function(Promise) {
  6878. function PromiseInspection(promise) {
  6879. if (promise !== undefined) {
  6880. promise = promise._target();
  6881. this._bitField = promise._bitField;
  6882. this._settledValueField = promise._isFateSealed()
  6883. ? promise._settledValue() : undefined;
  6884. }
  6885. else {
  6886. this._bitField = 0;
  6887. this._settledValueField = undefined;
  6888. }
  6889. }
  6890. PromiseInspection.prototype._settledValue = function() {
  6891. return this._settledValueField;
  6892. };
  6893. var value = PromiseInspection.prototype.value = function () {
  6894. if (!this.isFulfilled()) {
  6895. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6896. }
  6897. return this._settledValue();
  6898. };
  6899. var reason = PromiseInspection.prototype.error =
  6900. PromiseInspection.prototype.reason = function () {
  6901. if (!this.isRejected()) {
  6902. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6903. }
  6904. return this._settledValue();
  6905. };
  6906. var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
  6907. return (this._bitField & 33554432) !== 0;
  6908. };
  6909. var isRejected = PromiseInspection.prototype.isRejected = function () {
  6910. return (this._bitField & 16777216) !== 0;
  6911. };
  6912. var isPending = PromiseInspection.prototype.isPending = function () {
  6913. return (this._bitField & 50397184) === 0;
  6914. };
  6915. var isResolved = PromiseInspection.prototype.isResolved = function () {
  6916. return (this._bitField & 50331648) !== 0;
  6917. };
  6918. PromiseInspection.prototype.isCancelled =
  6919. Promise.prototype._isCancelled = function() {
  6920. return (this._bitField & 65536) === 65536;
  6921. };
  6922. Promise.prototype.isCancelled = function() {
  6923. return this._target()._isCancelled();
  6924. };
  6925. Promise.prototype.isPending = function() {
  6926. return isPending.call(this._target());
  6927. };
  6928. Promise.prototype.isRejected = function() {
  6929. return isRejected.call(this._target());
  6930. };
  6931. Promise.prototype.isFulfilled = function() {
  6932. return isFulfilled.call(this._target());
  6933. };
  6934. Promise.prototype.isResolved = function() {
  6935. return isResolved.call(this._target());
  6936. };
  6937. Promise.prototype.value = function() {
  6938. return value.call(this._target());
  6939. };
  6940. Promise.prototype.reason = function() {
  6941. var target = this._target();
  6942. target._unsetRejectionIsUnhandled();
  6943. return reason.call(target);
  6944. };
  6945. Promise.prototype._value = function() {
  6946. return this._settledValue();
  6947. };
  6948. Promise.prototype._reason = function() {
  6949. this._unsetRejectionIsUnhandled();
  6950. return this._settledValue();
  6951. };
  6952. Promise.PromiseInspection = PromiseInspection;
  6953. };
  6954. },{}],68:[function(require,module,exports){
  6955. "use strict";
  6956. module.exports = function(Promise, INTERNAL) {
  6957. var util = require("./util");
  6958. var errorObj = util.errorObj;
  6959. var isObject = util.isObject;
  6960. function tryConvertToPromise(obj, context) {
  6961. if (isObject(obj)) {
  6962. if (obj instanceof Promise) return obj;
  6963. var then = getThen(obj);
  6964. if (then === errorObj) {
  6965. if (context) context._pushContext();
  6966. var ret = Promise.reject(then.e);
  6967. if (context) context._popContext();
  6968. return ret;
  6969. } else if (typeof then === "function") {
  6970. if (isAnyBluebirdPromise(obj)) {
  6971. var ret = new Promise(INTERNAL);
  6972. obj._then(
  6973. ret._fulfill,
  6974. ret._reject,
  6975. undefined,
  6976. ret,
  6977. null
  6978. );
  6979. return ret;
  6980. }
  6981. return doThenable(obj, then, context);
  6982. }
  6983. }
  6984. return obj;
  6985. }
  6986. function doGetThen(obj) {
  6987. return obj.then;
  6988. }
  6989. function getThen(obj) {
  6990. try {
  6991. return doGetThen(obj);
  6992. } catch (e) {
  6993. errorObj.e = e;
  6994. return errorObj;
  6995. }
  6996. }
  6997. var hasProp = {}.hasOwnProperty;
  6998. function isAnyBluebirdPromise(obj) {
  6999. try {
  7000. return hasProp.call(obj, "_promise0");
  7001. } catch (e) {
  7002. return false;
  7003. }
  7004. }
  7005. function doThenable(x, then, context) {
  7006. var promise = new Promise(INTERNAL);
  7007. var ret = promise;
  7008. if (context) context._pushContext();
  7009. promise._captureStackTrace();
  7010. if (context) context._popContext();
  7011. var synchronous = true;
  7012. var result = util.tryCatch(then).call(x, resolve, reject);
  7013. synchronous = false;
  7014. if (promise && result === errorObj) {
  7015. promise._rejectCallback(result.e, true, true);
  7016. promise = null;
  7017. }
  7018. function resolve(value) {
  7019. if (!promise) return;
  7020. promise._resolveCallback(value);
  7021. promise = null;
  7022. }
  7023. function reject(reason) {
  7024. if (!promise) return;
  7025. promise._rejectCallback(reason, synchronous, true);
  7026. promise = null;
  7027. }
  7028. return ret;
  7029. }
  7030. return tryConvertToPromise;
  7031. };
  7032. },{"./util":71}],69:[function(require,module,exports){
  7033. "use strict";
  7034. module.exports = function(Promise, INTERNAL, debug) {
  7035. var util = require("./util");
  7036. var TimeoutError = Promise.TimeoutError;
  7037. function HandleWrapper(handle) {
  7038. this.handle = handle;
  7039. }
  7040. HandleWrapper.prototype._resultCancelled = function() {
  7041. clearTimeout(this.handle);
  7042. };
  7043. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  7044. var delay = Promise.delay = function (ms, value) {
  7045. var ret;
  7046. var handle;
  7047. if (value !== undefined) {
  7048. ret = Promise.resolve(value)
  7049. ._then(afterValue, null, null, ms, undefined);
  7050. if (debug.cancellation() && value instanceof Promise) {
  7051. ret._setOnCancel(value);
  7052. }
  7053. } else {
  7054. ret = new Promise(INTERNAL);
  7055. handle = setTimeout(function() { ret._fulfill(); }, +ms);
  7056. if (debug.cancellation()) {
  7057. ret._setOnCancel(new HandleWrapper(handle));
  7058. }
  7059. }
  7060. ret._setAsyncGuaranteed();
  7061. return ret;
  7062. };
  7063. Promise.prototype.delay = function (ms) {
  7064. return delay(ms, this);
  7065. };
  7066. var afterTimeout = function (promise, message, parent) {
  7067. var err;
  7068. if (typeof message !== "string") {
  7069. if (message instanceof Error) {
  7070. err = message;
  7071. } else {
  7072. err = new TimeoutError("operation timed out");
  7073. }
  7074. } else {
  7075. err = new TimeoutError(message);
  7076. }
  7077. util.markAsOriginatingFromRejection(err);
  7078. promise._attachExtraTrace(err);
  7079. promise._reject(err);
  7080. if (parent != null) {
  7081. parent.cancel();
  7082. }
  7083. };
  7084. function successClear(value) {
  7085. clearTimeout(this.handle);
  7086. return value;
  7087. }
  7088. function failureClear(reason) {
  7089. clearTimeout(this.handle);
  7090. throw reason;
  7091. }
  7092. Promise.prototype.timeout = function (ms, message) {
  7093. ms = +ms;
  7094. var ret, parent;
  7095. var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
  7096. if (ret.isPending()) {
  7097. afterTimeout(ret, message, parent);
  7098. }
  7099. }, ms));
  7100. if (debug.cancellation()) {
  7101. parent = this.then();
  7102. ret = parent._then(successClear, failureClear,
  7103. undefined, handleWrapper, undefined);
  7104. ret._setOnCancel(handleWrapper);
  7105. } else {
  7106. ret = this._then(successClear, failureClear,
  7107. undefined, handleWrapper, undefined);
  7108. }
  7109. return ret;
  7110. };
  7111. };
  7112. },{"./util":71}],70:[function(require,module,exports){
  7113. "use strict";
  7114. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  7115. createContext, INTERNAL, debug) {
  7116. var util = require("./util");
  7117. var TypeError = require("./errors").TypeError;
  7118. var inherits = require("./util").inherits;
  7119. var errorObj = util.errorObj;
  7120. var tryCatch = util.tryCatch;
  7121. var NULL = {};
  7122. function thrower(e) {
  7123. setTimeout(function(){throw e;}, 0);
  7124. }
  7125. function castPreservingDisposable(thenable) {
  7126. var maybePromise = tryConvertToPromise(thenable);
  7127. if (maybePromise !== thenable &&
  7128. typeof thenable._isDisposable === "function" &&
  7129. typeof thenable._getDisposer === "function" &&
  7130. thenable._isDisposable()) {
  7131. maybePromise._setDisposable(thenable._getDisposer());
  7132. }
  7133. return maybePromise;
  7134. }
  7135. function dispose(resources, inspection) {
  7136. var i = 0;
  7137. var len = resources.length;
  7138. var ret = new Promise(INTERNAL);
  7139. function iterator() {
  7140. if (i >= len) return ret._fulfill();
  7141. var maybePromise = castPreservingDisposable(resources[i++]);
  7142. if (maybePromise instanceof Promise &&
  7143. maybePromise._isDisposable()) {
  7144. try {
  7145. maybePromise = tryConvertToPromise(
  7146. maybePromise._getDisposer().tryDispose(inspection),
  7147. resources.promise);
  7148. } catch (e) {
  7149. return thrower(e);
  7150. }
  7151. if (maybePromise instanceof Promise) {
  7152. return maybePromise._then(iterator, thrower,
  7153. null, null, null);
  7154. }
  7155. }
  7156. iterator();
  7157. }
  7158. iterator();
  7159. return ret;
  7160. }
  7161. function Disposer(data, promise, context) {
  7162. this._data = data;
  7163. this._promise = promise;
  7164. this._context = context;
  7165. }
  7166. Disposer.prototype.data = function () {
  7167. return this._data;
  7168. };
  7169. Disposer.prototype.promise = function () {
  7170. return this._promise;
  7171. };
  7172. Disposer.prototype.resource = function () {
  7173. if (this.promise().isFulfilled()) {
  7174. return this.promise().value();
  7175. }
  7176. return NULL;
  7177. };
  7178. Disposer.prototype.tryDispose = function(inspection) {
  7179. var resource = this.resource();
  7180. var context = this._context;
  7181. if (context !== undefined) context._pushContext();
  7182. var ret = resource !== NULL
  7183. ? this.doDispose(resource, inspection) : null;
  7184. if (context !== undefined) context._popContext();
  7185. this._promise._unsetDisposable();
  7186. this._data = null;
  7187. return ret;
  7188. };
  7189. Disposer.isDisposer = function (d) {
  7190. return (d != null &&
  7191. typeof d.resource === "function" &&
  7192. typeof d.tryDispose === "function");
  7193. };
  7194. function FunctionDisposer(fn, promise, context) {
  7195. this.constructor$(fn, promise, context);
  7196. }
  7197. inherits(FunctionDisposer, Disposer);
  7198. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  7199. var fn = this.data();
  7200. return fn.call(resource, resource, inspection);
  7201. };
  7202. function maybeUnwrapDisposer(value) {
  7203. if (Disposer.isDisposer(value)) {
  7204. this.resources[this.index]._setDisposable(value);
  7205. return value.promise();
  7206. }
  7207. return value;
  7208. }
  7209. function ResourceList(length) {
  7210. this.length = length;
  7211. this.promise = null;
  7212. this[length-1] = null;
  7213. }
  7214. ResourceList.prototype._resultCancelled = function() {
  7215. var len = this.length;
  7216. for (var i = 0; i < len; ++i) {
  7217. var item = this[i];
  7218. if (item instanceof Promise) {
  7219. item.cancel();
  7220. }
  7221. }
  7222. };
  7223. Promise.using = function () {
  7224. var len = arguments.length;
  7225. if (len < 2) return apiRejection(
  7226. "you must pass at least 2 arguments to Promise.using");
  7227. var fn = arguments[len - 1];
  7228. if (typeof fn !== "function") {
  7229. return apiRejection("expecting a function but got " + util.classString(fn));
  7230. }
  7231. var input;
  7232. var spreadArgs = true;
  7233. if (len === 2 && Array.isArray(arguments[0])) {
  7234. input = arguments[0];
  7235. len = input.length;
  7236. spreadArgs = false;
  7237. } else {
  7238. input = arguments;
  7239. len--;
  7240. }
  7241. var resources = new ResourceList(len);
  7242. for (var i = 0; i < len; ++i) {
  7243. var resource = input[i];
  7244. if (Disposer.isDisposer(resource)) {
  7245. var disposer = resource;
  7246. resource = resource.promise();
  7247. resource._setDisposable(disposer);
  7248. } else {
  7249. var maybePromise = tryConvertToPromise(resource);
  7250. if (maybePromise instanceof Promise) {
  7251. resource =
  7252. maybePromise._then(maybeUnwrapDisposer, null, null, {
  7253. resources: resources,
  7254. index: i
  7255. }, undefined);
  7256. }
  7257. }
  7258. resources[i] = resource;
  7259. }
  7260. var reflectedResources = new Array(resources.length);
  7261. for (var i = 0; i < reflectedResources.length; ++i) {
  7262. reflectedResources[i] = Promise.resolve(resources[i]).reflect();
  7263. }
  7264. var resultPromise = Promise.all(reflectedResources)
  7265. .then(function(inspections) {
  7266. for (var i = 0; i < inspections.length; ++i) {
  7267. var inspection = inspections[i];
  7268. if (inspection.isRejected()) {
  7269. errorObj.e = inspection.error();
  7270. return errorObj;
  7271. } else if (!inspection.isFulfilled()) {
  7272. resultPromise.cancel();
  7273. return;
  7274. }
  7275. inspections[i] = inspection.value();
  7276. }
  7277. promise._pushContext();
  7278. fn = tryCatch(fn);
  7279. var ret = spreadArgs
  7280. ? fn.apply(undefined, inspections) : fn(inspections);
  7281. var promiseCreated = promise._popContext();
  7282. debug.checkForgottenReturns(
  7283. ret, promiseCreated, "Promise.using", promise);
  7284. return ret;
  7285. });
  7286. var promise = resultPromise.lastly(function() {
  7287. var inspection = new Promise.PromiseInspection(resultPromise);
  7288. return dispose(resources, inspection);
  7289. });
  7290. resources.promise = promise;
  7291. promise._setOnCancel(resources);
  7292. return promise;
  7293. };
  7294. Promise.prototype._setDisposable = function (disposer) {
  7295. this._bitField = this._bitField | 131072;
  7296. this._disposer = disposer;
  7297. };
  7298. Promise.prototype._isDisposable = function () {
  7299. return (this._bitField & 131072) > 0;
  7300. };
  7301. Promise.prototype._getDisposer = function () {
  7302. return this._disposer;
  7303. };
  7304. Promise.prototype._unsetDisposable = function () {
  7305. this._bitField = this._bitField & (~131072);
  7306. this._disposer = undefined;
  7307. };
  7308. Promise.prototype.disposer = function (fn) {
  7309. if (typeof fn === "function") {
  7310. return new FunctionDisposer(fn, this, createContext());
  7311. }
  7312. throw new TypeError();
  7313. };
  7314. };
  7315. },{"./errors":47,"./util":71}],71:[function(require,module,exports){
  7316. (function (process,global){
  7317. "use strict";
  7318. var es5 = require("./es5");
  7319. var canEvaluate = typeof navigator == "undefined";
  7320. var errorObj = {e: {}};
  7321. var tryCatchTarget;
  7322. var globalObject = typeof self !== "undefined" ? self :
  7323. typeof window !== "undefined" ? window :
  7324. typeof global !== "undefined" ? global :
  7325. this !== undefined ? this : null;
  7326. function tryCatcher() {
  7327. try {
  7328. var target = tryCatchTarget;
  7329. tryCatchTarget = null;
  7330. return target.apply(this, arguments);
  7331. } catch (e) {
  7332. errorObj.e = e;
  7333. return errorObj;
  7334. }
  7335. }
  7336. function tryCatch(fn) {
  7337. tryCatchTarget = fn;
  7338. return tryCatcher;
  7339. }
  7340. var inherits = function(Child, Parent) {
  7341. var hasProp = {}.hasOwnProperty;
  7342. function T() {
  7343. this.constructor = Child;
  7344. this.constructor$ = Parent;
  7345. for (var propertyName in Parent.prototype) {
  7346. if (hasProp.call(Parent.prototype, propertyName) &&
  7347. propertyName.charAt(propertyName.length-1) !== "$"
  7348. ) {
  7349. this[propertyName + "$"] = Parent.prototype[propertyName];
  7350. }
  7351. }
  7352. }
  7353. T.prototype = Parent.prototype;
  7354. Child.prototype = new T();
  7355. return Child.prototype;
  7356. };
  7357. function isPrimitive(val) {
  7358. return val == null || val === true || val === false ||
  7359. typeof val === "string" || typeof val === "number";
  7360. }
  7361. function isObject(value) {
  7362. return typeof value === "function" ||
  7363. typeof value === "object" && value !== null;
  7364. }
  7365. function maybeWrapAsError(maybeError) {
  7366. if (!isPrimitive(maybeError)) return maybeError;
  7367. return new Error(safeToString(maybeError));
  7368. }
  7369. function withAppended(target, appendee) {
  7370. var len = target.length;
  7371. var ret = new Array(len + 1);
  7372. var i;
  7373. for (i = 0; i < len; ++i) {
  7374. ret[i] = target[i];
  7375. }
  7376. ret[i] = appendee;
  7377. return ret;
  7378. }
  7379. function getDataPropertyOrDefault(obj, key, defaultValue) {
  7380. if (es5.isES5) {
  7381. var desc = Object.getOwnPropertyDescriptor(obj, key);
  7382. if (desc != null) {
  7383. return desc.get == null && desc.set == null
  7384. ? desc.value
  7385. : defaultValue;
  7386. }
  7387. } else {
  7388. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  7389. }
  7390. }
  7391. function notEnumerableProp(obj, name, value) {
  7392. if (isPrimitive(obj)) return obj;
  7393. var descriptor = {
  7394. value: value,
  7395. configurable: true,
  7396. enumerable: false,
  7397. writable: true
  7398. };
  7399. es5.defineProperty(obj, name, descriptor);
  7400. return obj;
  7401. }
  7402. function thrower(r) {
  7403. throw r;
  7404. }
  7405. var inheritedDataKeys = (function() {
  7406. var excludedPrototypes = [
  7407. Array.prototype,
  7408. Object.prototype,
  7409. Function.prototype
  7410. ];
  7411. var isExcludedProto = function(val) {
  7412. for (var i = 0; i < excludedPrototypes.length; ++i) {
  7413. if (excludedPrototypes[i] === val) {
  7414. return true;
  7415. }
  7416. }
  7417. return false;
  7418. };
  7419. if (es5.isES5) {
  7420. var getKeys = Object.getOwnPropertyNames;
  7421. return function(obj) {
  7422. var ret = [];
  7423. var visitedKeys = Object.create(null);
  7424. while (obj != null && !isExcludedProto(obj)) {
  7425. var keys;
  7426. try {
  7427. keys = getKeys(obj);
  7428. } catch (e) {
  7429. return ret;
  7430. }
  7431. for (var i = 0; i < keys.length; ++i) {
  7432. var key = keys[i];
  7433. if (visitedKeys[key]) continue;
  7434. visitedKeys[key] = true;
  7435. var desc = Object.getOwnPropertyDescriptor(obj, key);
  7436. if (desc != null && desc.get == null && desc.set == null) {
  7437. ret.push(key);
  7438. }
  7439. }
  7440. obj = es5.getPrototypeOf(obj);
  7441. }
  7442. return ret;
  7443. };
  7444. } else {
  7445. var hasProp = {}.hasOwnProperty;
  7446. return function(obj) {
  7447. if (isExcludedProto(obj)) return [];
  7448. var ret = [];
  7449. /*jshint forin:false */
  7450. enumeration: for (var key in obj) {
  7451. if (hasProp.call(obj, key)) {
  7452. ret.push(key);
  7453. } else {
  7454. for (var i = 0; i < excludedPrototypes.length; ++i) {
  7455. if (hasProp.call(excludedPrototypes[i], key)) {
  7456. continue enumeration;
  7457. }
  7458. }
  7459. ret.push(key);
  7460. }
  7461. }
  7462. return ret;
  7463. };
  7464. }
  7465. })();
  7466. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  7467. function isClass(fn) {
  7468. try {
  7469. if (typeof fn === "function") {
  7470. var keys = es5.names(fn.prototype);
  7471. var hasMethods = es5.isES5 && keys.length > 1;
  7472. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  7473. !(keys.length === 1 && keys[0] === "constructor");
  7474. var hasThisAssignmentAndStaticMethods =
  7475. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  7476. if (hasMethods || hasMethodsOtherThanConstructor ||
  7477. hasThisAssignmentAndStaticMethods) {
  7478. return true;
  7479. }
  7480. }
  7481. return false;
  7482. } catch (e) {
  7483. return false;
  7484. }
  7485. }
  7486. function toFastProperties(obj) {
  7487. /*jshint -W027,-W055,-W031*/
  7488. function FakeConstructor() {}
  7489. FakeConstructor.prototype = obj;
  7490. var l = 8;
  7491. while (l--) new FakeConstructor();
  7492. return obj;
  7493. eval(obj);
  7494. }
  7495. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  7496. function isIdentifier(str) {
  7497. return rident.test(str);
  7498. }
  7499. function filledRange(count, prefix, suffix) {
  7500. var ret = new Array(count);
  7501. for(var i = 0; i < count; ++i) {
  7502. ret[i] = prefix + i + suffix;
  7503. }
  7504. return ret;
  7505. }
  7506. function safeToString(obj) {
  7507. try {
  7508. return obj + "";
  7509. } catch (e) {
  7510. return "[no string representation]";
  7511. }
  7512. }
  7513. function isError(obj) {
  7514. return obj !== null &&
  7515. typeof obj === "object" &&
  7516. typeof obj.message === "string" &&
  7517. typeof obj.name === "string";
  7518. }
  7519. function markAsOriginatingFromRejection(e) {
  7520. try {
  7521. notEnumerableProp(e, "isOperational", true);
  7522. }
  7523. catch(ignore) {}
  7524. }
  7525. function originatesFromRejection(e) {
  7526. if (e == null) return false;
  7527. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  7528. e["isOperational"] === true);
  7529. }
  7530. function canAttachTrace(obj) {
  7531. return isError(obj) && es5.propertyIsWritable(obj, "stack");
  7532. }
  7533. var ensureErrorObject = (function() {
  7534. if (!("stack" in new Error())) {
  7535. return function(value) {
  7536. if (canAttachTrace(value)) return value;
  7537. try {throw new Error(safeToString(value));}
  7538. catch(err) {return err;}
  7539. };
  7540. } else {
  7541. return function(value) {
  7542. if (canAttachTrace(value)) return value;
  7543. return new Error(safeToString(value));
  7544. };
  7545. }
  7546. })();
  7547. function classString(obj) {
  7548. return {}.toString.call(obj);
  7549. }
  7550. function copyDescriptors(from, to, filter) {
  7551. var keys = es5.names(from);
  7552. for (var i = 0; i < keys.length; ++i) {
  7553. var key = keys[i];
  7554. if (filter(key)) {
  7555. try {
  7556. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  7557. } catch (ignore) {}
  7558. }
  7559. }
  7560. }
  7561. var asArray = function(v) {
  7562. if (es5.isArray(v)) {
  7563. return v;
  7564. }
  7565. return null;
  7566. };
  7567. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  7568. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  7569. return Array.from(v);
  7570. } : function(v) {
  7571. var ret = [];
  7572. var it = v[Symbol.iterator]();
  7573. var itResult;
  7574. while (!((itResult = it.next()).done)) {
  7575. ret.push(itResult.value);
  7576. }
  7577. return ret;
  7578. };
  7579. asArray = function(v) {
  7580. if (es5.isArray(v)) {
  7581. return v;
  7582. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  7583. return ArrayFrom(v);
  7584. }
  7585. return null;
  7586. };
  7587. }
  7588. var isNode = typeof process !== "undefined" &&
  7589. classString(process).toLowerCase() === "[object process]";
  7590. function env(key, def) {
  7591. return isNode ? process.env[key] : def;
  7592. }
  7593. function getNativePromise() {
  7594. if (typeof Promise === "function") {
  7595. try {
  7596. var promise = new Promise(function(){});
  7597. if ({}.toString.call(promise) === "[object Promise]") {
  7598. return Promise;
  7599. }
  7600. } catch (e) {}
  7601. }
  7602. }
  7603. var ret = {
  7604. isClass: isClass,
  7605. isIdentifier: isIdentifier,
  7606. inheritedDataKeys: inheritedDataKeys,
  7607. getDataPropertyOrDefault: getDataPropertyOrDefault,
  7608. thrower: thrower,
  7609. isArray: es5.isArray,
  7610. asArray: asArray,
  7611. notEnumerableProp: notEnumerableProp,
  7612. isPrimitive: isPrimitive,
  7613. isObject: isObject,
  7614. isError: isError,
  7615. canEvaluate: canEvaluate,
  7616. errorObj: errorObj,
  7617. tryCatch: tryCatch,
  7618. inherits: inherits,
  7619. withAppended: withAppended,
  7620. maybeWrapAsError: maybeWrapAsError,
  7621. toFastProperties: toFastProperties,
  7622. filledRange: filledRange,
  7623. toString: safeToString,
  7624. canAttachTrace: canAttachTrace,
  7625. ensureErrorObject: ensureErrorObject,
  7626. originatesFromRejection: originatesFromRejection,
  7627. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  7628. classString: classString,
  7629. copyDescriptors: copyDescriptors,
  7630. hasDevTools: typeof chrome !== "undefined" && chrome &&
  7631. typeof chrome.loadTimes === "function",
  7632. isNode: isNode,
  7633. env: env,
  7634. global: globalObject,
  7635. getNativePromise: getNativePromise
  7636. };
  7637. ret.isRecentNode = ret.isNode && (function() {
  7638. var version = process.versions.node.split(".").map(Number);
  7639. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  7640. })();
  7641. if (ret.isNode) ret.toFastProperties(process);
  7642. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  7643. module.exports = ret;
  7644. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7645. },{"./es5":48,"_process":81}],72:[function(require,module,exports){
  7646. },{}],73:[function(require,module,exports){
  7647. (function (global){
  7648. /*!
  7649. * The buffer module from node.js, for the browser.
  7650. *
  7651. * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
  7652. * @license MIT
  7653. */
  7654. /* eslint-disable no-proto */
  7655. 'use strict'
  7656. var base64 = require('base64-js')
  7657. var ieee754 = require('ieee754')
  7658. var isArray = require('isarray')
  7659. exports.Buffer = Buffer
  7660. exports.SlowBuffer = SlowBuffer
  7661. exports.INSPECT_MAX_BYTES = 50
  7662. /**
  7663. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  7664. * === true Use Uint8Array implementation (fastest)
  7665. * === false Use Object implementation (most compatible, even IE6)
  7666. *
  7667. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  7668. * Opera 11.6+, iOS 4.2+.
  7669. *
  7670. * Due to various browser bugs, sometimes the Object implementation will be used even
  7671. * when the browser supports typed arrays.
  7672. *
  7673. * Note:
  7674. *
  7675. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  7676. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  7677. *
  7678. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  7679. *
  7680. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  7681. * incorrect length in some situations.
  7682. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  7683. * get the Object implementation, which is slower but behaves correctly.
  7684. */
  7685. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  7686. ? global.TYPED_ARRAY_SUPPORT
  7687. : typedArraySupport()
  7688. /*
  7689. * Export kMaxLength after typed array support is determined.
  7690. */
  7691. exports.kMaxLength = kMaxLength()
  7692. function typedArraySupport () {
  7693. try {
  7694. var arr = new Uint8Array(1)
  7695. arr.foo = function () { return 42 }
  7696. return arr.foo() === 42 && // typed array instances can be augmented
  7697. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  7698. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  7699. } catch (e) {
  7700. return false
  7701. }
  7702. }
  7703. function kMaxLength () {
  7704. return Buffer.TYPED_ARRAY_SUPPORT
  7705. ? 0x7fffffff
  7706. : 0x3fffffff
  7707. }
  7708. function createBuffer (that, length) {
  7709. if (kMaxLength() < length) {
  7710. throw new RangeError('Invalid typed array length')
  7711. }
  7712. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7713. // Return an augmented `Uint8Array` instance, for best performance
  7714. that = new Uint8Array(length)
  7715. that.__proto__ = Buffer.prototype
  7716. } else {
  7717. // Fallback: Return an object instance of the Buffer class
  7718. if (that === null) {
  7719. that = new Buffer(length)
  7720. }
  7721. that.length = length
  7722. }
  7723. return that
  7724. }
  7725. /**
  7726. * The Buffer constructor returns instances of `Uint8Array` that have their
  7727. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  7728. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  7729. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  7730. * returns a single octet.
  7731. *
  7732. * The `Uint8Array` prototype remains unmodified.
  7733. */
  7734. function Buffer (arg, encodingOrOffset, length) {
  7735. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  7736. return new Buffer(arg, encodingOrOffset, length)
  7737. }
  7738. // Common case.
  7739. if (typeof arg === 'number') {
  7740. if (typeof encodingOrOffset === 'string') {
  7741. throw new Error(
  7742. 'If encoding is specified then the first argument must be a string'
  7743. )
  7744. }
  7745. return allocUnsafe(this, arg)
  7746. }
  7747. return from(this, arg, encodingOrOffset, length)
  7748. }
  7749. Buffer.poolSize = 8192 // not used by this implementation
  7750. // TODO: Legacy, not needed anymore. Remove in next major version.
  7751. Buffer._augment = function (arr) {
  7752. arr.__proto__ = Buffer.prototype
  7753. return arr
  7754. }
  7755. function from (that, value, encodingOrOffset, length) {
  7756. if (typeof value === 'number') {
  7757. throw new TypeError('"value" argument must not be a number')
  7758. }
  7759. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  7760. return fromArrayBuffer(that, value, encodingOrOffset, length)
  7761. }
  7762. if (typeof value === 'string') {
  7763. return fromString(that, value, encodingOrOffset)
  7764. }
  7765. return fromObject(that, value)
  7766. }
  7767. /**
  7768. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  7769. * if value is a number.
  7770. * Buffer.from(str[, encoding])
  7771. * Buffer.from(array)
  7772. * Buffer.from(buffer)
  7773. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  7774. **/
  7775. Buffer.from = function (value, encodingOrOffset, length) {
  7776. return from(null, value, encodingOrOffset, length)
  7777. }
  7778. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7779. Buffer.prototype.__proto__ = Uint8Array.prototype
  7780. Buffer.__proto__ = Uint8Array
  7781. if (typeof Symbol !== 'undefined' && Symbol.species &&
  7782. Buffer[Symbol.species] === Buffer) {
  7783. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  7784. Object.defineProperty(Buffer, Symbol.species, {
  7785. value: null,
  7786. configurable: true
  7787. })
  7788. }
  7789. }
  7790. function assertSize (size) {
  7791. if (typeof size !== 'number') {
  7792. throw new TypeError('"size" argument must be a number')
  7793. }
  7794. }
  7795. function alloc (that, size, fill, encoding) {
  7796. assertSize(size)
  7797. if (size <= 0) {
  7798. return createBuffer(that, size)
  7799. }
  7800. if (fill !== undefined) {
  7801. // Only pay attention to encoding if it's a string. This
  7802. // prevents accidentally sending in a number that would
  7803. // be interpretted as a start offset.
  7804. return typeof encoding === 'string'
  7805. ? createBuffer(that, size).fill(fill, encoding)
  7806. : createBuffer(that, size).fill(fill)
  7807. }
  7808. return createBuffer(that, size)
  7809. }
  7810. /**
  7811. * Creates a new filled Buffer instance.
  7812. * alloc(size[, fill[, encoding]])
  7813. **/
  7814. Buffer.alloc = function (size, fill, encoding) {
  7815. return alloc(null, size, fill, encoding)
  7816. }
  7817. function allocUnsafe (that, size) {
  7818. assertSize(size)
  7819. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  7820. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  7821. for (var i = 0; i < size; i++) {
  7822. that[i] = 0
  7823. }
  7824. }
  7825. return that
  7826. }
  7827. /**
  7828. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  7829. * */
  7830. Buffer.allocUnsafe = function (size) {
  7831. return allocUnsafe(null, size)
  7832. }
  7833. /**
  7834. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  7835. */
  7836. Buffer.allocUnsafeSlow = function (size) {
  7837. return allocUnsafe(null, size)
  7838. }
  7839. function fromString (that, string, encoding) {
  7840. if (typeof encoding !== 'string' || encoding === '') {
  7841. encoding = 'utf8'
  7842. }
  7843. if (!Buffer.isEncoding(encoding)) {
  7844. throw new TypeError('"encoding" must be a valid string encoding')
  7845. }
  7846. var length = byteLength(string, encoding) | 0
  7847. that = createBuffer(that, length)
  7848. that.write(string, encoding)
  7849. return that
  7850. }
  7851. function fromArrayLike (that, array) {
  7852. var length = checked(array.length) | 0
  7853. that = createBuffer(that, length)
  7854. for (var i = 0; i < length; i += 1) {
  7855. that[i] = array[i] & 255
  7856. }
  7857. return that
  7858. }
  7859. function fromArrayBuffer (that, array, byteOffset, length) {
  7860. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  7861. if (byteOffset < 0 || array.byteLength < byteOffset) {
  7862. throw new RangeError('\'offset\' is out of bounds')
  7863. }
  7864. if (array.byteLength < byteOffset + (length || 0)) {
  7865. throw new RangeError('\'length\' is out of bounds')
  7866. }
  7867. if (length === undefined) {
  7868. array = new Uint8Array(array, byteOffset)
  7869. } else {
  7870. array = new Uint8Array(array, byteOffset, length)
  7871. }
  7872. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7873. // Return an augmented `Uint8Array` instance, for best performance
  7874. that = array
  7875. that.__proto__ = Buffer.prototype
  7876. } else {
  7877. // Fallback: Return an object instance of the Buffer class
  7878. that = fromArrayLike(that, array)
  7879. }
  7880. return that
  7881. }
  7882. function fromObject (that, obj) {
  7883. if (Buffer.isBuffer(obj)) {
  7884. var len = checked(obj.length) | 0
  7885. that = createBuffer(that, len)
  7886. if (that.length === 0) {
  7887. return that
  7888. }
  7889. obj.copy(that, 0, 0, len)
  7890. return that
  7891. }
  7892. if (obj) {
  7893. if ((typeof ArrayBuffer !== 'undefined' &&
  7894. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  7895. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  7896. return createBuffer(that, 0)
  7897. }
  7898. return fromArrayLike(that, obj)
  7899. }
  7900. if (obj.type === 'Buffer' && isArray(obj.data)) {
  7901. return fromArrayLike(that, obj.data)
  7902. }
  7903. }
  7904. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  7905. }
  7906. function checked (length) {
  7907. // Note: cannot use `length < kMaxLength` here because that fails when
  7908. // length is NaN (which is otherwise coerced to zero.)
  7909. if (length >= kMaxLength()) {
  7910. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  7911. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  7912. }
  7913. return length | 0
  7914. }
  7915. function SlowBuffer (length) {
  7916. if (+length != length) { // eslint-disable-line eqeqeq
  7917. length = 0
  7918. }
  7919. return Buffer.alloc(+length)
  7920. }
  7921. Buffer.isBuffer = function isBuffer (b) {
  7922. return !!(b != null && b._isBuffer)
  7923. }
  7924. Buffer.compare = function compare (a, b) {
  7925. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  7926. throw new TypeError('Arguments must be Buffers')
  7927. }
  7928. if (a === b) return 0
  7929. var x = a.length
  7930. var y = b.length
  7931. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  7932. if (a[i] !== b[i]) {
  7933. x = a[i]
  7934. y = b[i]
  7935. break
  7936. }
  7937. }
  7938. if (x < y) return -1
  7939. if (y < x) return 1
  7940. return 0
  7941. }
  7942. Buffer.isEncoding = function isEncoding (encoding) {
  7943. switch (String(encoding).toLowerCase()) {
  7944. case 'hex':
  7945. case 'utf8':
  7946. case 'utf-8':
  7947. case 'ascii':
  7948. case 'binary':
  7949. case 'base64':
  7950. case 'raw':
  7951. case 'ucs2':
  7952. case 'ucs-2':
  7953. case 'utf16le':
  7954. case 'utf-16le':
  7955. return true
  7956. default:
  7957. return false
  7958. }
  7959. }
  7960. Buffer.concat = function concat (list, length) {
  7961. if (!isArray(list)) {
  7962. throw new TypeError('"list" argument must be an Array of Buffers')
  7963. }
  7964. if (list.length === 0) {
  7965. return Buffer.alloc(0)
  7966. }
  7967. var i
  7968. if (length === undefined) {
  7969. length = 0
  7970. for (i = 0; i < list.length; i++) {
  7971. length += list[i].length
  7972. }
  7973. }
  7974. var buffer = Buffer.allocUnsafe(length)
  7975. var pos = 0
  7976. for (i = 0; i < list.length; i++) {
  7977. var buf = list[i]
  7978. if (!Buffer.isBuffer(buf)) {
  7979. throw new TypeError('"list" argument must be an Array of Buffers')
  7980. }
  7981. buf.copy(buffer, pos)
  7982. pos += buf.length
  7983. }
  7984. return buffer
  7985. }
  7986. function byteLength (string, encoding) {
  7987. if (Buffer.isBuffer(string)) {
  7988. return string.length
  7989. }
  7990. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  7991. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  7992. return string.byteLength
  7993. }
  7994. if (typeof string !== 'string') {
  7995. string = '' + string
  7996. }
  7997. var len = string.length
  7998. if (len === 0) return 0
  7999. // Use a for loop to avoid recursion
  8000. var loweredCase = false
  8001. for (;;) {
  8002. switch (encoding) {
  8003. case 'ascii':
  8004. case 'binary':
  8005. // Deprecated
  8006. case 'raw':
  8007. case 'raws':
  8008. return len
  8009. case 'utf8':
  8010. case 'utf-8':
  8011. case undefined:
  8012. return utf8ToBytes(string).length
  8013. case 'ucs2':
  8014. case 'ucs-2':
  8015. case 'utf16le':
  8016. case 'utf-16le':
  8017. return len * 2
  8018. case 'hex':
  8019. return len >>> 1
  8020. case 'base64':
  8021. return base64ToBytes(string).length
  8022. default:
  8023. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  8024. encoding = ('' + encoding).toLowerCase()
  8025. loweredCase = true
  8026. }
  8027. }
  8028. }
  8029. Buffer.byteLength = byteLength
  8030. function slowToString (encoding, start, end) {
  8031. var loweredCase = false
  8032. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  8033. // property of a typed array.
  8034. // This behaves neither like String nor Uint8Array in that we set start/end
  8035. // to their upper/lower bounds if the value passed is out of range.
  8036. // undefined is handled specially as per ECMA-262 6th Edition,
  8037. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  8038. if (start === undefined || start < 0) {
  8039. start = 0
  8040. }
  8041. // Return early if start > this.length. Done here to prevent potential uint32
  8042. // coercion fail below.
  8043. if (start > this.length) {
  8044. return ''
  8045. }
  8046. if (end === undefined || end > this.length) {
  8047. end = this.length
  8048. }
  8049. if (end <= 0) {
  8050. return ''
  8051. }
  8052. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  8053. end >>>= 0
  8054. start >>>= 0
  8055. if (end <= start) {
  8056. return ''
  8057. }
  8058. if (!encoding) encoding = 'utf8'
  8059. while (true) {
  8060. switch (encoding) {
  8061. case 'hex':
  8062. return hexSlice(this, start, end)
  8063. case 'utf8':
  8064. case 'utf-8':
  8065. return utf8Slice(this, start, end)
  8066. case 'ascii':
  8067. return asciiSlice(this, start, end)
  8068. case 'binary':
  8069. return binarySlice(this, start, end)
  8070. case 'base64':
  8071. return base64Slice(this, start, end)
  8072. case 'ucs2':
  8073. case 'ucs-2':
  8074. case 'utf16le':
  8075. case 'utf-16le':
  8076. return utf16leSlice(this, start, end)
  8077. default:
  8078. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8079. encoding = (encoding + '').toLowerCase()
  8080. loweredCase = true
  8081. }
  8082. }
  8083. }
  8084. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  8085. // Buffer instances.
  8086. Buffer.prototype._isBuffer = true
  8087. function swap (b, n, m) {
  8088. var i = b[n]
  8089. b[n] = b[m]
  8090. b[m] = i
  8091. }
  8092. Buffer.prototype.swap16 = function swap16 () {
  8093. var len = this.length
  8094. if (len % 2 !== 0) {
  8095. throw new RangeError('Buffer size must be a multiple of 16-bits')
  8096. }
  8097. for (var i = 0; i < len; i += 2) {
  8098. swap(this, i, i + 1)
  8099. }
  8100. return this
  8101. }
  8102. Buffer.prototype.swap32 = function swap32 () {
  8103. var len = this.length
  8104. if (len % 4 !== 0) {
  8105. throw new RangeError('Buffer size must be a multiple of 32-bits')
  8106. }
  8107. for (var i = 0; i < len; i += 4) {
  8108. swap(this, i, i + 3)
  8109. swap(this, i + 1, i + 2)
  8110. }
  8111. return this
  8112. }
  8113. Buffer.prototype.toString = function toString () {
  8114. var length = this.length | 0
  8115. if (length === 0) return ''
  8116. if (arguments.length === 0) return utf8Slice(this, 0, length)
  8117. return slowToString.apply(this, arguments)
  8118. }
  8119. Buffer.prototype.equals = function equals (b) {
  8120. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  8121. if (this === b) return true
  8122. return Buffer.compare(this, b) === 0
  8123. }
  8124. Buffer.prototype.inspect = function inspect () {
  8125. var str = ''
  8126. var max = exports.INSPECT_MAX_BYTES
  8127. if (this.length > 0) {
  8128. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  8129. if (this.length > max) str += ' ... '
  8130. }
  8131. return '<Buffer ' + str + '>'
  8132. }
  8133. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  8134. if (!Buffer.isBuffer(target)) {
  8135. throw new TypeError('Argument must be a Buffer')
  8136. }
  8137. if (start === undefined) {
  8138. start = 0
  8139. }
  8140. if (end === undefined) {
  8141. end = target ? target.length : 0
  8142. }
  8143. if (thisStart === undefined) {
  8144. thisStart = 0
  8145. }
  8146. if (thisEnd === undefined) {
  8147. thisEnd = this.length
  8148. }
  8149. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  8150. throw new RangeError('out of range index')
  8151. }
  8152. if (thisStart >= thisEnd && start >= end) {
  8153. return 0
  8154. }
  8155. if (thisStart >= thisEnd) {
  8156. return -1
  8157. }
  8158. if (start >= end) {
  8159. return 1
  8160. }
  8161. start >>>= 0
  8162. end >>>= 0
  8163. thisStart >>>= 0
  8164. thisEnd >>>= 0
  8165. if (this === target) return 0
  8166. var x = thisEnd - thisStart
  8167. var y = end - start
  8168. var len = Math.min(x, y)
  8169. var thisCopy = this.slice(thisStart, thisEnd)
  8170. var targetCopy = target.slice(start, end)
  8171. for (var i = 0; i < len; ++i) {
  8172. if (thisCopy[i] !== targetCopy[i]) {
  8173. x = thisCopy[i]
  8174. y = targetCopy[i]
  8175. break
  8176. }
  8177. }
  8178. if (x < y) return -1
  8179. if (y < x) return 1
  8180. return 0
  8181. }
  8182. function arrayIndexOf (arr, val, byteOffset, encoding) {
  8183. var indexSize = 1
  8184. var arrLength = arr.length
  8185. var valLength = val.length
  8186. if (encoding !== undefined) {
  8187. encoding = String(encoding).toLowerCase()
  8188. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  8189. encoding === 'utf16le' || encoding === 'utf-16le') {
  8190. if (arr.length < 2 || val.length < 2) {
  8191. return -1
  8192. }
  8193. indexSize = 2
  8194. arrLength /= 2
  8195. valLength /= 2
  8196. byteOffset /= 2
  8197. }
  8198. }
  8199. function read (buf, i) {
  8200. if (indexSize === 1) {
  8201. return buf[i]
  8202. } else {
  8203. return buf.readUInt16BE(i * indexSize)
  8204. }
  8205. }
  8206. var foundIndex = -1
  8207. for (var i = 0; byteOffset + i < arrLength; i++) {
  8208. if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  8209. if (foundIndex === -1) foundIndex = i
  8210. if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize
  8211. } else {
  8212. if (foundIndex !== -1) i -= i - foundIndex
  8213. foundIndex = -1
  8214. }
  8215. }
  8216. return -1
  8217. }
  8218. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  8219. if (typeof byteOffset === 'string') {
  8220. encoding = byteOffset
  8221. byteOffset = 0
  8222. } else if (byteOffset > 0x7fffffff) {
  8223. byteOffset = 0x7fffffff
  8224. } else if (byteOffset < -0x80000000) {
  8225. byteOffset = -0x80000000
  8226. }
  8227. byteOffset >>= 0
  8228. if (this.length === 0) return -1
  8229. if (byteOffset >= this.length) return -1
  8230. // Negative offsets start from the end of the buffer
  8231. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  8232. if (typeof val === 'string') {
  8233. val = Buffer.from(val, encoding)
  8234. }
  8235. if (Buffer.isBuffer(val)) {
  8236. // special case: looking for empty string/buffer always fails
  8237. if (val.length === 0) {
  8238. return -1
  8239. }
  8240. return arrayIndexOf(this, val, byteOffset, encoding)
  8241. }
  8242. if (typeof val === 'number') {
  8243. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  8244. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  8245. }
  8246. return arrayIndexOf(this, [ val ], byteOffset, encoding)
  8247. }
  8248. throw new TypeError('val must be string, number or Buffer')
  8249. }
  8250. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  8251. return this.indexOf(val, byteOffset, encoding) !== -1
  8252. }
  8253. function hexWrite (buf, string, offset, length) {
  8254. offset = Number(offset) || 0
  8255. var remaining = buf.length - offset
  8256. if (!length) {
  8257. length = remaining
  8258. } else {
  8259. length = Number(length)
  8260. if (length > remaining) {
  8261. length = remaining
  8262. }
  8263. }
  8264. // must be an even number of digits
  8265. var strLen = string.length
  8266. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  8267. if (length > strLen / 2) {
  8268. length = strLen / 2
  8269. }
  8270. for (var i = 0; i < length; i++) {
  8271. var parsed = parseInt(string.substr(i * 2, 2), 16)
  8272. if (isNaN(parsed)) return i
  8273. buf[offset + i] = parsed
  8274. }
  8275. return i
  8276. }
  8277. function utf8Write (buf, string, offset, length) {
  8278. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  8279. }
  8280. function asciiWrite (buf, string, offset, length) {
  8281. return blitBuffer(asciiToBytes(string), buf, offset, length)
  8282. }
  8283. function binaryWrite (buf, string, offset, length) {
  8284. return asciiWrite(buf, string, offset, length)
  8285. }
  8286. function base64Write (buf, string, offset, length) {
  8287. return blitBuffer(base64ToBytes(string), buf, offset, length)
  8288. }
  8289. function ucs2Write (buf, string, offset, length) {
  8290. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  8291. }
  8292. Buffer.prototype.write = function write (string, offset, length, encoding) {
  8293. // Buffer#write(string)
  8294. if (offset === undefined) {
  8295. encoding = 'utf8'
  8296. length = this.length
  8297. offset = 0
  8298. // Buffer#write(string, encoding)
  8299. } else if (length === undefined && typeof offset === 'string') {
  8300. encoding = offset
  8301. length = this.length
  8302. offset = 0
  8303. // Buffer#write(string, offset[, length][, encoding])
  8304. } else if (isFinite(offset)) {
  8305. offset = offset | 0
  8306. if (isFinite(length)) {
  8307. length = length | 0
  8308. if (encoding === undefined) encoding = 'utf8'
  8309. } else {
  8310. encoding = length
  8311. length = undefined
  8312. }
  8313. // legacy write(string, encoding, offset, length) - remove in v0.13
  8314. } else {
  8315. throw new Error(
  8316. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  8317. )
  8318. }
  8319. var remaining = this.length - offset
  8320. if (length === undefined || length > remaining) length = remaining
  8321. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  8322. throw new RangeError('Attempt to write outside buffer bounds')
  8323. }
  8324. if (!encoding) encoding = 'utf8'
  8325. var loweredCase = false
  8326. for (;;) {
  8327. switch (encoding) {
  8328. case 'hex':
  8329. return hexWrite(this, string, offset, length)
  8330. case 'utf8':
  8331. case 'utf-8':
  8332. return utf8Write(this, string, offset, length)
  8333. case 'ascii':
  8334. return asciiWrite(this, string, offset, length)
  8335. case 'binary':
  8336. return binaryWrite(this, string, offset, length)
  8337. case 'base64':
  8338. // Warning: maxLength not taken into account in base64Write
  8339. return base64Write(this, string, offset, length)
  8340. case 'ucs2':
  8341. case 'ucs-2':
  8342. case 'utf16le':
  8343. case 'utf-16le':
  8344. return ucs2Write(this, string, offset, length)
  8345. default:
  8346. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8347. encoding = ('' + encoding).toLowerCase()
  8348. loweredCase = true
  8349. }
  8350. }
  8351. }
  8352. Buffer.prototype.toJSON = function toJSON () {
  8353. return {
  8354. type: 'Buffer',
  8355. data: Array.prototype.slice.call(this._arr || this, 0)
  8356. }
  8357. }
  8358. function base64Slice (buf, start, end) {
  8359. if (start === 0 && end === buf.length) {
  8360. return base64.fromByteArray(buf)
  8361. } else {
  8362. return base64.fromByteArray(buf.slice(start, end))
  8363. }
  8364. }
  8365. function utf8Slice (buf, start, end) {
  8366. end = Math.min(buf.length, end)
  8367. var res = []
  8368. var i = start
  8369. while (i < end) {
  8370. var firstByte = buf[i]
  8371. var codePoint = null
  8372. var bytesPerSequence = (firstByte > 0xEF) ? 4
  8373. : (firstByte > 0xDF) ? 3
  8374. : (firstByte > 0xBF) ? 2
  8375. : 1
  8376. if (i + bytesPerSequence <= end) {
  8377. var secondByte, thirdByte, fourthByte, tempCodePoint
  8378. switch (bytesPerSequence) {
  8379. case 1:
  8380. if (firstByte < 0x80) {
  8381. codePoint = firstByte
  8382. }
  8383. break
  8384. case 2:
  8385. secondByte = buf[i + 1]
  8386. if ((secondByte & 0xC0) === 0x80) {
  8387. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  8388. if (tempCodePoint > 0x7F) {
  8389. codePoint = tempCodePoint
  8390. }
  8391. }
  8392. break
  8393. case 3:
  8394. secondByte = buf[i + 1]
  8395. thirdByte = buf[i + 2]
  8396. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  8397. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  8398. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  8399. codePoint = tempCodePoint
  8400. }
  8401. }
  8402. break
  8403. case 4:
  8404. secondByte = buf[i + 1]
  8405. thirdByte = buf[i + 2]
  8406. fourthByte = buf[i + 3]
  8407. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  8408. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  8409. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  8410. codePoint = tempCodePoint
  8411. }
  8412. }
  8413. }
  8414. }
  8415. if (codePoint === null) {
  8416. // we did not generate a valid codePoint so insert a
  8417. // replacement char (U+FFFD) and advance only 1 byte
  8418. codePoint = 0xFFFD
  8419. bytesPerSequence = 1
  8420. } else if (codePoint > 0xFFFF) {
  8421. // encode to utf16 (surrogate pair dance)
  8422. codePoint -= 0x10000
  8423. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  8424. codePoint = 0xDC00 | codePoint & 0x3FF
  8425. }
  8426. res.push(codePoint)
  8427. i += bytesPerSequence
  8428. }
  8429. return decodeCodePointsArray(res)
  8430. }
  8431. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  8432. // the lowest limit is Chrome, with 0x10000 args.
  8433. // We go 1 magnitude less, for safety
  8434. var MAX_ARGUMENTS_LENGTH = 0x1000
  8435. function decodeCodePointsArray (codePoints) {
  8436. var len = codePoints.length
  8437. if (len <= MAX_ARGUMENTS_LENGTH) {
  8438. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  8439. }
  8440. // Decode in chunks to avoid "call stack size exceeded".
  8441. var res = ''
  8442. var i = 0
  8443. while (i < len) {
  8444. res += String.fromCharCode.apply(
  8445. String,
  8446. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  8447. )
  8448. }
  8449. return res
  8450. }
  8451. function asciiSlice (buf, start, end) {
  8452. var ret = ''
  8453. end = Math.min(buf.length, end)
  8454. for (var i = start; i < end; i++) {
  8455. ret += String.fromCharCode(buf[i] & 0x7F)
  8456. }
  8457. return ret
  8458. }
  8459. function binarySlice (buf, start, end) {
  8460. var ret = ''
  8461. end = Math.min(buf.length, end)
  8462. for (var i = start; i < end; i++) {
  8463. ret += String.fromCharCode(buf[i])
  8464. }
  8465. return ret
  8466. }
  8467. function hexSlice (buf, start, end) {
  8468. var len = buf.length
  8469. if (!start || start < 0) start = 0
  8470. if (!end || end < 0 || end > len) end = len
  8471. var out = ''
  8472. for (var i = start; i < end; i++) {
  8473. out += toHex(buf[i])
  8474. }
  8475. return out
  8476. }
  8477. function utf16leSlice (buf, start, end) {
  8478. var bytes = buf.slice(start, end)
  8479. var res = ''
  8480. for (var i = 0; i < bytes.length; i += 2) {
  8481. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  8482. }
  8483. return res
  8484. }
  8485. Buffer.prototype.slice = function slice (start, end) {
  8486. var len = this.length
  8487. start = ~~start
  8488. end = end === undefined ? len : ~~end
  8489. if (start < 0) {
  8490. start += len
  8491. if (start < 0) start = 0
  8492. } else if (start > len) {
  8493. start = len
  8494. }
  8495. if (end < 0) {
  8496. end += len
  8497. if (end < 0) end = 0
  8498. } else if (end > len) {
  8499. end = len
  8500. }
  8501. if (end < start) end = start
  8502. var newBuf
  8503. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8504. newBuf = this.subarray(start, end)
  8505. newBuf.__proto__ = Buffer.prototype
  8506. } else {
  8507. var sliceLen = end - start
  8508. newBuf = new Buffer(sliceLen, undefined)
  8509. for (var i = 0; i < sliceLen; i++) {
  8510. newBuf[i] = this[i + start]
  8511. }
  8512. }
  8513. return newBuf
  8514. }
  8515. /*
  8516. * Need to make sure that buffer isn't trying to write out of bounds.
  8517. */
  8518. function checkOffset (offset, ext, length) {
  8519. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  8520. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  8521. }
  8522. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  8523. offset = offset | 0
  8524. byteLength = byteLength | 0
  8525. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8526. var val = this[offset]
  8527. var mul = 1
  8528. var i = 0
  8529. while (++i < byteLength && (mul *= 0x100)) {
  8530. val += this[offset + i] * mul
  8531. }
  8532. return val
  8533. }
  8534. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  8535. offset = offset | 0
  8536. byteLength = byteLength | 0
  8537. if (!noAssert) {
  8538. checkOffset(offset, byteLength, this.length)
  8539. }
  8540. var val = this[offset + --byteLength]
  8541. var mul = 1
  8542. while (byteLength > 0 && (mul *= 0x100)) {
  8543. val += this[offset + --byteLength] * mul
  8544. }
  8545. return val
  8546. }
  8547. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  8548. if (!noAssert) checkOffset(offset, 1, this.length)
  8549. return this[offset]
  8550. }
  8551. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  8552. if (!noAssert) checkOffset(offset, 2, this.length)
  8553. return this[offset] | (this[offset + 1] << 8)
  8554. }
  8555. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  8556. if (!noAssert) checkOffset(offset, 2, this.length)
  8557. return (this[offset] << 8) | this[offset + 1]
  8558. }
  8559. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  8560. if (!noAssert) checkOffset(offset, 4, this.length)
  8561. return ((this[offset]) |
  8562. (this[offset + 1] << 8) |
  8563. (this[offset + 2] << 16)) +
  8564. (this[offset + 3] * 0x1000000)
  8565. }
  8566. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  8567. if (!noAssert) checkOffset(offset, 4, this.length)
  8568. return (this[offset] * 0x1000000) +
  8569. ((this[offset + 1] << 16) |
  8570. (this[offset + 2] << 8) |
  8571. this[offset + 3])
  8572. }
  8573. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  8574. offset = offset | 0
  8575. byteLength = byteLength | 0
  8576. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8577. var val = this[offset]
  8578. var mul = 1
  8579. var i = 0
  8580. while (++i < byteLength && (mul *= 0x100)) {
  8581. val += this[offset + i] * mul
  8582. }
  8583. mul *= 0x80
  8584. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8585. return val
  8586. }
  8587. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  8588. offset = offset | 0
  8589. byteLength = byteLength | 0
  8590. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8591. var i = byteLength
  8592. var mul = 1
  8593. var val = this[offset + --i]
  8594. while (i > 0 && (mul *= 0x100)) {
  8595. val += this[offset + --i] * mul
  8596. }
  8597. mul *= 0x80
  8598. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8599. return val
  8600. }
  8601. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  8602. if (!noAssert) checkOffset(offset, 1, this.length)
  8603. if (!(this[offset] & 0x80)) return (this[offset])
  8604. return ((0xff - this[offset] + 1) * -1)
  8605. }
  8606. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  8607. if (!noAssert) checkOffset(offset, 2, this.length)
  8608. var val = this[offset] | (this[offset + 1] << 8)
  8609. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8610. }
  8611. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  8612. if (!noAssert) checkOffset(offset, 2, this.length)
  8613. var val = this[offset + 1] | (this[offset] << 8)
  8614. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8615. }
  8616. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  8617. if (!noAssert) checkOffset(offset, 4, this.length)
  8618. return (this[offset]) |
  8619. (this[offset + 1] << 8) |
  8620. (this[offset + 2] << 16) |
  8621. (this[offset + 3] << 24)
  8622. }
  8623. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  8624. if (!noAssert) checkOffset(offset, 4, this.length)
  8625. return (this[offset] << 24) |
  8626. (this[offset + 1] << 16) |
  8627. (this[offset + 2] << 8) |
  8628. (this[offset + 3])
  8629. }
  8630. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  8631. if (!noAssert) checkOffset(offset, 4, this.length)
  8632. return ieee754.read(this, offset, true, 23, 4)
  8633. }
  8634. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  8635. if (!noAssert) checkOffset(offset, 4, this.length)
  8636. return ieee754.read(this, offset, false, 23, 4)
  8637. }
  8638. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  8639. if (!noAssert) checkOffset(offset, 8, this.length)
  8640. return ieee754.read(this, offset, true, 52, 8)
  8641. }
  8642. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  8643. if (!noAssert) checkOffset(offset, 8, this.length)
  8644. return ieee754.read(this, offset, false, 52, 8)
  8645. }
  8646. function checkInt (buf, value, offset, ext, max, min) {
  8647. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  8648. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  8649. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  8650. }
  8651. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  8652. value = +value
  8653. offset = offset | 0
  8654. byteLength = byteLength | 0
  8655. if (!noAssert) {
  8656. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8657. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8658. }
  8659. var mul = 1
  8660. var i = 0
  8661. this[offset] = value & 0xFF
  8662. while (++i < byteLength && (mul *= 0x100)) {
  8663. this[offset + i] = (value / mul) & 0xFF
  8664. }
  8665. return offset + byteLength
  8666. }
  8667. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  8668. value = +value
  8669. offset = offset | 0
  8670. byteLength = byteLength | 0
  8671. if (!noAssert) {
  8672. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8673. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8674. }
  8675. var i = byteLength - 1
  8676. var mul = 1
  8677. this[offset + i] = value & 0xFF
  8678. while (--i >= 0 && (mul *= 0x100)) {
  8679. this[offset + i] = (value / mul) & 0xFF
  8680. }
  8681. return offset + byteLength
  8682. }
  8683. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  8684. value = +value
  8685. offset = offset | 0
  8686. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  8687. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  8688. this[offset] = (value & 0xff)
  8689. return offset + 1
  8690. }
  8691. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  8692. if (value < 0) value = 0xffff + value + 1
  8693. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  8694. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  8695. (littleEndian ? i : 1 - i) * 8
  8696. }
  8697. }
  8698. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  8699. value = +value
  8700. offset = offset | 0
  8701. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  8702. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8703. this[offset] = (value & 0xff)
  8704. this[offset + 1] = (value >>> 8)
  8705. } else {
  8706. objectWriteUInt16(this, value, offset, true)
  8707. }
  8708. return offset + 2
  8709. }
  8710. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  8711. value = +value
  8712. offset = offset | 0
  8713. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  8714. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8715. this[offset] = (value >>> 8)
  8716. this[offset + 1] = (value & 0xff)
  8717. } else {
  8718. objectWriteUInt16(this, value, offset, false)
  8719. }
  8720. return offset + 2
  8721. }
  8722. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  8723. if (value < 0) value = 0xffffffff + value + 1
  8724. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  8725. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  8726. }
  8727. }
  8728. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  8729. value = +value
  8730. offset = offset | 0
  8731. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  8732. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8733. this[offset + 3] = (value >>> 24)
  8734. this[offset + 2] = (value >>> 16)
  8735. this[offset + 1] = (value >>> 8)
  8736. this[offset] = (value & 0xff)
  8737. } else {
  8738. objectWriteUInt32(this, value, offset, true)
  8739. }
  8740. return offset + 4
  8741. }
  8742. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  8743. value = +value
  8744. offset = offset | 0
  8745. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  8746. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8747. this[offset] = (value >>> 24)
  8748. this[offset + 1] = (value >>> 16)
  8749. this[offset + 2] = (value >>> 8)
  8750. this[offset + 3] = (value & 0xff)
  8751. } else {
  8752. objectWriteUInt32(this, value, offset, false)
  8753. }
  8754. return offset + 4
  8755. }
  8756. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  8757. value = +value
  8758. offset = offset | 0
  8759. if (!noAssert) {
  8760. var limit = Math.pow(2, 8 * byteLength - 1)
  8761. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  8762. }
  8763. var i = 0
  8764. var mul = 1
  8765. var sub = 0
  8766. this[offset] = value & 0xFF
  8767. while (++i < byteLength && (mul *= 0x100)) {
  8768. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  8769. sub = 1
  8770. }
  8771. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  8772. }
  8773. return offset + byteLength
  8774. }
  8775. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  8776. value = +value
  8777. offset = offset | 0
  8778. if (!noAssert) {
  8779. var limit = Math.pow(2, 8 * byteLength - 1)
  8780. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  8781. }
  8782. var i = byteLength - 1
  8783. var mul = 1
  8784. var sub = 0
  8785. this[offset + i] = value & 0xFF
  8786. while (--i >= 0 && (mul *= 0x100)) {
  8787. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  8788. sub = 1
  8789. }
  8790. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  8791. }
  8792. return offset + byteLength
  8793. }
  8794. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  8795. value = +value
  8796. offset = offset | 0
  8797. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  8798. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  8799. if (value < 0) value = 0xff + value + 1
  8800. this[offset] = (value & 0xff)
  8801. return offset + 1
  8802. }
  8803. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  8804. value = +value
  8805. offset = offset | 0
  8806. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  8807. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8808. this[offset] = (value & 0xff)
  8809. this[offset + 1] = (value >>> 8)
  8810. } else {
  8811. objectWriteUInt16(this, value, offset, true)
  8812. }
  8813. return offset + 2
  8814. }
  8815. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  8816. value = +value
  8817. offset = offset | 0
  8818. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  8819. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8820. this[offset] = (value >>> 8)
  8821. this[offset + 1] = (value & 0xff)
  8822. } else {
  8823. objectWriteUInt16(this, value, offset, false)
  8824. }
  8825. return offset + 2
  8826. }
  8827. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  8828. value = +value
  8829. offset = offset | 0
  8830. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8831. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8832. this[offset] = (value & 0xff)
  8833. this[offset + 1] = (value >>> 8)
  8834. this[offset + 2] = (value >>> 16)
  8835. this[offset + 3] = (value >>> 24)
  8836. } else {
  8837. objectWriteUInt32(this, value, offset, true)
  8838. }
  8839. return offset + 4
  8840. }
  8841. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  8842. value = +value
  8843. offset = offset | 0
  8844. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8845. if (value < 0) value = 0xffffffff + value + 1
  8846. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8847. this[offset] = (value >>> 24)
  8848. this[offset + 1] = (value >>> 16)
  8849. this[offset + 2] = (value >>> 8)
  8850. this[offset + 3] = (value & 0xff)
  8851. } else {
  8852. objectWriteUInt32(this, value, offset, false)
  8853. }
  8854. return offset + 4
  8855. }
  8856. function checkIEEE754 (buf, value, offset, ext, max, min) {
  8857. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  8858. if (offset < 0) throw new RangeError('Index out of range')
  8859. }
  8860. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  8861. if (!noAssert) {
  8862. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  8863. }
  8864. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  8865. return offset + 4
  8866. }
  8867. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  8868. return writeFloat(this, value, offset, true, noAssert)
  8869. }
  8870. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  8871. return writeFloat(this, value, offset, false, noAssert)
  8872. }
  8873. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  8874. if (!noAssert) {
  8875. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  8876. }
  8877. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  8878. return offset + 8
  8879. }
  8880. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  8881. return writeDouble(this, value, offset, true, noAssert)
  8882. }
  8883. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  8884. return writeDouble(this, value, offset, false, noAssert)
  8885. }
  8886. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  8887. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  8888. if (!start) start = 0
  8889. if (!end && end !== 0) end = this.length
  8890. if (targetStart >= target.length) targetStart = target.length
  8891. if (!targetStart) targetStart = 0
  8892. if (end > 0 && end < start) end = start
  8893. // Copy 0 bytes; we're done
  8894. if (end === start) return 0
  8895. if (target.length === 0 || this.length === 0) return 0
  8896. // Fatal error conditions
  8897. if (targetStart < 0) {
  8898. throw new RangeError('targetStart out of bounds')
  8899. }
  8900. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  8901. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  8902. // Are we oob?
  8903. if (end > this.length) end = this.length
  8904. if (target.length - targetStart < end - start) {
  8905. end = target.length - targetStart + start
  8906. }
  8907. var len = end - start
  8908. var i
  8909. if (this === target && start < targetStart && targetStart < end) {
  8910. // descending copy from end
  8911. for (i = len - 1; i >= 0; i--) {
  8912. target[i + targetStart] = this[i + start]
  8913. }
  8914. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  8915. // ascending copy from start
  8916. for (i = 0; i < len; i++) {
  8917. target[i + targetStart] = this[i + start]
  8918. }
  8919. } else {
  8920. Uint8Array.prototype.set.call(
  8921. target,
  8922. this.subarray(start, start + len),
  8923. targetStart
  8924. )
  8925. }
  8926. return len
  8927. }
  8928. // Usage:
  8929. // buffer.fill(number[, offset[, end]])
  8930. // buffer.fill(buffer[, offset[, end]])
  8931. // buffer.fill(string[, offset[, end]][, encoding])
  8932. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  8933. // Handle string cases:
  8934. if (typeof val === 'string') {
  8935. if (typeof start === 'string') {
  8936. encoding = start
  8937. start = 0
  8938. end = this.length
  8939. } else if (typeof end === 'string') {
  8940. encoding = end
  8941. end = this.length
  8942. }
  8943. if (val.length === 1) {
  8944. var code = val.charCodeAt(0)
  8945. if (code < 256) {
  8946. val = code
  8947. }
  8948. }
  8949. if (encoding !== undefined && typeof encoding !== 'string') {
  8950. throw new TypeError('encoding must be a string')
  8951. }
  8952. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  8953. throw new TypeError('Unknown encoding: ' + encoding)
  8954. }
  8955. } else if (typeof val === 'number') {
  8956. val = val & 255
  8957. }
  8958. // Invalid ranges are not set to a default, so can range check early.
  8959. if (start < 0 || this.length < start || this.length < end) {
  8960. throw new RangeError('Out of range index')
  8961. }
  8962. if (end <= start) {
  8963. return this
  8964. }
  8965. start = start >>> 0
  8966. end = end === undefined ? this.length : end >>> 0
  8967. if (!val) val = 0
  8968. var i
  8969. if (typeof val === 'number') {
  8970. for (i = start; i < end; i++) {
  8971. this[i] = val
  8972. }
  8973. } else {
  8974. var bytes = Buffer.isBuffer(val)
  8975. ? val
  8976. : utf8ToBytes(new Buffer(val, encoding).toString())
  8977. var len = bytes.length
  8978. for (i = 0; i < end - start; i++) {
  8979. this[i + start] = bytes[i % len]
  8980. }
  8981. }
  8982. return this
  8983. }
  8984. // HELPER FUNCTIONS
  8985. // ================
  8986. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  8987. function base64clean (str) {
  8988. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  8989. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  8990. // Node converts strings with length < 2 to ''
  8991. if (str.length < 2) return ''
  8992. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  8993. while (str.length % 4 !== 0) {
  8994. str = str + '='
  8995. }
  8996. return str
  8997. }
  8998. function stringtrim (str) {
  8999. if (str.trim) return str.trim()
  9000. return str.replace(/^\s+|\s+$/g, '')
  9001. }
  9002. function toHex (n) {
  9003. if (n < 16) return '0' + n.toString(16)
  9004. return n.toString(16)
  9005. }
  9006. function utf8ToBytes (string, units) {
  9007. units = units || Infinity
  9008. var codePoint
  9009. var length = string.length
  9010. var leadSurrogate = null
  9011. var bytes = []
  9012. for (var i = 0; i < length; i++) {
  9013. codePoint = string.charCodeAt(i)
  9014. // is surrogate component
  9015. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  9016. // last char was a lead
  9017. if (!leadSurrogate) {
  9018. // no lead yet
  9019. if (codePoint > 0xDBFF) {
  9020. // unexpected trail
  9021. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9022. continue
  9023. } else if (i + 1 === length) {
  9024. // unpaired lead
  9025. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9026. continue
  9027. }
  9028. // valid lead
  9029. leadSurrogate = codePoint
  9030. continue
  9031. }
  9032. // 2 leads in a row
  9033. if (codePoint < 0xDC00) {
  9034. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9035. leadSurrogate = codePoint
  9036. continue
  9037. }
  9038. // valid surrogate pair
  9039. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  9040. } else if (leadSurrogate) {
  9041. // valid bmp char, but last char was a lead
  9042. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9043. }
  9044. leadSurrogate = null
  9045. // encode utf8
  9046. if (codePoint < 0x80) {
  9047. if ((units -= 1) < 0) break
  9048. bytes.push(codePoint)
  9049. } else if (codePoint < 0x800) {
  9050. if ((units -= 2) < 0) break
  9051. bytes.push(
  9052. codePoint >> 0x6 | 0xC0,
  9053. codePoint & 0x3F | 0x80
  9054. )
  9055. } else if (codePoint < 0x10000) {
  9056. if ((units -= 3) < 0) break
  9057. bytes.push(
  9058. codePoint >> 0xC | 0xE0,
  9059. codePoint >> 0x6 & 0x3F | 0x80,
  9060. codePoint & 0x3F | 0x80
  9061. )
  9062. } else if (codePoint < 0x110000) {
  9063. if ((units -= 4) < 0) break
  9064. bytes.push(
  9065. codePoint >> 0x12 | 0xF0,
  9066. codePoint >> 0xC & 0x3F | 0x80,
  9067. codePoint >> 0x6 & 0x3F | 0x80,
  9068. codePoint & 0x3F | 0x80
  9069. )
  9070. } else {
  9071. throw new Error('Invalid code point')
  9072. }
  9073. }
  9074. return bytes
  9075. }
  9076. function asciiToBytes (str) {
  9077. var byteArray = []
  9078. for (var i = 0; i < str.length; i++) {
  9079. // Node's code seems to be doing this and not & 0x7F..
  9080. byteArray.push(str.charCodeAt(i) & 0xFF)
  9081. }
  9082. return byteArray
  9083. }
  9084. function utf16leToBytes (str, units) {
  9085. var c, hi, lo
  9086. var byteArray = []
  9087. for (var i = 0; i < str.length; i++) {
  9088. if ((units -= 2) < 0) break
  9089. c = str.charCodeAt(i)
  9090. hi = c >> 8
  9091. lo = c % 256
  9092. byteArray.push(lo)
  9093. byteArray.push(hi)
  9094. }
  9095. return byteArray
  9096. }
  9097. function base64ToBytes (str) {
  9098. return base64.toByteArray(base64clean(str))
  9099. }
  9100. function blitBuffer (src, dst, offset, length) {
  9101. for (var i = 0; i < length; i++) {
  9102. if ((i + offset >= dst.length) || (i >= src.length)) break
  9103. dst[i + offset] = src[i]
  9104. }
  9105. return i
  9106. }
  9107. function isnan (val) {
  9108. return val !== val // eslint-disable-line no-self-compare
  9109. }
  9110. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9111. },{"base64-js":74,"ieee754":75,"isarray":76}],74:[function(require,module,exports){
  9112. 'use strict'
  9113. exports.toByteArray = toByteArray
  9114. exports.fromByteArray = fromByteArray
  9115. var lookup = []
  9116. var revLookup = []
  9117. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  9118. function init () {
  9119. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  9120. for (var i = 0, len = code.length; i < len; ++i) {
  9121. lookup[i] = code[i]
  9122. revLookup[code.charCodeAt(i)] = i
  9123. }
  9124. revLookup['-'.charCodeAt(0)] = 62
  9125. revLookup['_'.charCodeAt(0)] = 63
  9126. }
  9127. init()
  9128. function toByteArray (b64) {
  9129. var i, j, l, tmp, placeHolders, arr
  9130. var len = b64.length
  9131. if (len % 4 > 0) {
  9132. throw new Error('Invalid string. Length must be a multiple of 4')
  9133. }
  9134. // the number of equal signs (place holders)
  9135. // if there are two placeholders, than the two characters before it
  9136. // represent one byte
  9137. // if there is only one, then the three characters before it represent 2 bytes
  9138. // this is just a cheap hack to not do indexOf twice
  9139. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  9140. // base64 is 4/3 + up to two characters of the original data
  9141. arr = new Arr(len * 3 / 4 - placeHolders)
  9142. // if there are placeholders, only get up to the last complete 4 chars
  9143. l = placeHolders > 0 ? len - 4 : len
  9144. var L = 0
  9145. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  9146. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  9147. arr[L++] = (tmp >> 16) & 0xFF
  9148. arr[L++] = (tmp >> 8) & 0xFF
  9149. arr[L++] = tmp & 0xFF
  9150. }
  9151. if (placeHolders === 2) {
  9152. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  9153. arr[L++] = tmp & 0xFF
  9154. } else if (placeHolders === 1) {
  9155. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  9156. arr[L++] = (tmp >> 8) & 0xFF
  9157. arr[L++] = tmp & 0xFF
  9158. }
  9159. return arr
  9160. }
  9161. function tripletToBase64 (num) {
  9162. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  9163. }
  9164. function encodeChunk (uint8, start, end) {
  9165. var tmp
  9166. var output = []
  9167. for (var i = start; i < end; i += 3) {
  9168. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  9169. output.push(tripletToBase64(tmp))
  9170. }
  9171. return output.join('')
  9172. }
  9173. function fromByteArray (uint8) {
  9174. var tmp
  9175. var len = uint8.length
  9176. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  9177. var output = ''
  9178. var parts = []
  9179. var maxChunkLength = 16383 // must be multiple of 3
  9180. // go through the array every three bytes, we'll deal with trailing stuff later
  9181. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  9182. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  9183. }
  9184. // pad the end with zeros, but make sure to not forget the extra bytes
  9185. if (extraBytes === 1) {
  9186. tmp = uint8[len - 1]
  9187. output += lookup[tmp >> 2]
  9188. output += lookup[(tmp << 4) & 0x3F]
  9189. output += '=='
  9190. } else if (extraBytes === 2) {
  9191. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  9192. output += lookup[tmp >> 10]
  9193. output += lookup[(tmp >> 4) & 0x3F]
  9194. output += lookup[(tmp << 2) & 0x3F]
  9195. output += '='
  9196. }
  9197. parts.push(output)
  9198. return parts.join('')
  9199. }
  9200. },{}],75:[function(require,module,exports){
  9201. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  9202. var e, m
  9203. var eLen = nBytes * 8 - mLen - 1
  9204. var eMax = (1 << eLen) - 1
  9205. var eBias = eMax >> 1
  9206. var nBits = -7
  9207. var i = isLE ? (nBytes - 1) : 0
  9208. var d = isLE ? -1 : 1
  9209. var s = buffer[offset + i]
  9210. i += d
  9211. e = s & ((1 << (-nBits)) - 1)
  9212. s >>= (-nBits)
  9213. nBits += eLen
  9214. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  9215. m = e & ((1 << (-nBits)) - 1)
  9216. e >>= (-nBits)
  9217. nBits += mLen
  9218. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  9219. if (e === 0) {
  9220. e = 1 - eBias
  9221. } else if (e === eMax) {
  9222. return m ? NaN : ((s ? -1 : 1) * Infinity)
  9223. } else {
  9224. m = m + Math.pow(2, mLen)
  9225. e = e - eBias
  9226. }
  9227. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  9228. }
  9229. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  9230. var e, m, c
  9231. var eLen = nBytes * 8 - mLen - 1
  9232. var eMax = (1 << eLen) - 1
  9233. var eBias = eMax >> 1
  9234. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  9235. var i = isLE ? 0 : (nBytes - 1)
  9236. var d = isLE ? 1 : -1
  9237. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  9238. value = Math.abs(value)
  9239. if (isNaN(value) || value === Infinity) {
  9240. m = isNaN(value) ? 1 : 0
  9241. e = eMax
  9242. } else {
  9243. e = Math.floor(Math.log(value) / Math.LN2)
  9244. if (value * (c = Math.pow(2, -e)) < 1) {
  9245. e--
  9246. c *= 2
  9247. }
  9248. if (e + eBias >= 1) {
  9249. value += rt / c
  9250. } else {
  9251. value += rt * Math.pow(2, 1 - eBias)
  9252. }
  9253. if (value * c >= 2) {
  9254. e++
  9255. c /= 2
  9256. }
  9257. if (e + eBias >= eMax) {
  9258. m = 0
  9259. e = eMax
  9260. } else if (e + eBias >= 1) {
  9261. m = (value * c - 1) * Math.pow(2, mLen)
  9262. e = e + eBias
  9263. } else {
  9264. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  9265. e = 0
  9266. }
  9267. }
  9268. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  9269. e = (e << mLen) | m
  9270. eLen += mLen
  9271. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  9272. buffer[offset + i - d] |= s * 128
  9273. }
  9274. },{}],76:[function(require,module,exports){
  9275. var toString = {}.toString;
  9276. module.exports = Array.isArray || function (arr) {
  9277. return toString.call(arr) == '[object Array]';
  9278. };
  9279. },{}],77:[function(require,module,exports){
  9280. // Copyright Joyent, Inc. and other Node contributors.
  9281. //
  9282. // Permission is hereby granted, free of charge, to any person obtaining a
  9283. // copy of this software and associated documentation files (the
  9284. // "Software"), to deal in the Software without restriction, including
  9285. // without limitation the rights to use, copy, modify, merge, publish,
  9286. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9287. // persons to whom the Software is furnished to do so, subject to the
  9288. // following conditions:
  9289. //
  9290. // The above copyright notice and this permission notice shall be included
  9291. // in all copies or substantial portions of the Software.
  9292. //
  9293. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9294. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9295. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9296. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9297. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9298. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9299. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9300. function EventEmitter() {
  9301. this._events = this._events || {};
  9302. this._maxListeners = this._maxListeners || undefined;
  9303. }
  9304. module.exports = EventEmitter;
  9305. // Backwards-compat with node 0.10.x
  9306. EventEmitter.EventEmitter = EventEmitter;
  9307. EventEmitter.prototype._events = undefined;
  9308. EventEmitter.prototype._maxListeners = undefined;
  9309. // By default EventEmitters will print a warning if more than 10 listeners are
  9310. // added to it. This is a useful default which helps finding memory leaks.
  9311. EventEmitter.defaultMaxListeners = 10;
  9312. // Obviously not all Emitters should be limited to 10. This function allows
  9313. // that to be increased. Set to zero for unlimited.
  9314. EventEmitter.prototype.setMaxListeners = function(n) {
  9315. if (!isNumber(n) || n < 0 || isNaN(n))
  9316. throw TypeError('n must be a positive number');
  9317. this._maxListeners = n;
  9318. return this;
  9319. };
  9320. EventEmitter.prototype.emit = function(type) {
  9321. var er, handler, len, args, i, listeners;
  9322. if (!this._events)
  9323. this._events = {};
  9324. // If there is no 'error' event listener then throw.
  9325. if (type === 'error') {
  9326. if (!this._events.error ||
  9327. (isObject(this._events.error) && !this._events.error.length)) {
  9328. er = arguments[1];
  9329. if (er instanceof Error) {
  9330. throw er; // Unhandled 'error' event
  9331. }
  9332. throw TypeError('Uncaught, unspecified "error" event.');
  9333. }
  9334. }
  9335. handler = this._events[type];
  9336. if (isUndefined(handler))
  9337. return false;
  9338. if (isFunction(handler)) {
  9339. switch (arguments.length) {
  9340. // fast cases
  9341. case 1:
  9342. handler.call(this);
  9343. break;
  9344. case 2:
  9345. handler.call(this, arguments[1]);
  9346. break;
  9347. case 3:
  9348. handler.call(this, arguments[1], arguments[2]);
  9349. break;
  9350. // slower
  9351. default:
  9352. args = Array.prototype.slice.call(arguments, 1);
  9353. handler.apply(this, args);
  9354. }
  9355. } else if (isObject(handler)) {
  9356. args = Array.prototype.slice.call(arguments, 1);
  9357. listeners = handler.slice();
  9358. len = listeners.length;
  9359. for (i = 0; i < len; i++)
  9360. listeners[i].apply(this, args);
  9361. }
  9362. return true;
  9363. };
  9364. EventEmitter.prototype.addListener = function(type, listener) {
  9365. var m;
  9366. if (!isFunction(listener))
  9367. throw TypeError('listener must be a function');
  9368. if (!this._events)
  9369. this._events = {};
  9370. // To avoid recursion in the case that type === "newListener"! Before
  9371. // adding it to the listeners, first emit "newListener".
  9372. if (this._events.newListener)
  9373. this.emit('newListener', type,
  9374. isFunction(listener.listener) ?
  9375. listener.listener : listener);
  9376. if (!this._events[type])
  9377. // Optimize the case of one listener. Don't need the extra array object.
  9378. this._events[type] = listener;
  9379. else if (isObject(this._events[type]))
  9380. // If we've already got an array, just append.
  9381. this._events[type].push(listener);
  9382. else
  9383. // Adding the second element, need to change to array.
  9384. this._events[type] = [this._events[type], listener];
  9385. // Check for listener leak
  9386. if (isObject(this._events[type]) && !this._events[type].warned) {
  9387. if (!isUndefined(this._maxListeners)) {
  9388. m = this._maxListeners;
  9389. } else {
  9390. m = EventEmitter.defaultMaxListeners;
  9391. }
  9392. if (m && m > 0 && this._events[type].length > m) {
  9393. this._events[type].warned = true;
  9394. console.error('(node) warning: possible EventEmitter memory ' +
  9395. 'leak detected. %d listeners added. ' +
  9396. 'Use emitter.setMaxListeners() to increase limit.',
  9397. this._events[type].length);
  9398. if (typeof console.trace === 'function') {
  9399. // not supported in IE 10
  9400. console.trace();
  9401. }
  9402. }
  9403. }
  9404. return this;
  9405. };
  9406. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  9407. EventEmitter.prototype.once = function(type, listener) {
  9408. if (!isFunction(listener))
  9409. throw TypeError('listener must be a function');
  9410. var fired = false;
  9411. function g() {
  9412. this.removeListener(type, g);
  9413. if (!fired) {
  9414. fired = true;
  9415. listener.apply(this, arguments);
  9416. }
  9417. }
  9418. g.listener = listener;
  9419. this.on(type, g);
  9420. return this;
  9421. };
  9422. // emits a 'removeListener' event iff the listener was removed
  9423. EventEmitter.prototype.removeListener = function(type, listener) {
  9424. var list, position, length, i;
  9425. if (!isFunction(listener))
  9426. throw TypeError('listener must be a function');
  9427. if (!this._events || !this._events[type])
  9428. return this;
  9429. list = this._events[type];
  9430. length = list.length;
  9431. position = -1;
  9432. if (list === listener ||
  9433. (isFunction(list.listener) && list.listener === listener)) {
  9434. delete this._events[type];
  9435. if (this._events.removeListener)
  9436. this.emit('removeListener', type, listener);
  9437. } else if (isObject(list)) {
  9438. for (i = length; i-- > 0;) {
  9439. if (list[i] === listener ||
  9440. (list[i].listener && list[i].listener === listener)) {
  9441. position = i;
  9442. break;
  9443. }
  9444. }
  9445. if (position < 0)
  9446. return this;
  9447. if (list.length === 1) {
  9448. list.length = 0;
  9449. delete this._events[type];
  9450. } else {
  9451. list.splice(position, 1);
  9452. }
  9453. if (this._events.removeListener)
  9454. this.emit('removeListener', type, listener);
  9455. }
  9456. return this;
  9457. };
  9458. EventEmitter.prototype.removeAllListeners = function(type) {
  9459. var key, listeners;
  9460. if (!this._events)
  9461. return this;
  9462. // not listening for removeListener, no need to emit
  9463. if (!this._events.removeListener) {
  9464. if (arguments.length === 0)
  9465. this._events = {};
  9466. else if (this._events[type])
  9467. delete this._events[type];
  9468. return this;
  9469. }
  9470. // emit removeListener for all listeners on all events
  9471. if (arguments.length === 0) {
  9472. for (key in this._events) {
  9473. if (key === 'removeListener') continue;
  9474. this.removeAllListeners(key);
  9475. }
  9476. this.removeAllListeners('removeListener');
  9477. this._events = {};
  9478. return this;
  9479. }
  9480. listeners = this._events[type];
  9481. if (isFunction(listeners)) {
  9482. this.removeListener(type, listeners);
  9483. } else if (listeners) {
  9484. // LIFO order
  9485. while (listeners.length)
  9486. this.removeListener(type, listeners[listeners.length - 1]);
  9487. }
  9488. delete this._events[type];
  9489. return this;
  9490. };
  9491. EventEmitter.prototype.listeners = function(type) {
  9492. var ret;
  9493. if (!this._events || !this._events[type])
  9494. ret = [];
  9495. else if (isFunction(this._events[type]))
  9496. ret = [this._events[type]];
  9497. else
  9498. ret = this._events[type].slice();
  9499. return ret;
  9500. };
  9501. EventEmitter.prototype.listenerCount = function(type) {
  9502. if (this._events) {
  9503. var evlistener = this._events[type];
  9504. if (isFunction(evlistener))
  9505. return 1;
  9506. else if (evlistener)
  9507. return evlistener.length;
  9508. }
  9509. return 0;
  9510. };
  9511. EventEmitter.listenerCount = function(emitter, type) {
  9512. return emitter.listenerCount(type);
  9513. };
  9514. function isFunction(arg) {
  9515. return typeof arg === 'function';
  9516. }
  9517. function isNumber(arg) {
  9518. return typeof arg === 'number';
  9519. }
  9520. function isObject(arg) {
  9521. return typeof arg === 'object' && arg !== null;
  9522. }
  9523. function isUndefined(arg) {
  9524. return arg === void 0;
  9525. }
  9526. },{}],78:[function(require,module,exports){
  9527. if (typeof Object.create === 'function') {
  9528. // implementation from standard node.js 'util' module
  9529. module.exports = function inherits(ctor, superCtor) {
  9530. ctor.super_ = superCtor
  9531. ctor.prototype = Object.create(superCtor.prototype, {
  9532. constructor: {
  9533. value: ctor,
  9534. enumerable: false,
  9535. writable: true,
  9536. configurable: true
  9537. }
  9538. });
  9539. };
  9540. } else {
  9541. // old school shim for old browsers
  9542. module.exports = function inherits(ctor, superCtor) {
  9543. ctor.super_ = superCtor
  9544. var TempCtor = function () {}
  9545. TempCtor.prototype = superCtor.prototype
  9546. ctor.prototype = new TempCtor()
  9547. ctor.prototype.constructor = ctor
  9548. }
  9549. }
  9550. },{}],79:[function(require,module,exports){
  9551. /**
  9552. * Determine if an object is Buffer
  9553. *
  9554. * Author: Feross Aboukhadijeh <[email protected]> <http://feross.org>
  9555. * License: MIT
  9556. *
  9557. * `npm install is-buffer`
  9558. */
  9559. module.exports = function (obj) {
  9560. return !!(obj != null &&
  9561. (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
  9562. (obj.constructor &&
  9563. typeof obj.constructor.isBuffer === 'function' &&
  9564. obj.constructor.isBuffer(obj))
  9565. ))
  9566. }
  9567. },{}],80:[function(require,module,exports){
  9568. (function (process){
  9569. // Copyright Joyent, Inc. and other Node contributors.
  9570. //
  9571. // Permission is hereby granted, free of charge, to any person obtaining a
  9572. // copy of this software and associated documentation files (the
  9573. // "Software"), to deal in the Software without restriction, including
  9574. // without limitation the rights to use, copy, modify, merge, publish,
  9575. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9576. // persons to whom the Software is furnished to do so, subject to the
  9577. // following conditions:
  9578. //
  9579. // The above copyright notice and this permission notice shall be included
  9580. // in all copies or substantial portions of the Software.
  9581. //
  9582. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9583. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9584. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9585. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9586. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9587. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9588. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9589. // resolves . and .. elements in a path array with directory names there
  9590. // must be no slashes, empty elements, or device names (c:\) in the array
  9591. // (so also no leading and trailing slashes - it does not distinguish
  9592. // relative and absolute paths)
  9593. function normalizeArray(parts, allowAboveRoot) {
  9594. // if the path tries to go above the root, `up` ends up > 0
  9595. var up = 0;
  9596. for (var i = parts.length - 1; i >= 0; i--) {
  9597. var last = parts[i];
  9598. if (last === '.') {
  9599. parts.splice(i, 1);
  9600. } else if (last === '..') {
  9601. parts.splice(i, 1);
  9602. up++;
  9603. } else if (up) {
  9604. parts.splice(i, 1);
  9605. up--;
  9606. }
  9607. }
  9608. // if the path is allowed to go above the root, restore leading ..s
  9609. if (allowAboveRoot) {
  9610. for (; up--; up) {
  9611. parts.unshift('..');
  9612. }
  9613. }
  9614. return parts;
  9615. }
  9616. // Split a filename into [root, dir, basename, ext], unix version
  9617. // 'root' is just a slash, or nothing.
  9618. var splitPathRe =
  9619. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  9620. var splitPath = function(filename) {
  9621. return splitPathRe.exec(filename).slice(1);
  9622. };
  9623. // path.resolve([from ...], to)
  9624. // posix version
  9625. exports.resolve = function() {
  9626. var resolvedPath = '',
  9627. resolvedAbsolute = false;
  9628. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  9629. var path = (i >= 0) ? arguments[i] : process.cwd();
  9630. // Skip empty and invalid entries
  9631. if (typeof path !== 'string') {
  9632. throw new TypeError('Arguments to path.resolve must be strings');
  9633. } else if (!path) {
  9634. continue;
  9635. }
  9636. resolvedPath = path + '/' + resolvedPath;
  9637. resolvedAbsolute = path.charAt(0) === '/';
  9638. }
  9639. // At this point the path should be resolved to a full absolute path, but
  9640. // handle relative paths to be safe (might happen when process.cwd() fails)
  9641. // Normalize the path
  9642. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  9643. return !!p;
  9644. }), !resolvedAbsolute).join('/');
  9645. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  9646. };
  9647. // path.normalize(path)
  9648. // posix version
  9649. exports.normalize = function(path) {
  9650. var isAbsolute = exports.isAbsolute(path),
  9651. trailingSlash = substr(path, -1) === '/';
  9652. // Normalize the path
  9653. path = normalizeArray(filter(path.split('/'), function(p) {
  9654. return !!p;
  9655. }), !isAbsolute).join('/');
  9656. if (!path && !isAbsolute) {
  9657. path = '.';
  9658. }
  9659. if (path && trailingSlash) {
  9660. path += '/';
  9661. }
  9662. return (isAbsolute ? '/' : '') + path;
  9663. };
  9664. // posix version
  9665. exports.isAbsolute = function(path) {
  9666. return path.charAt(0) === '/';
  9667. };
  9668. // posix version
  9669. exports.join = function() {
  9670. var paths = Array.prototype.slice.call(arguments, 0);
  9671. return exports.normalize(filter(paths, function(p, index) {
  9672. if (typeof p !== 'string') {
  9673. throw new TypeError('Arguments to path.join must be strings');
  9674. }
  9675. return p;
  9676. }).join('/'));
  9677. };
  9678. // path.relative(from, to)
  9679. // posix version
  9680. exports.relative = function(from, to) {
  9681. from = exports.resolve(from).substr(1);
  9682. to = exports.resolve(to).substr(1);
  9683. function trim(arr) {
  9684. var start = 0;
  9685. for (; start < arr.length; start++) {
  9686. if (arr[start] !== '') break;
  9687. }
  9688. var end = arr.length - 1;
  9689. for (; end >= 0; end--) {
  9690. if (arr[end] !== '') break;
  9691. }
  9692. if (start > end) return [];
  9693. return arr.slice(start, end - start + 1);
  9694. }
  9695. var fromParts = trim(from.split('/'));
  9696. var toParts = trim(to.split('/'));
  9697. var length = Math.min(fromParts.length, toParts.length);
  9698. var samePartsLength = length;
  9699. for (var i = 0; i < length; i++) {
  9700. if (fromParts[i] !== toParts[i]) {
  9701. samePartsLength = i;
  9702. break;
  9703. }
  9704. }
  9705. var outputParts = [];
  9706. for (var i = samePartsLength; i < fromParts.length; i++) {
  9707. outputParts.push('..');
  9708. }
  9709. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  9710. return outputParts.join('/');
  9711. };
  9712. exports.sep = '/';
  9713. exports.delimiter = ':';
  9714. exports.dirname = function(path) {
  9715. var result = splitPath(path),
  9716. root = result[0],
  9717. dir = result[1];
  9718. if (!root && !dir) {
  9719. // No dirname whatsoever
  9720. return '.';
  9721. }
  9722. if (dir) {
  9723. // It has a dirname, strip trailing slash
  9724. dir = dir.substr(0, dir.length - 1);
  9725. }
  9726. return root + dir;
  9727. };
  9728. exports.basename = function(path, ext) {
  9729. var f = splitPath(path)[2];
  9730. // TODO: make this comparison case-insensitive on windows?
  9731. if (ext && f.substr(-1 * ext.length) === ext) {
  9732. f = f.substr(0, f.length - ext.length);
  9733. }
  9734. return f;
  9735. };
  9736. exports.extname = function(path) {
  9737. return splitPath(path)[3];
  9738. };
  9739. function filter (xs, f) {
  9740. if (xs.filter) return xs.filter(f);
  9741. var res = [];
  9742. for (var i = 0; i < xs.length; i++) {
  9743. if (f(xs[i], i, xs)) res.push(xs[i]);
  9744. }
  9745. return res;
  9746. }
  9747. // String.prototype.substr - negative index don't work in IE8
  9748. var substr = 'ab'.substr(-1) === 'b'
  9749. ? function (str, start, len) { return str.substr(start, len) }
  9750. : function (str, start, len) {
  9751. if (start < 0) start = str.length + start;
  9752. return str.substr(start, len);
  9753. }
  9754. ;
  9755. }).call(this,require('_process'))
  9756. },{"_process":81}],81:[function(require,module,exports){
  9757. // shim for using process in browser
  9758. var process = module.exports = {};
  9759. // cached from whatever global is present so that test runners that stub it
  9760. // don't break things. But we need to wrap it in a try catch in case it is
  9761. // wrapped in strict mode code which doesn't define any globals. It's inside a
  9762. // function because try/catches deoptimize in certain engines.
  9763. var cachedSetTimeout;
  9764. var cachedClearTimeout;
  9765. (function () {
  9766. try {
  9767. cachedSetTimeout = setTimeout;
  9768. } catch (e) {
  9769. cachedSetTimeout = function () {
  9770. throw new Error('setTimeout is not defined');
  9771. }
  9772. }
  9773. try {
  9774. cachedClearTimeout = clearTimeout;
  9775. } catch (e) {
  9776. cachedClearTimeout = function () {
  9777. throw new Error('clearTimeout is not defined');
  9778. }
  9779. }
  9780. } ())
  9781. var queue = [];
  9782. var draining = false;
  9783. var currentQueue;
  9784. var queueIndex = -1;
  9785. function cleanUpNextTick() {
  9786. if (!draining || !currentQueue) {
  9787. return;
  9788. }
  9789. draining = false;
  9790. if (currentQueue.length) {
  9791. queue = currentQueue.concat(queue);
  9792. } else {
  9793. queueIndex = -1;
  9794. }
  9795. if (queue.length) {
  9796. drainQueue();
  9797. }
  9798. }
  9799. function drainQueue() {
  9800. if (draining) {
  9801. return;
  9802. }
  9803. var timeout = cachedSetTimeout(cleanUpNextTick);
  9804. draining = true;
  9805. var len = queue.length;
  9806. while(len) {
  9807. currentQueue = queue;
  9808. queue = [];
  9809. while (++queueIndex < len) {
  9810. if (currentQueue) {
  9811. currentQueue[queueIndex].run();
  9812. }
  9813. }
  9814. queueIndex = -1;
  9815. len = queue.length;
  9816. }
  9817. currentQueue = null;
  9818. draining = false;
  9819. cachedClearTimeout(timeout);
  9820. }
  9821. process.nextTick = function (fun) {
  9822. var args = new Array(arguments.length - 1);
  9823. if (arguments.length > 1) {
  9824. for (var i = 1; i < arguments.length; i++) {
  9825. args[i - 1] = arguments[i];
  9826. }
  9827. }
  9828. queue.push(new Item(fun, args));
  9829. if (queue.length === 1 && !draining) {
  9830. cachedSetTimeout(drainQueue, 0);
  9831. }
  9832. };
  9833. // v8 likes predictible objects
  9834. function Item(fun, array) {
  9835. this.fun = fun;
  9836. this.array = array;
  9837. }
  9838. Item.prototype.run = function () {
  9839. this.fun.apply(null, this.array);
  9840. };
  9841. process.title = 'browser';
  9842. process.browser = true;
  9843. process.env = {};
  9844. process.argv = [];
  9845. process.version = ''; // empty string to avoid regexp issues
  9846. process.versions = {};
  9847. function noop() {}
  9848. process.on = noop;
  9849. process.addListener = noop;
  9850. process.once = noop;
  9851. process.off = noop;
  9852. process.removeListener = noop;
  9853. process.removeAllListeners = noop;
  9854. process.emit = noop;
  9855. process.binding = function (name) {
  9856. throw new Error('process.binding is not supported');
  9857. };
  9858. process.cwd = function () { return '/' };
  9859. process.chdir = function (dir) {
  9860. throw new Error('process.chdir is not supported');
  9861. };
  9862. process.umask = function() { return 0; };
  9863. },{}],82:[function(require,module,exports){
  9864. module.exports = require("./lib/_stream_duplex.js")
  9865. },{"./lib/_stream_duplex.js":83}],83:[function(require,module,exports){
  9866. // a duplex stream is just a stream that is both readable and writable.
  9867. // Since JS doesn't have multiple prototypal inheritance, this class
  9868. // prototypally inherits from Readable, and then parasitically from
  9869. // Writable.
  9870. 'use strict';
  9871. /*<replacement>*/
  9872. var objectKeys = Object.keys || function (obj) {
  9873. var keys = [];
  9874. for (var key in obj) {
  9875. keys.push(key);
  9876. }return keys;
  9877. };
  9878. /*</replacement>*/
  9879. module.exports = Duplex;
  9880. /*<replacement>*/
  9881. var processNextTick = require('process-nextick-args');
  9882. /*</replacement>*/
  9883. /*<replacement>*/
  9884. var util = require('core-util-is');
  9885. util.inherits = require('inherits');
  9886. /*</replacement>*/
  9887. var Readable = require('./_stream_readable');
  9888. var Writable = require('./_stream_writable');
  9889. util.inherits(Duplex, Readable);
  9890. var keys = objectKeys(Writable.prototype);
  9891. for (var v = 0; v < keys.length; v++) {
  9892. var method = keys[v];
  9893. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  9894. }
  9895. function Duplex(options) {
  9896. if (!(this instanceof Duplex)) return new Duplex(options);
  9897. Readable.call(this, options);
  9898. Writable.call(this, options);
  9899. if (options && options.readable === false) this.readable = false;
  9900. if (options && options.writable === false) this.writable = false;
  9901. this.allowHalfOpen = true;
  9902. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  9903. this.once('end', onend);
  9904. }
  9905. // the no-half-open enforcer
  9906. function onend() {
  9907. // if we allow half-open state, or if the writable side ended,
  9908. // then we're ok.
  9909. if (this.allowHalfOpen || this._writableState.ended) return;
  9910. // no more data can be written.
  9911. // But allow more writes to happen in this tick.
  9912. processNextTick(onEndNT, this);
  9913. }
  9914. function onEndNT(self) {
  9915. self.end();
  9916. }
  9917. function forEach(xs, f) {
  9918. for (var i = 0, l = xs.length; i < l; i++) {
  9919. f(xs[i], i);
  9920. }
  9921. }
  9922. },{"./_stream_readable":85,"./_stream_writable":87,"core-util-is":89,"inherits":78,"process-nextick-args":91}],84:[function(require,module,exports){
  9923. // a passthrough stream.
  9924. // basically just the most minimal sort of Transform stream.
  9925. // Every written chunk gets output as-is.
  9926. 'use strict';
  9927. module.exports = PassThrough;
  9928. var Transform = require('./_stream_transform');
  9929. /*<replacement>*/
  9930. var util = require('core-util-is');
  9931. util.inherits = require('inherits');
  9932. /*</replacement>*/
  9933. util.inherits(PassThrough, Transform);
  9934. function PassThrough(options) {
  9935. if (!(this instanceof PassThrough)) return new PassThrough(options);
  9936. Transform.call(this, options);
  9937. }
  9938. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  9939. cb(null, chunk);
  9940. };
  9941. },{"./_stream_transform":86,"core-util-is":89,"inherits":78}],85:[function(require,module,exports){
  9942. (function (process){
  9943. 'use strict';
  9944. module.exports = Readable;
  9945. /*<replacement>*/
  9946. var processNextTick = require('process-nextick-args');
  9947. /*</replacement>*/
  9948. /*<replacement>*/
  9949. var isArray = require('isarray');
  9950. /*</replacement>*/
  9951. Readable.ReadableState = ReadableState;
  9952. /*<replacement>*/
  9953. var EE = require('events').EventEmitter;
  9954. var EElistenerCount = function (emitter, type) {
  9955. return emitter.listeners(type).length;
  9956. };
  9957. /*</replacement>*/
  9958. /*<replacement>*/
  9959. var Stream;
  9960. (function () {
  9961. try {
  9962. Stream = require('st' + 'ream');
  9963. } catch (_) {} finally {
  9964. if (!Stream) Stream = require('events').EventEmitter;
  9965. }
  9966. })();
  9967. /*</replacement>*/
  9968. var Buffer = require('buffer').Buffer;
  9969. /*<replacement>*/
  9970. var bufferShim = require('buffer-shims');
  9971. /*</replacement>*/
  9972. /*<replacement>*/
  9973. var util = require('core-util-is');
  9974. util.inherits = require('inherits');
  9975. /*</replacement>*/
  9976. /*<replacement>*/
  9977. var debugUtil = require('util');
  9978. var debug = void 0;
  9979. if (debugUtil && debugUtil.debuglog) {
  9980. debug = debugUtil.debuglog('stream');
  9981. } else {
  9982. debug = function () {};
  9983. }
  9984. /*</replacement>*/
  9985. var StringDecoder;
  9986. util.inherits(Readable, Stream);
  9987. var hasPrependListener = typeof EE.prototype.prependListener === 'function';
  9988. function prependListener(emitter, event, fn) {
  9989. if (hasPrependListener) return emitter.prependListener(event, fn);
  9990. // This is a brutally ugly hack to make sure that our error handler
  9991. // is attached before any userland ones. NEVER DO THIS. This is here
  9992. // only because this code needs to continue to work with older versions
  9993. // of Node.js that do not include the prependListener() method. The goal
  9994. // is to eventually remove this hack.
  9995. 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]];
  9996. }
  9997. var Duplex;
  9998. function ReadableState(options, stream) {
  9999. Duplex = Duplex || require('./_stream_duplex');
  10000. options = options || {};
  10001. // object stream flag. Used to make read(n) ignore n and to
  10002. // make all the buffer merging and length checks go away
  10003. this.objectMode = !!options.objectMode;
  10004. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  10005. // the point at which it stops calling _read() to fill the buffer
  10006. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  10007. var hwm = options.highWaterMark;
  10008. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  10009. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  10010. // cast to ints.
  10011. this.highWaterMark = ~ ~this.highWaterMark;
  10012. this.buffer = [];
  10013. this.length = 0;
  10014. this.pipes = null;
  10015. this.pipesCount = 0;
  10016. this.flowing = null;
  10017. this.ended = false;
  10018. this.endEmitted = false;
  10019. this.reading = false;
  10020. // a flag to be able to tell if the onwrite cb is called immediately,
  10021. // or on a later tick. We set this to true at first, because any
  10022. // actions that shouldn't happen until "later" should generally also
  10023. // not happen before the first write call.
  10024. this.sync = true;
  10025. // whenever we return null, then we set a flag to say
  10026. // that we're awaiting a 'readable' event emission.
  10027. this.needReadable = false;
  10028. this.emittedReadable = false;
  10029. this.readableListening = false;
  10030. this.resumeScheduled = false;
  10031. // Crypto is kind of old and crusty. Historically, its default string
  10032. // encoding is 'binary' so we have to make this configurable.
  10033. // Everything else in the universe uses 'utf8', though.
  10034. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10035. // when piping, we only care about 'readable' events that happen
  10036. // after read()ing all the bytes and not getting any pushback.
  10037. this.ranOut = false;
  10038. // the number of writers that are awaiting a drain event in .pipe()s
  10039. this.awaitDrain = 0;
  10040. // if true, a maybeReadMore has been scheduled
  10041. this.readingMore = false;
  10042. this.decoder = null;
  10043. this.encoding = null;
  10044. if (options.encoding) {
  10045. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  10046. this.decoder = new StringDecoder(options.encoding);
  10047. this.encoding = options.encoding;
  10048. }
  10049. }
  10050. var Duplex;
  10051. function Readable(options) {
  10052. Duplex = Duplex || require('./_stream_duplex');
  10053. if (!(this instanceof Readable)) return new Readable(options);
  10054. this._readableState = new ReadableState(options, this);
  10055. // legacy
  10056. this.readable = true;
  10057. if (options && typeof options.read === 'function') this._read = options.read;
  10058. Stream.call(this);
  10059. }
  10060. // Manually shove something into the read() buffer.
  10061. // This returns true if the highWaterMark has not been hit yet,
  10062. // similar to how Writable.write() returns true if you should
  10063. // write() some more.
  10064. Readable.prototype.push = function (chunk, encoding) {
  10065. var state = this._readableState;
  10066. if (!state.objectMode && typeof chunk === 'string') {
  10067. encoding = encoding || state.defaultEncoding;
  10068. if (encoding !== state.encoding) {
  10069. chunk = bufferShim.from(chunk, encoding);
  10070. encoding = '';
  10071. }
  10072. }
  10073. return readableAddChunk(this, state, chunk, encoding, false);
  10074. };
  10075. // Unshift should *always* be something directly out of read()
  10076. Readable.prototype.unshift = function (chunk) {
  10077. var state = this._readableState;
  10078. return readableAddChunk(this, state, chunk, '', true);
  10079. };
  10080. Readable.prototype.isPaused = function () {
  10081. return this._readableState.flowing === false;
  10082. };
  10083. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  10084. var er = chunkInvalid(state, chunk);
  10085. if (er) {
  10086. stream.emit('error', er);
  10087. } else if (chunk === null) {
  10088. state.reading = false;
  10089. onEofChunk(stream, state);
  10090. } else if (state.objectMode || chunk && chunk.length > 0) {
  10091. if (state.ended && !addToFront) {
  10092. var e = new Error('stream.push() after EOF');
  10093. stream.emit('error', e);
  10094. } else if (state.endEmitted && addToFront) {
  10095. var _e = new Error('stream.unshift() after end event');
  10096. stream.emit('error', _e);
  10097. } else {
  10098. var skipAdd;
  10099. if (state.decoder && !addToFront && !encoding) {
  10100. chunk = state.decoder.write(chunk);
  10101. skipAdd = !state.objectMode && chunk.length === 0;
  10102. }
  10103. if (!addToFront) state.reading = false;
  10104. // Don't add to the buffer if we've decoded to an empty string chunk and
  10105. // we're not in object mode
  10106. if (!skipAdd) {
  10107. // if we want the data now, just emit it.
  10108. if (state.flowing && state.length === 0 && !state.sync) {
  10109. stream.emit('data', chunk);
  10110. stream.read(0);
  10111. } else {
  10112. // update the buffer info.
  10113. state.length += state.objectMode ? 1 : chunk.length;
  10114. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  10115. if (state.needReadable) emitReadable(stream);
  10116. }
  10117. }
  10118. maybeReadMore(stream, state);
  10119. }
  10120. } else if (!addToFront) {
  10121. state.reading = false;
  10122. }
  10123. return needMoreData(state);
  10124. }
  10125. // if it's past the high water mark, we can push in some more.
  10126. // Also, if we have no data yet, we can stand some
  10127. // more bytes. This is to work around cases where hwm=0,
  10128. // such as the repl. Also, if the push() triggered a
  10129. // readable event, and the user called read(largeNumber) such that
  10130. // needReadable was set, then we ought to push more, so that another
  10131. // 'readable' event will be triggered.
  10132. function needMoreData(state) {
  10133. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  10134. }
  10135. // backwards compatibility.
  10136. Readable.prototype.setEncoding = function (enc) {
  10137. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  10138. this._readableState.decoder = new StringDecoder(enc);
  10139. this._readableState.encoding = enc;
  10140. return this;
  10141. };
  10142. // Don't raise the hwm > 8MB
  10143. var MAX_HWM = 0x800000;
  10144. function computeNewHighWaterMark(n) {
  10145. if (n >= MAX_HWM) {
  10146. n = MAX_HWM;
  10147. } else {
  10148. // Get the next highest power of 2
  10149. n--;
  10150. n |= n >>> 1;
  10151. n |= n >>> 2;
  10152. n |= n >>> 4;
  10153. n |= n >>> 8;
  10154. n |= n >>> 16;
  10155. n++;
  10156. }
  10157. return n;
  10158. }
  10159. function howMuchToRead(n, state) {
  10160. if (state.length === 0 && state.ended) return 0;
  10161. if (state.objectMode) return n === 0 ? 0 : 1;
  10162. if (n === null || isNaN(n)) {
  10163. // only flow one buffer at a time
  10164. if (state.flowing && state.buffer.length) return state.buffer[0].length;else return state.length;
  10165. }
  10166. if (n <= 0) return 0;
  10167. // If we're asking for more than the target buffer level,
  10168. // then raise the water mark. Bump up to the next highest
  10169. // power of 2, to prevent increasing it excessively in tiny
  10170. // amounts.
  10171. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  10172. // don't have that much. return null, unless we've ended.
  10173. if (n > state.length) {
  10174. if (!state.ended) {
  10175. state.needReadable = true;
  10176. return 0;
  10177. } else {
  10178. return state.length;
  10179. }
  10180. }
  10181. return n;
  10182. }
  10183. // you can override either this method, or the async _read(n) below.
  10184. Readable.prototype.read = function (n) {
  10185. debug('read', n);
  10186. var state = this._readableState;
  10187. var nOrig = n;
  10188. if (typeof n !== 'number' || n > 0) state.emittedReadable = false;
  10189. // if we're doing read(0) to trigger a readable event, but we
  10190. // already have a bunch of data in the buffer, then just trigger
  10191. // the 'readable' event and move on.
  10192. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  10193. debug('read: emitReadable', state.length, state.ended);
  10194. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  10195. return null;
  10196. }
  10197. n = howMuchToRead(n, state);
  10198. // if we've ended, and we're now clear, then finish it up.
  10199. if (n === 0 && state.ended) {
  10200. if (state.length === 0) endReadable(this);
  10201. return null;
  10202. }
  10203. // All the actual chunk generation logic needs to be
  10204. // *below* the call to _read. The reason is that in certain
  10205. // synthetic stream cases, such as passthrough streams, _read
  10206. // may be a completely synchronous operation which may change
  10207. // the state of the read buffer, providing enough data when
  10208. // before there was *not* enough.
  10209. //
  10210. // So, the steps are:
  10211. // 1. Figure out what the state of things will be after we do
  10212. // a read from the buffer.
  10213. //
  10214. // 2. If that resulting state will trigger a _read, then call _read.
  10215. // Note that this may be asynchronous, or synchronous. Yes, it is
  10216. // deeply ugly to write APIs this way, but that still doesn't mean
  10217. // that the Readable class should behave improperly, as streams are
  10218. // designed to be sync/async agnostic.
  10219. // Take note if the _read call is sync or async (ie, if the read call
  10220. // has returned yet), so that we know whether or not it's safe to emit
  10221. // 'readable' etc.
  10222. //
  10223. // 3. Actually pull the requested chunks out of the buffer and return.
  10224. // if we need a readable event, then we need to do some reading.
  10225. var doRead = state.needReadable;
  10226. debug('need readable', doRead);
  10227. // if we currently have less than the highWaterMark, then also read some
  10228. if (state.length === 0 || state.length - n < state.highWaterMark) {
  10229. doRead = true;
  10230. debug('length less than watermark', doRead);
  10231. }
  10232. // however, if we've ended, then there's no point, and if we're already
  10233. // reading, then it's unnecessary.
  10234. if (state.ended || state.reading) {
  10235. doRead = false;
  10236. debug('reading or ended', doRead);
  10237. }
  10238. if (doRead) {
  10239. debug('do read');
  10240. state.reading = true;
  10241. state.sync = true;
  10242. // if the length is currently zero, then we *need* a readable event.
  10243. if (state.length === 0) state.needReadable = true;
  10244. // call internal read method
  10245. this._read(state.highWaterMark);
  10246. state.sync = false;
  10247. }
  10248. // If _read pushed data synchronously, then `reading` will be false,
  10249. // and we need to re-evaluate how much data we can return to the user.
  10250. if (doRead && !state.reading) n = howMuchToRead(nOrig, state);
  10251. var ret;
  10252. if (n > 0) ret = fromList(n, state);else ret = null;
  10253. if (ret === null) {
  10254. state.needReadable = true;
  10255. n = 0;
  10256. }
  10257. state.length -= n;
  10258. // If we have nothing in the buffer, then we want to know
  10259. // as soon as we *do* get something into the buffer.
  10260. if (state.length === 0 && !state.ended) state.needReadable = true;
  10261. // If we tried to read() past the EOF, then emit end on the next tick.
  10262. if (nOrig !== n && state.ended && state.length === 0) endReadable(this);
  10263. if (ret !== null) this.emit('data', ret);
  10264. return ret;
  10265. };
  10266. function chunkInvalid(state, chunk) {
  10267. var er = null;
  10268. if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
  10269. er = new TypeError('Invalid non-string/buffer chunk');
  10270. }
  10271. return er;
  10272. }
  10273. function onEofChunk(stream, state) {
  10274. if (state.ended) return;
  10275. if (state.decoder) {
  10276. var chunk = state.decoder.end();
  10277. if (chunk && chunk.length) {
  10278. state.buffer.push(chunk);
  10279. state.length += state.objectMode ? 1 : chunk.length;
  10280. }
  10281. }
  10282. state.ended = true;
  10283. // emit 'readable' now to make sure it gets picked up.
  10284. emitReadable(stream);
  10285. }
  10286. // Don't emit readable right away in sync mode, because this can trigger
  10287. // another read() call => stack overflow. This way, it might trigger
  10288. // a nextTick recursion warning, but that's not so bad.
  10289. function emitReadable(stream) {
  10290. var state = stream._readableState;
  10291. state.needReadable = false;
  10292. if (!state.emittedReadable) {
  10293. debug('emitReadable', state.flowing);
  10294. state.emittedReadable = true;
  10295. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  10296. }
  10297. }
  10298. function emitReadable_(stream) {
  10299. debug('emit readable');
  10300. stream.emit('readable');
  10301. flow(stream);
  10302. }
  10303. // at this point, the user has presumably seen the 'readable' event,
  10304. // and called read() to consume some data. that may have triggered
  10305. // in turn another _read(n) call, in which case reading = true if
  10306. // it's in progress.
  10307. // However, if we're not ended, or reading, and the length < hwm,
  10308. // then go ahead and try to read some more preemptively.
  10309. function maybeReadMore(stream, state) {
  10310. if (!state.readingMore) {
  10311. state.readingMore = true;
  10312. processNextTick(maybeReadMore_, stream, state);
  10313. }
  10314. }
  10315. function maybeReadMore_(stream, state) {
  10316. var len = state.length;
  10317. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  10318. debug('maybeReadMore read 0');
  10319. stream.read(0);
  10320. if (len === state.length)
  10321. // didn't get any data, stop spinning.
  10322. break;else len = state.length;
  10323. }
  10324. state.readingMore = false;
  10325. }
  10326. // abstract method. to be overridden in specific implementation classes.
  10327. // call cb(er, data) where data is <= n in length.
  10328. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  10329. // arbitrary, and perhaps not very meaningful.
  10330. Readable.prototype._read = function (n) {
  10331. this.emit('error', new Error('not implemented'));
  10332. };
  10333. Readable.prototype.pipe = function (dest, pipeOpts) {
  10334. var src = this;
  10335. var state = this._readableState;
  10336. switch (state.pipesCount) {
  10337. case 0:
  10338. state.pipes = dest;
  10339. break;
  10340. case 1:
  10341. state.pipes = [state.pipes, dest];
  10342. break;
  10343. default:
  10344. state.pipes.push(dest);
  10345. break;
  10346. }
  10347. state.pipesCount += 1;
  10348. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  10349. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  10350. var endFn = doEnd ? onend : cleanup;
  10351. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  10352. dest.on('unpipe', onunpipe);
  10353. function onunpipe(readable) {
  10354. debug('onunpipe');
  10355. if (readable === src) {
  10356. cleanup();
  10357. }
  10358. }
  10359. function onend() {
  10360. debug('onend');
  10361. dest.end();
  10362. }
  10363. // when the dest drains, it reduces the awaitDrain counter
  10364. // on the source. This would be more elegant with a .once()
  10365. // handler in flow(), but adding and removing repeatedly is
  10366. // too slow.
  10367. var ondrain = pipeOnDrain(src);
  10368. dest.on('drain', ondrain);
  10369. var cleanedUp = false;
  10370. function cleanup() {
  10371. debug('cleanup');
  10372. // cleanup event handlers once the pipe is broken
  10373. dest.removeListener('close', onclose);
  10374. dest.removeListener('finish', onfinish);
  10375. dest.removeListener('drain', ondrain);
  10376. dest.removeListener('error', onerror);
  10377. dest.removeListener('unpipe', onunpipe);
  10378. src.removeListener('end', onend);
  10379. src.removeListener('end', cleanup);
  10380. src.removeListener('data', ondata);
  10381. cleanedUp = true;
  10382. // if the reader is waiting for a drain event from this
  10383. // specific writer, then it would cause it to never start
  10384. // flowing again.
  10385. // So, if this is awaiting a drain, then we just call it now.
  10386. // If we don't know, then assume that we are waiting for one.
  10387. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  10388. }
  10389. src.on('data', ondata);
  10390. function ondata(chunk) {
  10391. debug('ondata');
  10392. var ret = dest.write(chunk);
  10393. if (false === ret) {
  10394. // If the user unpiped during `dest.write()`, it is possible
  10395. // to get stuck in a permanently paused state if that write
  10396. // also returned false.
  10397. // => Check whether `dest` is still a piping destination.
  10398. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  10399. debug('false write response, pause', src._readableState.awaitDrain);
  10400. src._readableState.awaitDrain++;
  10401. }
  10402. src.pause();
  10403. }
  10404. }
  10405. // if the dest has an error, then stop piping into it.
  10406. // however, don't suppress the throwing behavior for this.
  10407. function onerror(er) {
  10408. debug('onerror', er);
  10409. unpipe();
  10410. dest.removeListener('error', onerror);
  10411. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  10412. }
  10413. // Make sure our error handler is attached before userland ones.
  10414. prependListener(dest, 'error', onerror);
  10415. // Both close and finish should trigger unpipe, but only once.
  10416. function onclose() {
  10417. dest.removeListener('finish', onfinish);
  10418. unpipe();
  10419. }
  10420. dest.once('close', onclose);
  10421. function onfinish() {
  10422. debug('onfinish');
  10423. dest.removeListener('close', onclose);
  10424. unpipe();
  10425. }
  10426. dest.once('finish', onfinish);
  10427. function unpipe() {
  10428. debug('unpipe');
  10429. src.unpipe(dest);
  10430. }
  10431. // tell the dest that it's being piped to
  10432. dest.emit('pipe', src);
  10433. // start the flow if it hasn't been started already.
  10434. if (!state.flowing) {
  10435. debug('pipe resume');
  10436. src.resume();
  10437. }
  10438. return dest;
  10439. };
  10440. function pipeOnDrain(src) {
  10441. return function () {
  10442. var state = src._readableState;
  10443. debug('pipeOnDrain', state.awaitDrain);
  10444. if (state.awaitDrain) state.awaitDrain--;
  10445. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  10446. state.flowing = true;
  10447. flow(src);
  10448. }
  10449. };
  10450. }
  10451. Readable.prototype.unpipe = function (dest) {
  10452. var state = this._readableState;
  10453. // if we're not piping anywhere, then do nothing.
  10454. if (state.pipesCount === 0) return this;
  10455. // just one destination. most common case.
  10456. if (state.pipesCount === 1) {
  10457. // passed in one, but it's not the right one.
  10458. if (dest && dest !== state.pipes) return this;
  10459. if (!dest) dest = state.pipes;
  10460. // got a match.
  10461. state.pipes = null;
  10462. state.pipesCount = 0;
  10463. state.flowing = false;
  10464. if (dest) dest.emit('unpipe', this);
  10465. return this;
  10466. }
  10467. // slow case. multiple pipe destinations.
  10468. if (!dest) {
  10469. // remove all.
  10470. var dests = state.pipes;
  10471. var len = state.pipesCount;
  10472. state.pipes = null;
  10473. state.pipesCount = 0;
  10474. state.flowing = false;
  10475. for (var _i = 0; _i < len; _i++) {
  10476. dests[_i].emit('unpipe', this);
  10477. }return this;
  10478. }
  10479. // try to find the right one.
  10480. var i = indexOf(state.pipes, dest);
  10481. if (i === -1) return this;
  10482. state.pipes.splice(i, 1);
  10483. state.pipesCount -= 1;
  10484. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  10485. dest.emit('unpipe', this);
  10486. return this;
  10487. };
  10488. // set up data events if they are asked for
  10489. // Ensure readable listeners eventually get something
  10490. Readable.prototype.on = function (ev, fn) {
  10491. var res = Stream.prototype.on.call(this, ev, fn);
  10492. // If listening to data, and it has not explicitly been paused,
  10493. // then call resume to start the flow of data on the next tick.
  10494. if (ev === 'data' && false !== this._readableState.flowing) {
  10495. this.resume();
  10496. }
  10497. if (ev === 'readable' && !this._readableState.endEmitted) {
  10498. var state = this._readableState;
  10499. if (!state.readableListening) {
  10500. state.readableListening = true;
  10501. state.emittedReadable = false;
  10502. state.needReadable = true;
  10503. if (!state.reading) {
  10504. processNextTick(nReadingNextTick, this);
  10505. } else if (state.length) {
  10506. emitReadable(this, state);
  10507. }
  10508. }
  10509. }
  10510. return res;
  10511. };
  10512. Readable.prototype.addListener = Readable.prototype.on;
  10513. function nReadingNextTick(self) {
  10514. debug('readable nexttick read 0');
  10515. self.read(0);
  10516. }
  10517. // pause() and resume() are remnants of the legacy readable stream API
  10518. // If the user uses them, then switch into old mode.
  10519. Readable.prototype.resume = function () {
  10520. var state = this._readableState;
  10521. if (!state.flowing) {
  10522. debug('resume');
  10523. state.flowing = true;
  10524. resume(this, state);
  10525. }
  10526. return this;
  10527. };
  10528. function resume(stream, state) {
  10529. if (!state.resumeScheduled) {
  10530. state.resumeScheduled = true;
  10531. processNextTick(resume_, stream, state);
  10532. }
  10533. }
  10534. function resume_(stream, state) {
  10535. if (!state.reading) {
  10536. debug('resume read 0');
  10537. stream.read(0);
  10538. }
  10539. state.resumeScheduled = false;
  10540. stream.emit('resume');
  10541. flow(stream);
  10542. if (state.flowing && !state.reading) stream.read(0);
  10543. }
  10544. Readable.prototype.pause = function () {
  10545. debug('call pause flowing=%j', this._readableState.flowing);
  10546. if (false !== this._readableState.flowing) {
  10547. debug('pause');
  10548. this._readableState.flowing = false;
  10549. this.emit('pause');
  10550. }
  10551. return this;
  10552. };
  10553. function flow(stream) {
  10554. var state = stream._readableState;
  10555. debug('flow', state.flowing);
  10556. if (state.flowing) {
  10557. do {
  10558. var chunk = stream.read();
  10559. } while (null !== chunk && state.flowing);
  10560. }
  10561. }
  10562. // wrap an old-style stream as the async data source.
  10563. // This is *not* part of the readable stream interface.
  10564. // It is an ugly unfortunate mess of history.
  10565. Readable.prototype.wrap = function (stream) {
  10566. var state = this._readableState;
  10567. var paused = false;
  10568. var self = this;
  10569. stream.on('end', function () {
  10570. debug('wrapped end');
  10571. if (state.decoder && !state.ended) {
  10572. var chunk = state.decoder.end();
  10573. if (chunk && chunk.length) self.push(chunk);
  10574. }
  10575. self.push(null);
  10576. });
  10577. stream.on('data', function (chunk) {
  10578. debug('wrapped data');
  10579. if (state.decoder) chunk = state.decoder.write(chunk);
  10580. // don't skip over falsy values in objectMode
  10581. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  10582. var ret = self.push(chunk);
  10583. if (!ret) {
  10584. paused = true;
  10585. stream.pause();
  10586. }
  10587. });
  10588. // proxy all the other methods.
  10589. // important when wrapping filters and duplexes.
  10590. for (var i in stream) {
  10591. if (this[i] === undefined && typeof stream[i] === 'function') {
  10592. this[i] = function (method) {
  10593. return function () {
  10594. return stream[method].apply(stream, arguments);
  10595. };
  10596. }(i);
  10597. }
  10598. }
  10599. // proxy certain important events.
  10600. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  10601. forEach(events, function (ev) {
  10602. stream.on(ev, self.emit.bind(self, ev));
  10603. });
  10604. // when we try to consume some more bytes, simply unpause the
  10605. // underlying stream.
  10606. self._read = function (n) {
  10607. debug('wrapped _read', n);
  10608. if (paused) {
  10609. paused = false;
  10610. stream.resume();
  10611. }
  10612. };
  10613. return self;
  10614. };
  10615. // exposed for testing purposes only.
  10616. Readable._fromList = fromList;
  10617. // Pluck off n bytes from an array of buffers.
  10618. // Length is the combined lengths of all the buffers in the list.
  10619. function fromList(n, state) {
  10620. var list = state.buffer;
  10621. var length = state.length;
  10622. var stringMode = !!state.decoder;
  10623. var objectMode = !!state.objectMode;
  10624. var ret;
  10625. // nothing in the list, definitely empty.
  10626. if (list.length === 0) return null;
  10627. if (length === 0) ret = null;else if (objectMode) ret = list.shift();else if (!n || n >= length) {
  10628. // read it all, truncate the array.
  10629. if (stringMode) ret = list.join('');else if (list.length === 1) ret = list[0];else ret = Buffer.concat(list, length);
  10630. list.length = 0;
  10631. } else {
  10632. // read just some of it.
  10633. if (n < list[0].length) {
  10634. // just take a part of the first list item.
  10635. // slice is the same for buffers and strings.
  10636. var buf = list[0];
  10637. ret = buf.slice(0, n);
  10638. list[0] = buf.slice(n);
  10639. } else if (n === list[0].length) {
  10640. // first list is a perfect match
  10641. ret = list.shift();
  10642. } else {
  10643. // complex case.
  10644. // we have enough to cover it, but it spans past the first buffer.
  10645. if (stringMode) ret = '';else ret = bufferShim.allocUnsafe(n);
  10646. var c = 0;
  10647. for (var i = 0, l = list.length; i < l && c < n; i++) {
  10648. var _buf = list[0];
  10649. var cpy = Math.min(n - c, _buf.length);
  10650. if (stringMode) ret += _buf.slice(0, cpy);else _buf.copy(ret, c, 0, cpy);
  10651. if (cpy < _buf.length) list[0] = _buf.slice(cpy);else list.shift();
  10652. c += cpy;
  10653. }
  10654. }
  10655. }
  10656. return ret;
  10657. }
  10658. function endReadable(stream) {
  10659. var state = stream._readableState;
  10660. // If we get here before consuming all the bytes, then that is a
  10661. // bug in node. Should never happen.
  10662. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  10663. if (!state.endEmitted) {
  10664. state.ended = true;
  10665. processNextTick(endReadableNT, state, stream);
  10666. }
  10667. }
  10668. function endReadableNT(state, stream) {
  10669. // Check that we didn't get one last unshift.
  10670. if (!state.endEmitted && state.length === 0) {
  10671. state.endEmitted = true;
  10672. stream.readable = false;
  10673. stream.emit('end');
  10674. }
  10675. }
  10676. function forEach(xs, f) {
  10677. for (var i = 0, l = xs.length; i < l; i++) {
  10678. f(xs[i], i);
  10679. }
  10680. }
  10681. function indexOf(xs, x) {
  10682. for (var i = 0, l = xs.length; i < l; i++) {
  10683. if (xs[i] === x) return i;
  10684. }
  10685. return -1;
  10686. }
  10687. }).call(this,require('_process'))
  10688. },{"./_stream_duplex":83,"_process":81,"buffer":73,"buffer-shims":88,"core-util-is":89,"events":77,"inherits":78,"isarray":90,"process-nextick-args":91,"string_decoder/":98,"util":72}],86:[function(require,module,exports){
  10689. // a transform stream is a readable/writable stream where you do
  10690. // something with the data. Sometimes it's called a "filter",
  10691. // but that's not a great name for it, since that implies a thing where
  10692. // some bits pass through, and others are simply ignored. (That would
  10693. // be a valid example of a transform, of course.)
  10694. //
  10695. // While the output is causally related to the input, it's not a
  10696. // necessarily symmetric or synchronous transformation. For example,
  10697. // a zlib stream might take multiple plain-text writes(), and then
  10698. // emit a single compressed chunk some time in the future.
  10699. //
  10700. // Here's how this works:
  10701. //
  10702. // The Transform stream has all the aspects of the readable and writable
  10703. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  10704. // internally, and returns false if there's a lot of pending writes
  10705. // buffered up. When you call read(), that calls _read(n) until
  10706. // there's enough pending readable data buffered up.
  10707. //
  10708. // In a transform stream, the written data is placed in a buffer. When
  10709. // _read(n) is called, it transforms the queued up data, calling the
  10710. // buffered _write cb's as it consumes chunks. If consuming a single
  10711. // written chunk would result in multiple output chunks, then the first
  10712. // outputted bit calls the readcb, and subsequent chunks just go into
  10713. // the read buffer, and will cause it to emit 'readable' if necessary.
  10714. //
  10715. // This way, back-pressure is actually determined by the reading side,
  10716. // since _read has to be called to start processing a new chunk. However,
  10717. // a pathological inflate type of transform can cause excessive buffering
  10718. // here. For example, imagine a stream where every byte of input is
  10719. // interpreted as an integer from 0-255, and then results in that many
  10720. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  10721. // 1kb of data being output. In this case, you could write a very small
  10722. // amount of input, and end up with a very large amount of output. In
  10723. // such a pathological inflating mechanism, there'd be no way to tell
  10724. // the system to stop doing the transform. A single 4MB write could
  10725. // cause the system to run out of memory.
  10726. //
  10727. // However, even in such a pathological case, only a single written chunk
  10728. // would be consumed, and then the rest would wait (un-transformed) until
  10729. // the results of the previous transformed chunk were consumed.
  10730. 'use strict';
  10731. module.exports = Transform;
  10732. var Duplex = require('./_stream_duplex');
  10733. /*<replacement>*/
  10734. var util = require('core-util-is');
  10735. util.inherits = require('inherits');
  10736. /*</replacement>*/
  10737. util.inherits(Transform, Duplex);
  10738. function TransformState(stream) {
  10739. this.afterTransform = function (er, data) {
  10740. return afterTransform(stream, er, data);
  10741. };
  10742. this.needTransform = false;
  10743. this.transforming = false;
  10744. this.writecb = null;
  10745. this.writechunk = null;
  10746. this.writeencoding = null;
  10747. }
  10748. function afterTransform(stream, er, data) {
  10749. var ts = stream._transformState;
  10750. ts.transforming = false;
  10751. var cb = ts.writecb;
  10752. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  10753. ts.writechunk = null;
  10754. ts.writecb = null;
  10755. if (data !== null && data !== undefined) stream.push(data);
  10756. cb(er);
  10757. var rs = stream._readableState;
  10758. rs.reading = false;
  10759. if (rs.needReadable || rs.length < rs.highWaterMark) {
  10760. stream._read(rs.highWaterMark);
  10761. }
  10762. }
  10763. function Transform(options) {
  10764. if (!(this instanceof Transform)) return new Transform(options);
  10765. Duplex.call(this, options);
  10766. this._transformState = new TransformState(this);
  10767. // when the writable side finishes, then flush out anything remaining.
  10768. var stream = this;
  10769. // start out asking for a readable event once data is transformed.
  10770. this._readableState.needReadable = true;
  10771. // we have implemented the _read method, and done the other things
  10772. // that Readable wants before the first _read call, so unset the
  10773. // sync guard flag.
  10774. this._readableState.sync = false;
  10775. if (options) {
  10776. if (typeof options.transform === 'function') this._transform = options.transform;
  10777. if (typeof options.flush === 'function') this._flush = options.flush;
  10778. }
  10779. this.once('prefinish', function () {
  10780. if (typeof this._flush === 'function') this._flush(function (er) {
  10781. done(stream, er);
  10782. });else done(stream);
  10783. });
  10784. }
  10785. Transform.prototype.push = function (chunk, encoding) {
  10786. this._transformState.needTransform = false;
  10787. return Duplex.prototype.push.call(this, chunk, encoding);
  10788. };
  10789. // This is the part where you do stuff!
  10790. // override this function in implementation classes.
  10791. // 'chunk' is an input chunk.
  10792. //
  10793. // Call `push(newChunk)` to pass along transformed output
  10794. // to the readable side. You may call 'push' zero or more times.
  10795. //
  10796. // Call `cb(err)` when you are done with this chunk. If you pass
  10797. // an error, then that'll put the hurt on the whole operation. If you
  10798. // never call cb(), then you'll never get another chunk.
  10799. Transform.prototype._transform = function (chunk, encoding, cb) {
  10800. throw new Error('Not implemented');
  10801. };
  10802. Transform.prototype._write = function (chunk, encoding, cb) {
  10803. var ts = this._transformState;
  10804. ts.writecb = cb;
  10805. ts.writechunk = chunk;
  10806. ts.writeencoding = encoding;
  10807. if (!ts.transforming) {
  10808. var rs = this._readableState;
  10809. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  10810. }
  10811. };
  10812. // Doesn't matter what the args are here.
  10813. // _transform does all the work.
  10814. // That we got here means that the readable side wants more data.
  10815. Transform.prototype._read = function (n) {
  10816. var ts = this._transformState;
  10817. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  10818. ts.transforming = true;
  10819. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  10820. } else {
  10821. // mark that we need a transform, so that any data that comes in
  10822. // will get processed, now that we've asked for it.
  10823. ts.needTransform = true;
  10824. }
  10825. };
  10826. function done(stream, er) {
  10827. if (er) return stream.emit('error', er);
  10828. // if there's nothing in the write buffer, then that means
  10829. // that nothing more will ever be provided
  10830. var ws = stream._writableState;
  10831. var ts = stream._transformState;
  10832. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  10833. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  10834. return stream.push(null);
  10835. }
  10836. },{"./_stream_duplex":83,"core-util-is":89,"inherits":78}],87:[function(require,module,exports){
  10837. (function (process){
  10838. // A bit simpler than readable streams.
  10839. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  10840. // the drain event emission and buffering.
  10841. 'use strict';
  10842. module.exports = Writable;
  10843. /*<replacement>*/
  10844. var processNextTick = require('process-nextick-args');
  10845. /*</replacement>*/
  10846. /*<replacement>*/
  10847. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  10848. /*</replacement>*/
  10849. Writable.WritableState = WritableState;
  10850. /*<replacement>*/
  10851. var util = require('core-util-is');
  10852. util.inherits = require('inherits');
  10853. /*</replacement>*/
  10854. /*<replacement>*/
  10855. var internalUtil = {
  10856. deprecate: require('util-deprecate')
  10857. };
  10858. /*</replacement>*/
  10859. /*<replacement>*/
  10860. var Stream;
  10861. (function () {
  10862. try {
  10863. Stream = require('st' + 'ream');
  10864. } catch (_) {} finally {
  10865. if (!Stream) Stream = require('events').EventEmitter;
  10866. }
  10867. })();
  10868. /*</replacement>*/
  10869. var Buffer = require('buffer').Buffer;
  10870. /*<replacement>*/
  10871. var bufferShim = require('buffer-shims');
  10872. /*</replacement>*/
  10873. util.inherits(Writable, Stream);
  10874. function nop() {}
  10875. function WriteReq(chunk, encoding, cb) {
  10876. this.chunk = chunk;
  10877. this.encoding = encoding;
  10878. this.callback = cb;
  10879. this.next = null;
  10880. }
  10881. var Duplex;
  10882. function WritableState(options, stream) {
  10883. Duplex = Duplex || require('./_stream_duplex');
  10884. options = options || {};
  10885. // object stream flag to indicate whether or not this stream
  10886. // contains buffers or objects.
  10887. this.objectMode = !!options.objectMode;
  10888. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  10889. // the point at which write() starts returning false
  10890. // Note: 0 is a valid value, means that we always return false if
  10891. // the entire buffer is not flushed immediately on write()
  10892. var hwm = options.highWaterMark;
  10893. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  10894. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  10895. // cast to ints.
  10896. this.highWaterMark = ~ ~this.highWaterMark;
  10897. this.needDrain = false;
  10898. // at the start of calling end()
  10899. this.ending = false;
  10900. // when end() has been called, and returned
  10901. this.ended = false;
  10902. // when 'finish' is emitted
  10903. this.finished = false;
  10904. // should we decode strings into buffers before passing to _write?
  10905. // this is here so that some node-core streams can optimize string
  10906. // handling at a lower level.
  10907. var noDecode = options.decodeStrings === false;
  10908. this.decodeStrings = !noDecode;
  10909. // Crypto is kind of old and crusty. Historically, its default string
  10910. // encoding is 'binary' so we have to make this configurable.
  10911. // Everything else in the universe uses 'utf8', though.
  10912. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10913. // not an actual buffer we keep track of, but a measurement
  10914. // of how much we're waiting to get pushed to some underlying
  10915. // socket or file.
  10916. this.length = 0;
  10917. // a flag to see when we're in the middle of a write.
  10918. this.writing = false;
  10919. // when true all writes will be buffered until .uncork() call
  10920. this.corked = 0;
  10921. // a flag to be able to tell if the onwrite cb is called immediately,
  10922. // or on a later tick. We set this to true at first, because any
  10923. // actions that shouldn't happen until "later" should generally also
  10924. // not happen before the first write call.
  10925. this.sync = true;
  10926. // a flag to know if we're processing previously buffered items, which
  10927. // may call the _write() callback in the same tick, so that we don't
  10928. // end up in an overlapped onwrite situation.
  10929. this.bufferProcessing = false;
  10930. // the callback that's passed to _write(chunk,cb)
  10931. this.onwrite = function (er) {
  10932. onwrite(stream, er);
  10933. };
  10934. // the callback that the user supplies to write(chunk,encoding,cb)
  10935. this.writecb = null;
  10936. // the amount that is being written when _write is called.
  10937. this.writelen = 0;
  10938. this.bufferedRequest = null;
  10939. this.lastBufferedRequest = null;
  10940. // number of pending user-supplied write callbacks
  10941. // this must be 0 before 'finish' can be emitted
  10942. this.pendingcb = 0;
  10943. // emit prefinish if the only thing we're waiting for is _write cbs
  10944. // This is relevant for synchronous Transform streams
  10945. this.prefinished = false;
  10946. // True if the error was already emitted and should not be thrown again
  10947. this.errorEmitted = false;
  10948. // count buffered requests
  10949. this.bufferedRequestCount = 0;
  10950. // allocate the first CorkedRequest, there is always
  10951. // one allocated and free to use, and we maintain at most two
  10952. this.corkedRequestsFree = new CorkedRequest(this);
  10953. }
  10954. WritableState.prototype.getBuffer = function writableStateGetBuffer() {
  10955. var current = this.bufferedRequest;
  10956. var out = [];
  10957. while (current) {
  10958. out.push(current);
  10959. current = current.next;
  10960. }
  10961. return out;
  10962. };
  10963. (function () {
  10964. try {
  10965. Object.defineProperty(WritableState.prototype, 'buffer', {
  10966. get: internalUtil.deprecate(function () {
  10967. return this.getBuffer();
  10968. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
  10969. });
  10970. } catch (_) {}
  10971. })();
  10972. var Duplex;
  10973. function Writable(options) {
  10974. Duplex = Duplex || require('./_stream_duplex');
  10975. // Writable ctor is applied to Duplexes, though they're not
  10976. // instanceof Writable, they're instanceof Readable.
  10977. if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
  10978. this._writableState = new WritableState(options, this);
  10979. // legacy.
  10980. this.writable = true;
  10981. if (options) {
  10982. if (typeof options.write === 'function') this._write = options.write;
  10983. if (typeof options.writev === 'function') this._writev = options.writev;
  10984. }
  10985. Stream.call(this);
  10986. }
  10987. // Otherwise people can pipe Writable streams, which is just wrong.
  10988. Writable.prototype.pipe = function () {
  10989. this.emit('error', new Error('Cannot pipe, not readable'));
  10990. };
  10991. function writeAfterEnd(stream, cb) {
  10992. var er = new Error('write after end');
  10993. // TODO: defer error events consistently everywhere, not just the cb
  10994. stream.emit('error', er);
  10995. processNextTick(cb, er);
  10996. }
  10997. // If we get something that is not a buffer, string, null, or undefined,
  10998. // and we're not in objectMode, then that's an error.
  10999. // Otherwise stream chunks are all considered to be of length=1, and the
  11000. // watermarks determine how many objects to keep in the buffer, rather than
  11001. // how many bytes or characters.
  11002. function validChunk(stream, state, chunk, cb) {
  11003. var valid = true;
  11004. var er = false;
  11005. // Always throw error if a null is written
  11006. // if we are not in object mode then throw
  11007. // if it is not a buffer, string, or undefined.
  11008. if (chunk === null) {
  11009. er = new TypeError('May not write null values to stream');
  11010. } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  11011. er = new TypeError('Invalid non-string/buffer chunk');
  11012. }
  11013. if (er) {
  11014. stream.emit('error', er);
  11015. processNextTick(cb, er);
  11016. valid = false;
  11017. }
  11018. return valid;
  11019. }
  11020. Writable.prototype.write = function (chunk, encoding, cb) {
  11021. var state = this._writableState;
  11022. var ret = false;
  11023. if (typeof encoding === 'function') {
  11024. cb = encoding;
  11025. encoding = null;
  11026. }
  11027. if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  11028. if (typeof cb !== 'function') cb = nop;
  11029. if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
  11030. state.pendingcb++;
  11031. ret = writeOrBuffer(this, state, chunk, encoding, cb);
  11032. }
  11033. return ret;
  11034. };
  11035. Writable.prototype.cork = function () {
  11036. var state = this._writableState;
  11037. state.corked++;
  11038. };
  11039. Writable.prototype.uncork = function () {
  11040. var state = this._writableState;
  11041. if (state.corked) {
  11042. state.corked--;
  11043. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  11044. }
  11045. };
  11046. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  11047. // node::ParseEncoding() requires lower case.
  11048. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  11049. 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);
  11050. this._writableState.defaultEncoding = encoding;
  11051. return this;
  11052. };
  11053. function decodeChunk(state, chunk, encoding) {
  11054. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  11055. chunk = bufferShim.from(chunk, encoding);
  11056. }
  11057. return chunk;
  11058. }
  11059. // if we're already writing something, then just put this
  11060. // in the queue, and wait our turn. Otherwise, call _write
  11061. // If we return false, then we need a drain event, so set that flag.
  11062. function writeOrBuffer(stream, state, chunk, encoding, cb) {
  11063. chunk = decodeChunk(state, chunk, encoding);
  11064. if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  11065. var len = state.objectMode ? 1 : chunk.length;
  11066. state.length += len;
  11067. var ret = state.length < state.highWaterMark;
  11068. // we must ensure that previous needDrain will not be reset to false.
  11069. if (!ret) state.needDrain = true;
  11070. if (state.writing || state.corked) {
  11071. var last = state.lastBufferedRequest;
  11072. state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
  11073. if (last) {
  11074. last.next = state.lastBufferedRequest;
  11075. } else {
  11076. state.bufferedRequest = state.lastBufferedRequest;
  11077. }
  11078. state.bufferedRequestCount += 1;
  11079. } else {
  11080. doWrite(stream, state, false, len, chunk, encoding, cb);
  11081. }
  11082. return ret;
  11083. }
  11084. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  11085. state.writelen = len;
  11086. state.writecb = cb;
  11087. state.writing = true;
  11088. state.sync = true;
  11089. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  11090. state.sync = false;
  11091. }
  11092. function onwriteError(stream, state, sync, er, cb) {
  11093. --state.pendingcb;
  11094. if (sync) processNextTick(cb, er);else cb(er);
  11095. stream._writableState.errorEmitted = true;
  11096. stream.emit('error', er);
  11097. }
  11098. function onwriteStateUpdate(state) {
  11099. state.writing = false;
  11100. state.writecb = null;
  11101. state.length -= state.writelen;
  11102. state.writelen = 0;
  11103. }
  11104. function onwrite(stream, er) {
  11105. var state = stream._writableState;
  11106. var sync = state.sync;
  11107. var cb = state.writecb;
  11108. onwriteStateUpdate(state);
  11109. if (er) onwriteError(stream, state, sync, er, cb);else {
  11110. // Check if we're actually ready to finish, but don't emit yet
  11111. var finished = needFinish(state);
  11112. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  11113. clearBuffer(stream, state);
  11114. }
  11115. if (sync) {
  11116. /*<replacement>*/
  11117. asyncWrite(afterWrite, stream, state, finished, cb);
  11118. /*</replacement>*/
  11119. } else {
  11120. afterWrite(stream, state, finished, cb);
  11121. }
  11122. }
  11123. }
  11124. function afterWrite(stream, state, finished, cb) {
  11125. if (!finished) onwriteDrain(stream, state);
  11126. state.pendingcb--;
  11127. cb();
  11128. finishMaybe(stream, state);
  11129. }
  11130. // Must force callback to be called on nextTick, so that we don't
  11131. // emit 'drain' before the write() consumer gets the 'false' return
  11132. // value, and has a chance to attach a 'drain' listener.
  11133. function onwriteDrain(stream, state) {
  11134. if (state.length === 0 && state.needDrain) {
  11135. state.needDrain = false;
  11136. stream.emit('drain');
  11137. }
  11138. }
  11139. // if there's something in the buffer waiting, then process it
  11140. function clearBuffer(stream, state) {
  11141. state.bufferProcessing = true;
  11142. var entry = state.bufferedRequest;
  11143. if (stream._writev && entry && entry.next) {
  11144. // Fast case, write everything using _writev()
  11145. var l = state.bufferedRequestCount;
  11146. var buffer = new Array(l);
  11147. var holder = state.corkedRequestsFree;
  11148. holder.entry = entry;
  11149. var count = 0;
  11150. while (entry) {
  11151. buffer[count] = entry;
  11152. entry = entry.next;
  11153. count += 1;
  11154. }
  11155. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  11156. // doWrite is almost always async, defer these to save a bit of time
  11157. // as the hot path ends with doWrite
  11158. state.pendingcb++;
  11159. state.lastBufferedRequest = null;
  11160. if (holder.next) {
  11161. state.corkedRequestsFree = holder.next;
  11162. holder.next = null;
  11163. } else {
  11164. state.corkedRequestsFree = new CorkedRequest(state);
  11165. }
  11166. } else {
  11167. // Slow case, write chunks one-by-one
  11168. while (entry) {
  11169. var chunk = entry.chunk;
  11170. var encoding = entry.encoding;
  11171. var cb = entry.callback;
  11172. var len = state.objectMode ? 1 : chunk.length;
  11173. doWrite(stream, state, false, len, chunk, encoding, cb);
  11174. entry = entry.next;
  11175. // if we didn't call the onwrite immediately, then
  11176. // it means that we need to wait until it does.
  11177. // also, that means that the chunk and cb are currently
  11178. // being processed, so move the buffer counter past them.
  11179. if (state.writing) {
  11180. break;
  11181. }
  11182. }
  11183. if (entry === null) state.lastBufferedRequest = null;
  11184. }
  11185. state.bufferedRequestCount = 0;
  11186. state.bufferedRequest = entry;
  11187. state.bufferProcessing = false;
  11188. }
  11189. Writable.prototype._write = function (chunk, encoding, cb) {
  11190. cb(new Error('not implemented'));
  11191. };
  11192. Writable.prototype._writev = null;
  11193. Writable.prototype.end = function (chunk, encoding, cb) {
  11194. var state = this._writableState;
  11195. if (typeof chunk === 'function') {
  11196. cb = chunk;
  11197. chunk = null;
  11198. encoding = null;
  11199. } else if (typeof encoding === 'function') {
  11200. cb = encoding;
  11201. encoding = null;
  11202. }
  11203. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  11204. // .end() fully uncorks
  11205. if (state.corked) {
  11206. state.corked = 1;
  11207. this.uncork();
  11208. }
  11209. // ignore unnecessary end() calls.
  11210. if (!state.ending && !state.finished) endWritable(this, state, cb);
  11211. };
  11212. function needFinish(state) {
  11213. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  11214. }
  11215. function prefinish(stream, state) {
  11216. if (!state.prefinished) {
  11217. state.prefinished = true;
  11218. stream.emit('prefinish');
  11219. }
  11220. }
  11221. function finishMaybe(stream, state) {
  11222. var need = needFinish(state);
  11223. if (need) {
  11224. if (state.pendingcb === 0) {
  11225. prefinish(stream, state);
  11226. state.finished = true;
  11227. stream.emit('finish');
  11228. } else {
  11229. prefinish(stream, state);
  11230. }
  11231. }
  11232. return need;
  11233. }
  11234. function endWritable(stream, state, cb) {
  11235. state.ending = true;
  11236. finishMaybe(stream, state);
  11237. if (cb) {
  11238. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  11239. }
  11240. state.ended = true;
  11241. stream.writable = false;
  11242. }
  11243. // It seems a linked list but it is not
  11244. // there will be only 2 of these for each stream
  11245. function CorkedRequest(state) {
  11246. var _this = this;
  11247. this.next = null;
  11248. this.entry = null;
  11249. this.finish = function (err) {
  11250. var entry = _this.entry;
  11251. _this.entry = null;
  11252. while (entry) {
  11253. var cb = entry.callback;
  11254. state.pendingcb--;
  11255. cb(err);
  11256. entry = entry.next;
  11257. }
  11258. if (state.corkedRequestsFree) {
  11259. state.corkedRequestsFree.next = _this;
  11260. } else {
  11261. state.corkedRequestsFree = _this;
  11262. }
  11263. };
  11264. }
  11265. }).call(this,require('_process'))
  11266. },{"./_stream_duplex":83,"_process":81,"buffer":73,"buffer-shims":88,"core-util-is":89,"events":77,"inherits":78,"process-nextick-args":91,"util-deprecate":92}],88:[function(require,module,exports){
  11267. (function (global){
  11268. 'use strict';
  11269. var buffer = require('buffer');
  11270. var Buffer = buffer.Buffer;
  11271. var SlowBuffer = buffer.SlowBuffer;
  11272. var MAX_LEN = buffer.kMaxLength || 2147483647;
  11273. exports.alloc = function alloc(size, fill, encoding) {
  11274. if (typeof Buffer.alloc === 'function') {
  11275. return Buffer.alloc(size, fill, encoding);
  11276. }
  11277. if (typeof encoding === 'number') {
  11278. throw new TypeError('encoding must not be number');
  11279. }
  11280. if (typeof size !== 'number') {
  11281. throw new TypeError('size must be a number');
  11282. }
  11283. if (size > MAX_LEN) {
  11284. throw new RangeError('size is too large');
  11285. }
  11286. var enc = encoding;
  11287. var _fill = fill;
  11288. if (_fill === undefined) {
  11289. enc = undefined;
  11290. _fill = 0;
  11291. }
  11292. var buf = new Buffer(size);
  11293. if (typeof _fill === 'string') {
  11294. var fillBuf = new Buffer(_fill, enc);
  11295. var flen = fillBuf.length;
  11296. var i = -1;
  11297. while (++i < size) {
  11298. buf[i] = fillBuf[i % flen];
  11299. }
  11300. } else {
  11301. buf.fill(_fill);
  11302. }
  11303. return buf;
  11304. }
  11305. exports.allocUnsafe = function allocUnsafe(size) {
  11306. if (typeof Buffer.allocUnsafe === 'function') {
  11307. return Buffer.allocUnsafe(size);
  11308. }
  11309. if (typeof size !== 'number') {
  11310. throw new TypeError('size must be a number');
  11311. }
  11312. if (size > MAX_LEN) {
  11313. throw new RangeError('size is too large');
  11314. }
  11315. return new Buffer(size);
  11316. }
  11317. exports.from = function from(value, encodingOrOffset, length) {
  11318. if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
  11319. return Buffer.from(value, encodingOrOffset, length);
  11320. }
  11321. if (typeof value === 'number') {
  11322. throw new TypeError('"value" argument must not be a number');
  11323. }
  11324. if (typeof value === 'string') {
  11325. return new Buffer(value, encodingOrOffset);
  11326. }
  11327. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  11328. var offset = encodingOrOffset;
  11329. if (arguments.length === 1) {
  11330. return new Buffer(value);
  11331. }
  11332. if (typeof offset === 'undefined') {
  11333. offset = 0;
  11334. }
  11335. var len = length;
  11336. if (typeof len === 'undefined') {
  11337. len = value.byteLength - offset;
  11338. }
  11339. if (offset >= value.byteLength) {
  11340. throw new RangeError('\'offset\' is out of bounds');
  11341. }
  11342. if (len > value.byteLength - offset) {
  11343. throw new RangeError('\'length\' is out of bounds');
  11344. }
  11345. return new Buffer(value.slice(offset, offset + len));
  11346. }
  11347. if (Buffer.isBuffer(value)) {
  11348. var out = new Buffer(value.length);
  11349. value.copy(out, 0, 0, value.length);
  11350. return out;
  11351. }
  11352. if (value) {
  11353. if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
  11354. return new Buffer(value);
  11355. }
  11356. if (value.type === 'Buffer' && Array.isArray(value.data)) {
  11357. return new Buffer(value.data);
  11358. }
  11359. }
  11360. throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
  11361. }
  11362. exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  11363. if (typeof Buffer.allocUnsafeSlow === 'function') {
  11364. return Buffer.allocUnsafeSlow(size);
  11365. }
  11366. if (typeof size !== 'number') {
  11367. throw new TypeError('size must be a number');
  11368. }
  11369. if (size >= MAX_LEN) {
  11370. throw new RangeError('size is too large');
  11371. }
  11372. return new SlowBuffer(size);
  11373. }
  11374. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11375. },{"buffer":73}],89:[function(require,module,exports){
  11376. (function (Buffer){
  11377. // Copyright Joyent, Inc. and other Node contributors.
  11378. //
  11379. // Permission is hereby granted, free of charge, to any person obtaining a
  11380. // copy of this software and associated documentation files (the
  11381. // "Software"), to deal in the Software without restriction, including
  11382. // without limitation the rights to use, copy, modify, merge, publish,
  11383. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11384. // persons to whom the Software is furnished to do so, subject to the
  11385. // following conditions:
  11386. //
  11387. // The above copyright notice and this permission notice shall be included
  11388. // in all copies or substantial portions of the Software.
  11389. //
  11390. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11391. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11392. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11393. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11394. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11395. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11396. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11397. // NOTE: These type checking functions intentionally don't use `instanceof`
  11398. // because it is fragile and can be easily faked with `Object.create()`.
  11399. function isArray(arg) {
  11400. if (Array.isArray) {
  11401. return Array.isArray(arg);
  11402. }
  11403. return objectToString(arg) === '[object Array]';
  11404. }
  11405. exports.isArray = isArray;
  11406. function isBoolean(arg) {
  11407. return typeof arg === 'boolean';
  11408. }
  11409. exports.isBoolean = isBoolean;
  11410. function isNull(arg) {
  11411. return arg === null;
  11412. }
  11413. exports.isNull = isNull;
  11414. function isNullOrUndefined(arg) {
  11415. return arg == null;
  11416. }
  11417. exports.isNullOrUndefined = isNullOrUndefined;
  11418. function isNumber(arg) {
  11419. return typeof arg === 'number';
  11420. }
  11421. exports.isNumber = isNumber;
  11422. function isString(arg) {
  11423. return typeof arg === 'string';
  11424. }
  11425. exports.isString = isString;
  11426. function isSymbol(arg) {
  11427. return typeof arg === 'symbol';
  11428. }
  11429. exports.isSymbol = isSymbol;
  11430. function isUndefined(arg) {
  11431. return arg === void 0;
  11432. }
  11433. exports.isUndefined = isUndefined;
  11434. function isRegExp(re) {
  11435. return objectToString(re) === '[object RegExp]';
  11436. }
  11437. exports.isRegExp = isRegExp;
  11438. function isObject(arg) {
  11439. return typeof arg === 'object' && arg !== null;
  11440. }
  11441. exports.isObject = isObject;
  11442. function isDate(d) {
  11443. return objectToString(d) === '[object Date]';
  11444. }
  11445. exports.isDate = isDate;
  11446. function isError(e) {
  11447. return (objectToString(e) === '[object Error]' || e instanceof Error);
  11448. }
  11449. exports.isError = isError;
  11450. function isFunction(arg) {
  11451. return typeof arg === 'function';
  11452. }
  11453. exports.isFunction = isFunction;
  11454. function isPrimitive(arg) {
  11455. return arg === null ||
  11456. typeof arg === 'boolean' ||
  11457. typeof arg === 'number' ||
  11458. typeof arg === 'string' ||
  11459. typeof arg === 'symbol' || // ES6 symbol
  11460. typeof arg === 'undefined';
  11461. }
  11462. exports.isPrimitive = isPrimitive;
  11463. exports.isBuffer = Buffer.isBuffer;
  11464. function objectToString(o) {
  11465. return Object.prototype.toString.call(o);
  11466. }
  11467. }).call(this,{"isBuffer":require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})
  11468. },{"../../../../insert-module-globals/node_modules/is-buffer/index.js":79}],90:[function(require,module,exports){
  11469. arguments[4][76][0].apply(exports,arguments)
  11470. },{"dup":76}],91:[function(require,module,exports){
  11471. (function (process){
  11472. 'use strict';
  11473. if (!process.version ||
  11474. process.version.indexOf('v0.') === 0 ||
  11475. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  11476. module.exports = nextTick;
  11477. } else {
  11478. module.exports = process.nextTick;
  11479. }
  11480. function nextTick(fn, arg1, arg2, arg3) {
  11481. if (typeof fn !== 'function') {
  11482. throw new TypeError('"callback" argument must be a function');
  11483. }
  11484. var len = arguments.length;
  11485. var args, i;
  11486. switch (len) {
  11487. case 0:
  11488. case 1:
  11489. return process.nextTick(fn);
  11490. case 2:
  11491. return process.nextTick(function afterTickOne() {
  11492. fn.call(null, arg1);
  11493. });
  11494. case 3:
  11495. return process.nextTick(function afterTickTwo() {
  11496. fn.call(null, arg1, arg2);
  11497. });
  11498. case 4:
  11499. return process.nextTick(function afterTickThree() {
  11500. fn.call(null, arg1, arg2, arg3);
  11501. });
  11502. default:
  11503. args = new Array(len - 1);
  11504. i = 0;
  11505. while (i < args.length) {
  11506. args[i++] = arguments[i];
  11507. }
  11508. return process.nextTick(function afterTick() {
  11509. fn.apply(null, args);
  11510. });
  11511. }
  11512. }
  11513. }).call(this,require('_process'))
  11514. },{"_process":81}],92:[function(require,module,exports){
  11515. (function (global){
  11516. /**
  11517. * Module exports.
  11518. */
  11519. module.exports = deprecate;
  11520. /**
  11521. * Mark that a method should not be used.
  11522. * Returns a modified function which warns once by default.
  11523. *
  11524. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  11525. *
  11526. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  11527. * will throw an Error when invoked.
  11528. *
  11529. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  11530. * will invoke `console.trace()` instead of `console.error()`.
  11531. *
  11532. * @param {Function} fn - the function to deprecate
  11533. * @param {String} msg - the string to print to the console when `fn` is invoked
  11534. * @returns {Function} a new "deprecated" version of `fn`
  11535. * @api public
  11536. */
  11537. function deprecate (fn, msg) {
  11538. if (config('noDeprecation')) {
  11539. return fn;
  11540. }
  11541. var warned = false;
  11542. function deprecated() {
  11543. if (!warned) {
  11544. if (config('throwDeprecation')) {
  11545. throw new Error(msg);
  11546. } else if (config('traceDeprecation')) {
  11547. console.trace(msg);
  11548. } else {
  11549. console.warn(msg);
  11550. }
  11551. warned = true;
  11552. }
  11553. return fn.apply(this, arguments);
  11554. }
  11555. return deprecated;
  11556. }
  11557. /**
  11558. * Checks `localStorage` for boolean values for the given `name`.
  11559. *
  11560. * @param {String} name
  11561. * @returns {Boolean}
  11562. * @api private
  11563. */
  11564. function config (name) {
  11565. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  11566. try {
  11567. if (!global.localStorage) return false;
  11568. } catch (_) {
  11569. return false;
  11570. }
  11571. var val = global.localStorage[name];
  11572. if (null == val) return false;
  11573. return String(val).toLowerCase() === 'true';
  11574. }
  11575. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11576. },{}],93:[function(require,module,exports){
  11577. module.exports = require("./lib/_stream_passthrough.js")
  11578. },{"./lib/_stream_passthrough.js":84}],94:[function(require,module,exports){
  11579. (function (process){
  11580. var Stream = (function (){
  11581. try {
  11582. return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
  11583. } catch(_){}
  11584. }());
  11585. exports = module.exports = require('./lib/_stream_readable.js');
  11586. exports.Stream = Stream || exports;
  11587. exports.Readable = exports;
  11588. exports.Writable = require('./lib/_stream_writable.js');
  11589. exports.Duplex = require('./lib/_stream_duplex.js');
  11590. exports.Transform = require('./lib/_stream_transform.js');
  11591. exports.PassThrough = require('./lib/_stream_passthrough.js');
  11592. if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
  11593. module.exports = Stream;
  11594. }
  11595. }).call(this,require('_process'))
  11596. },{"./lib/_stream_duplex.js":83,"./lib/_stream_passthrough.js":84,"./lib/_stream_readable.js":85,"./lib/_stream_transform.js":86,"./lib/_stream_writable.js":87,"_process":81}],95:[function(require,module,exports){
  11597. module.exports = require("./lib/_stream_transform.js")
  11598. },{"./lib/_stream_transform.js":86}],96:[function(require,module,exports){
  11599. module.exports = require("./lib/_stream_writable.js")
  11600. },{"./lib/_stream_writable.js":87}],97:[function(require,module,exports){
  11601. // Copyright Joyent, Inc. and other Node contributors.
  11602. //
  11603. // Permission is hereby granted, free of charge, to any person obtaining a
  11604. // copy of this software and associated documentation files (the
  11605. // "Software"), to deal in the Software without restriction, including
  11606. // without limitation the rights to use, copy, modify, merge, publish,
  11607. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11608. // persons to whom the Software is furnished to do so, subject to the
  11609. // following conditions:
  11610. //
  11611. // The above copyright notice and this permission notice shall be included
  11612. // in all copies or substantial portions of the Software.
  11613. //
  11614. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11615. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11616. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11617. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11618. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11619. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11620. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11621. module.exports = Stream;
  11622. var EE = require('events').EventEmitter;
  11623. var inherits = require('inherits');
  11624. inherits(Stream, EE);
  11625. Stream.Readable = require('readable-stream/readable.js');
  11626. Stream.Writable = require('readable-stream/writable.js');
  11627. Stream.Duplex = require('readable-stream/duplex.js');
  11628. Stream.Transform = require('readable-stream/transform.js');
  11629. Stream.PassThrough = require('readable-stream/passthrough.js');
  11630. // Backwards-compat with node 0.4.x
  11631. Stream.Stream = Stream;
  11632. // old-style streams. Note that the pipe method (the only relevant
  11633. // part of this class) is overridden in the Readable class.
  11634. function Stream() {
  11635. EE.call(this);
  11636. }
  11637. Stream.prototype.pipe = function(dest, options) {
  11638. var source = this;
  11639. function ondata(chunk) {
  11640. if (dest.writable) {
  11641. if (false === dest.write(chunk) && source.pause) {
  11642. source.pause();
  11643. }
  11644. }
  11645. }
  11646. source.on('data', ondata);
  11647. function ondrain() {
  11648. if (source.readable && source.resume) {
  11649. source.resume();
  11650. }
  11651. }
  11652. dest.on('drain', ondrain);
  11653. // If the 'end' option is not supplied, dest.end() will be called when
  11654. // source gets the 'end' or 'close' events. Only dest.end() once.
  11655. if (!dest._isStdio && (!options || options.end !== false)) {
  11656. source.on('end', onend);
  11657. source.on('close', onclose);
  11658. }
  11659. var didOnEnd = false;
  11660. function onend() {
  11661. if (didOnEnd) return;
  11662. didOnEnd = true;
  11663. dest.end();
  11664. }
  11665. function onclose() {
  11666. if (didOnEnd) return;
  11667. didOnEnd = true;
  11668. if (typeof dest.destroy === 'function') dest.destroy();
  11669. }
  11670. // don't leave dangling pipes when there are errors.
  11671. function onerror(er) {
  11672. cleanup();
  11673. if (EE.listenerCount(this, 'error') === 0) {
  11674. throw er; // Unhandled stream error in pipe.
  11675. }
  11676. }
  11677. source.on('error', onerror);
  11678. dest.on('error', onerror);
  11679. // remove all the event listeners that were added.
  11680. function cleanup() {
  11681. source.removeListener('data', ondata);
  11682. dest.removeListener('drain', ondrain);
  11683. source.removeListener('end', onend);
  11684. source.removeListener('close', onclose);
  11685. source.removeListener('error', onerror);
  11686. dest.removeListener('error', onerror);
  11687. source.removeListener('end', cleanup);
  11688. source.removeListener('close', cleanup);
  11689. dest.removeListener('close', cleanup);
  11690. }
  11691. source.on('end', cleanup);
  11692. source.on('close', cleanup);
  11693. dest.on('close', cleanup);
  11694. dest.emit('pipe', source);
  11695. // Allow for unix-like usage: A.pipe(B).pipe(C)
  11696. return dest;
  11697. };
  11698. },{"events":77,"inherits":78,"readable-stream/duplex.js":82,"readable-stream/passthrough.js":93,"readable-stream/readable.js":94,"readable-stream/transform.js":95,"readable-stream/writable.js":96}],98:[function(require,module,exports){
  11699. // Copyright Joyent, Inc. and other Node contributors.
  11700. //
  11701. // Permission is hereby granted, free of charge, to any person obtaining a
  11702. // copy of this software and associated documentation files (the
  11703. // "Software"), to deal in the Software without restriction, including
  11704. // without limitation the rights to use, copy, modify, merge, publish,
  11705. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11706. // persons to whom the Software is furnished to do so, subject to the
  11707. // following conditions:
  11708. //
  11709. // The above copyright notice and this permission notice shall be included
  11710. // in all copies or substantial portions of the Software.
  11711. //
  11712. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11713. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11714. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11715. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11716. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11717. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11718. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11719. var Buffer = require('buffer').Buffer;
  11720. var isBufferEncoding = Buffer.isEncoding
  11721. || function(encoding) {
  11722. switch (encoding && encoding.toLowerCase()) {
  11723. 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': return true;
  11724. default: return false;
  11725. }
  11726. }
  11727. function assertEncoding(encoding) {
  11728. if (encoding && !isBufferEncoding(encoding)) {
  11729. throw new Error('Unknown encoding: ' + encoding);
  11730. }
  11731. }
  11732. // StringDecoder provides an interface for efficiently splitting a series of
  11733. // buffers into a series of JS strings without breaking apart multi-byte
  11734. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  11735. //
  11736. // @TODO Handling all encodings inside a single object makes it very difficult
  11737. // to reason about this code, so it should be split up in the future.
  11738. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  11739. // points as used by CESU-8.
  11740. var StringDecoder = exports.StringDecoder = function(encoding) {
  11741. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  11742. assertEncoding(encoding);
  11743. switch (this.encoding) {
  11744. case 'utf8':
  11745. // CESU-8 represents each of Surrogate Pair by 3-bytes
  11746. this.surrogateSize = 3;
  11747. break;
  11748. case 'ucs2':
  11749. case 'utf16le':
  11750. // UTF-16 represents each of Surrogate Pair by 2-bytes
  11751. this.surrogateSize = 2;
  11752. this.detectIncompleteChar = utf16DetectIncompleteChar;
  11753. break;
  11754. case 'base64':
  11755. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  11756. this.surrogateSize = 3;
  11757. this.detectIncompleteChar = base64DetectIncompleteChar;
  11758. break;
  11759. default:
  11760. this.write = passThroughWrite;
  11761. return;
  11762. }
  11763. // Enough space to store all bytes of a single character. UTF-8 needs 4
  11764. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  11765. this.charBuffer = new Buffer(6);
  11766. // Number of bytes received for the current incomplete multi-byte character.
  11767. this.charReceived = 0;
  11768. // Number of bytes expected for the current incomplete multi-byte character.
  11769. this.charLength = 0;
  11770. };
  11771. // write decodes the given buffer and returns it as JS string that is
  11772. // guaranteed to not contain any partial multi-byte characters. Any partial
  11773. // character found at the end of the buffer is buffered up, and will be
  11774. // returned when calling write again with the remaining bytes.
  11775. //
  11776. // Note: Converting a Buffer containing an orphan surrogate to a String
  11777. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  11778. // Buffer#write) will replace incomplete surrogates with the unicode
  11779. // replacement character. See https://codereview.chromium.org/121173009/ .
  11780. StringDecoder.prototype.write = function(buffer) {
  11781. var charStr = '';
  11782. // if our last write ended with an incomplete multibyte character
  11783. while (this.charLength) {
  11784. // determine how many remaining bytes this buffer has to offer for this char
  11785. var available = (buffer.length >= this.charLength - this.charReceived) ?
  11786. this.charLength - this.charReceived :
  11787. buffer.length;
  11788. // add the new bytes to the char buffer
  11789. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  11790. this.charReceived += available;
  11791. if (this.charReceived < this.charLength) {
  11792. // still not enough chars in this buffer? wait for more ...
  11793. return '';
  11794. }
  11795. // remove bytes belonging to the current character from the buffer
  11796. buffer = buffer.slice(available, buffer.length);
  11797. // get the character that was split
  11798. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  11799. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  11800. var charCode = charStr.charCodeAt(charStr.length - 1);
  11801. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  11802. this.charLength += this.surrogateSize;
  11803. charStr = '';
  11804. continue;
  11805. }
  11806. this.charReceived = this.charLength = 0;
  11807. // if there are no more bytes in this buffer, just emit our char
  11808. if (buffer.length === 0) {
  11809. return charStr;
  11810. }
  11811. break;
  11812. }
  11813. // determine and set charLength / charReceived
  11814. this.detectIncompleteChar(buffer);
  11815. var end = buffer.length;
  11816. if (this.charLength) {
  11817. // buffer the incomplete character bytes we got
  11818. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  11819. end -= this.charReceived;
  11820. }
  11821. charStr += buffer.toString(this.encoding, 0, end);
  11822. var end = charStr.length - 1;
  11823. var charCode = charStr.charCodeAt(end);
  11824. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  11825. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  11826. var size = this.surrogateSize;
  11827. this.charLength += size;
  11828. this.charReceived += size;
  11829. this.charBuffer.copy(this.charBuffer, size, 0, size);
  11830. buffer.copy(this.charBuffer, 0, 0, size);
  11831. return charStr.substring(0, end);
  11832. }
  11833. // or just emit the charStr
  11834. return charStr;
  11835. };
  11836. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  11837. // the end of the given buffer. If so, it sets this.charLength to the byte
  11838. // length that character, and sets this.charReceived to the number of bytes
  11839. // that are available for this character.
  11840. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  11841. // determine how many bytes we have to check at the end of this buffer
  11842. var i = (buffer.length >= 3) ? 3 : buffer.length;
  11843. // Figure out if one of the last i bytes of our buffer announces an
  11844. // incomplete char.
  11845. for (; i > 0; i--) {
  11846. var c = buffer[buffer.length - i];
  11847. // See http://en.wikipedia.org/wiki/UTF-8#Description
  11848. // 110XXXXX
  11849. if (i == 1 && c >> 5 == 0x06) {
  11850. this.charLength = 2;
  11851. break;
  11852. }
  11853. // 1110XXXX
  11854. if (i <= 2 && c >> 4 == 0x0E) {
  11855. this.charLength = 3;
  11856. break;
  11857. }
  11858. // 11110XXX
  11859. if (i <= 3 && c >> 3 == 0x1E) {
  11860. this.charLength = 4;
  11861. break;
  11862. }
  11863. }
  11864. this.charReceived = i;
  11865. };
  11866. StringDecoder.prototype.end = function(buffer) {
  11867. var res = '';
  11868. if (buffer && buffer.length)
  11869. res = this.write(buffer);
  11870. if (this.charReceived) {
  11871. var cr = this.charReceived;
  11872. var buf = this.charBuffer;
  11873. var enc = this.encoding;
  11874. res += buf.slice(0, cr).toString(enc);
  11875. }
  11876. return res;
  11877. };
  11878. function passThroughWrite(buffer) {
  11879. return buffer.toString(this.encoding);
  11880. }
  11881. function utf16DetectIncompleteChar(buffer) {
  11882. this.charReceived = buffer.length % 2;
  11883. this.charLength = this.charReceived ? 2 : 0;
  11884. }
  11885. function base64DetectIncompleteChar(buffer) {
  11886. this.charReceived = buffer.length % 3;
  11887. this.charLength = this.charReceived ? 3 : 0;
  11888. }
  11889. },{"buffer":73}],99:[function(require,module,exports){
  11890. module.exports = function isBuffer(arg) {
  11891. return arg && typeof arg === 'object'
  11892. && typeof arg.copy === 'function'
  11893. && typeof arg.fill === 'function'
  11894. && typeof arg.readUInt8 === 'function';
  11895. }
  11896. },{}],100:[function(require,module,exports){
  11897. (function (process,global){
  11898. // Copyright Joyent, Inc. and other Node contributors.
  11899. //
  11900. // Permission is hereby granted, free of charge, to any person obtaining a
  11901. // copy of this software and associated documentation files (the
  11902. // "Software"), to deal in the Software without restriction, including
  11903. // without limitation the rights to use, copy, modify, merge, publish,
  11904. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11905. // persons to whom the Software is furnished to do so, subject to the
  11906. // following conditions:
  11907. //
  11908. // The above copyright notice and this permission notice shall be included
  11909. // in all copies or substantial portions of the Software.
  11910. //
  11911. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11912. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11913. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11914. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11915. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11916. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11917. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11918. var formatRegExp = /%[sdj%]/g;
  11919. exports.format = function(f) {
  11920. if (!isString(f)) {
  11921. var objects = [];
  11922. for (var i = 0; i < arguments.length; i++) {
  11923. objects.push(inspect(arguments[i]));
  11924. }
  11925. return objects.join(' ');
  11926. }
  11927. var i = 1;
  11928. var args = arguments;
  11929. var len = args.length;
  11930. var str = String(f).replace(formatRegExp, function(x) {
  11931. if (x === '%%') return '%';
  11932. if (i >= len) return x;
  11933. switch (x) {
  11934. case '%s': return String(args[i++]);
  11935. case '%d': return Number(args[i++]);
  11936. case '%j':
  11937. try {
  11938. return JSON.stringify(args[i++]);
  11939. } catch (_) {
  11940. return '[Circular]';
  11941. }
  11942. default:
  11943. return x;
  11944. }
  11945. });
  11946. for (var x = args[i]; i < len; x = args[++i]) {
  11947. if (isNull(x) || !isObject(x)) {
  11948. str += ' ' + x;
  11949. } else {
  11950. str += ' ' + inspect(x);
  11951. }
  11952. }
  11953. return str;
  11954. };
  11955. // Mark that a method should not be used.
  11956. // Returns a modified function which warns once by default.
  11957. // If --no-deprecation is set, then it is a no-op.
  11958. exports.deprecate = function(fn, msg) {
  11959. // Allow for deprecating things in the process of starting up.
  11960. if (isUndefined(global.process)) {
  11961. return function() {
  11962. return exports.deprecate(fn, msg).apply(this, arguments);
  11963. };
  11964. }
  11965. if (process.noDeprecation === true) {
  11966. return fn;
  11967. }
  11968. var warned = false;
  11969. function deprecated() {
  11970. if (!warned) {
  11971. if (process.throwDeprecation) {
  11972. throw new Error(msg);
  11973. } else if (process.traceDeprecation) {
  11974. console.trace(msg);
  11975. } else {
  11976. console.error(msg);
  11977. }
  11978. warned = true;
  11979. }
  11980. return fn.apply(this, arguments);
  11981. }
  11982. return deprecated;
  11983. };
  11984. var debugs = {};
  11985. var debugEnviron;
  11986. exports.debuglog = function(set) {
  11987. if (isUndefined(debugEnviron))
  11988. debugEnviron = process.env.NODE_DEBUG || '';
  11989. set = set.toUpperCase();
  11990. if (!debugs[set]) {
  11991. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  11992. var pid = process.pid;
  11993. debugs[set] = function() {
  11994. var msg = exports.format.apply(exports, arguments);
  11995. console.error('%s %d: %s', set, pid, msg);
  11996. };
  11997. } else {
  11998. debugs[set] = function() {};
  11999. }
  12000. }
  12001. return debugs[set];
  12002. };
  12003. /**
  12004. * Echos the value of a value. Trys to print the value out
  12005. * in the best way possible given the different types.
  12006. *
  12007. * @param {Object} obj The object to print out.
  12008. * @param {Object} opts Optional options object that alters the output.
  12009. */
  12010. /* legacy: obj, showHidden, depth, colors*/
  12011. function inspect(obj, opts) {
  12012. // default options
  12013. var ctx = {
  12014. seen: [],
  12015. stylize: stylizeNoColor
  12016. };
  12017. // legacy...
  12018. if (arguments.length >= 3) ctx.depth = arguments[2];
  12019. if (arguments.length >= 4) ctx.colors = arguments[3];
  12020. if (isBoolean(opts)) {
  12021. // legacy...
  12022. ctx.showHidden = opts;
  12023. } else if (opts) {
  12024. // got an "options" object
  12025. exports._extend(ctx, opts);
  12026. }
  12027. // set default options
  12028. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  12029. if (isUndefined(ctx.depth)) ctx.depth = 2;
  12030. if (isUndefined(ctx.colors)) ctx.colors = false;
  12031. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  12032. if (ctx.colors) ctx.stylize = stylizeWithColor;
  12033. return formatValue(ctx, obj, ctx.depth);
  12034. }
  12035. exports.inspect = inspect;
  12036. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  12037. inspect.colors = {
  12038. 'bold' : [1, 22],
  12039. 'italic' : [3, 23],
  12040. 'underline' : [4, 24],
  12041. 'inverse' : [7, 27],
  12042. 'white' : [37, 39],
  12043. 'grey' : [90, 39],
  12044. 'black' : [30, 39],
  12045. 'blue' : [34, 39],
  12046. 'cyan' : [36, 39],
  12047. 'green' : [32, 39],
  12048. 'magenta' : [35, 39],
  12049. 'red' : [31, 39],
  12050. 'yellow' : [33, 39]
  12051. };
  12052. // Don't use 'blue' not visible on cmd.exe
  12053. inspect.styles = {
  12054. 'special': 'cyan',
  12055. 'number': 'yellow',
  12056. 'boolean': 'yellow',
  12057. 'undefined': 'grey',
  12058. 'null': 'bold',
  12059. 'string': 'green',
  12060. 'date': 'magenta',
  12061. // "name": intentionally not styling
  12062. 'regexp': 'red'
  12063. };
  12064. function stylizeWithColor(str, styleType) {
  12065. var style = inspect.styles[styleType];
  12066. if (style) {
  12067. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  12068. '\u001b[' + inspect.colors[style][1] + 'm';
  12069. } else {
  12070. return str;
  12071. }
  12072. }
  12073. function stylizeNoColor(str, styleType) {
  12074. return str;
  12075. }
  12076. function arrayToHash(array) {
  12077. var hash = {};
  12078. array.forEach(function(val, idx) {
  12079. hash[val] = true;
  12080. });
  12081. return hash;
  12082. }
  12083. function formatValue(ctx, value, recurseTimes) {
  12084. // Provide a hook for user-specified inspect functions.
  12085. // Check that value is an object with an inspect function on it
  12086. if (ctx.customInspect &&
  12087. value &&
  12088. isFunction(value.inspect) &&
  12089. // Filter out the util module, it's inspect function is special
  12090. value.inspect !== exports.inspect &&
  12091. // Also filter out any prototype objects using the circular check.
  12092. !(value.constructor && value.constructor.prototype === value)) {
  12093. var ret = value.inspect(recurseTimes, ctx);
  12094. if (!isString(ret)) {
  12095. ret = formatValue(ctx, ret, recurseTimes);
  12096. }
  12097. return ret;
  12098. }
  12099. // Primitive types cannot have properties
  12100. var primitive = formatPrimitive(ctx, value);
  12101. if (primitive) {
  12102. return primitive;
  12103. }
  12104. // Look up the keys of the object.
  12105. var keys = Object.keys(value);
  12106. var visibleKeys = arrayToHash(keys);
  12107. if (ctx.showHidden) {
  12108. keys = Object.getOwnPropertyNames(value);
  12109. }
  12110. // IE doesn't make error fields non-enumerable
  12111. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  12112. if (isError(value)
  12113. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  12114. return formatError(value);
  12115. }
  12116. // Some type of object without properties can be shortcutted.
  12117. if (keys.length === 0) {
  12118. if (isFunction(value)) {
  12119. var name = value.name ? ': ' + value.name : '';
  12120. return ctx.stylize('[Function' + name + ']', 'special');
  12121. }
  12122. if (isRegExp(value)) {
  12123. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12124. }
  12125. if (isDate(value)) {
  12126. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  12127. }
  12128. if (isError(value)) {
  12129. return formatError(value);
  12130. }
  12131. }
  12132. var base = '', array = false, braces = ['{', '}'];
  12133. // Make Array say that they are Array
  12134. if (isArray(value)) {
  12135. array = true;
  12136. braces = ['[', ']'];
  12137. }
  12138. // Make functions say that they are functions
  12139. if (isFunction(value)) {
  12140. var n = value.name ? ': ' + value.name : '';
  12141. base = ' [Function' + n + ']';
  12142. }
  12143. // Make RegExps say that they are RegExps
  12144. if (isRegExp(value)) {
  12145. base = ' ' + RegExp.prototype.toString.call(value);
  12146. }
  12147. // Make dates with properties first say the date
  12148. if (isDate(value)) {
  12149. base = ' ' + Date.prototype.toUTCString.call(value);
  12150. }
  12151. // Make error with message first say the error
  12152. if (isError(value)) {
  12153. base = ' ' + formatError(value);
  12154. }
  12155. if (keys.length === 0 && (!array || value.length == 0)) {
  12156. return braces[0] + base + braces[1];
  12157. }
  12158. if (recurseTimes < 0) {
  12159. if (isRegExp(value)) {
  12160. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  12161. } else {
  12162. return ctx.stylize('[Object]', 'special');
  12163. }
  12164. }
  12165. ctx.seen.push(value);
  12166. var output;
  12167. if (array) {
  12168. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  12169. } else {
  12170. output = keys.map(function(key) {
  12171. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  12172. });
  12173. }
  12174. ctx.seen.pop();
  12175. return reduceToSingleString(output, base, braces);
  12176. }
  12177. function formatPrimitive(ctx, value) {
  12178. if (isUndefined(value))
  12179. return ctx.stylize('undefined', 'undefined');
  12180. if (isString(value)) {
  12181. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  12182. .replace(/'/g, "\\'")
  12183. .replace(/\\"/g, '"') + '\'';
  12184. return ctx.stylize(simple, 'string');
  12185. }
  12186. if (isNumber(value))
  12187. return ctx.stylize('' + value, 'number');
  12188. if (isBoolean(value))
  12189. return ctx.stylize('' + value, 'boolean');
  12190. // For some reason typeof null is "object", so special case here.
  12191. if (isNull(value))
  12192. return ctx.stylize('null', 'null');
  12193. }
  12194. function formatError(value) {
  12195. return '[' + Error.prototype.toString.call(value) + ']';
  12196. }
  12197. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  12198. var output = [];
  12199. for (var i = 0, l = value.length; i < l; ++i) {
  12200. if (hasOwnProperty(value, String(i))) {
  12201. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12202. String(i), true));
  12203. } else {
  12204. output.push('');
  12205. }
  12206. }
  12207. keys.forEach(function(key) {
  12208. if (!key.match(/^\d+$/)) {
  12209. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  12210. key, true));
  12211. }
  12212. });
  12213. return output;
  12214. }
  12215. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  12216. var name, str, desc;
  12217. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  12218. if (desc.get) {
  12219. if (desc.set) {
  12220. str = ctx.stylize('[Getter/Setter]', 'special');
  12221. } else {
  12222. str = ctx.stylize('[Getter]', 'special');
  12223. }
  12224. } else {
  12225. if (desc.set) {
  12226. str = ctx.stylize('[Setter]', 'special');
  12227. }
  12228. }
  12229. if (!hasOwnProperty(visibleKeys, key)) {
  12230. name = '[' + key + ']';
  12231. }
  12232. if (!str) {
  12233. if (ctx.seen.indexOf(desc.value) < 0) {
  12234. if (isNull(recurseTimes)) {
  12235. str = formatValue(ctx, desc.value, null);
  12236. } else {
  12237. str = formatValue(ctx, desc.value, recurseTimes - 1);
  12238. }
  12239. if (str.indexOf('\n') > -1) {
  12240. if (array) {
  12241. str = str.split('\n').map(function(line) {
  12242. return ' ' + line;
  12243. }).join('\n').substr(2);
  12244. } else {
  12245. str = '\n' + str.split('\n').map(function(line) {
  12246. return ' ' + line;
  12247. }).join('\n');
  12248. }
  12249. }
  12250. } else {
  12251. str = ctx.stylize('[Circular]', 'special');
  12252. }
  12253. }
  12254. if (isUndefined(name)) {
  12255. if (array && key.match(/^\d+$/)) {
  12256. return str;
  12257. }
  12258. name = JSON.stringify('' + key);
  12259. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  12260. name = name.substr(1, name.length - 2);
  12261. name = ctx.stylize(name, 'name');
  12262. } else {
  12263. name = name.replace(/'/g, "\\'")
  12264. .replace(/\\"/g, '"')
  12265. .replace(/(^"|"$)/g, "'");
  12266. name = ctx.stylize(name, 'string');
  12267. }
  12268. }
  12269. return name + ': ' + str;
  12270. }
  12271. function reduceToSingleString(output, base, braces) {
  12272. var numLinesEst = 0;
  12273. var length = output.reduce(function(prev, cur) {
  12274. numLinesEst++;
  12275. if (cur.indexOf('\n') >= 0) numLinesEst++;
  12276. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  12277. }, 0);
  12278. if (length > 60) {
  12279. return braces[0] +
  12280. (base === '' ? '' : base + '\n ') +
  12281. ' ' +
  12282. output.join(',\n ') +
  12283. ' ' +
  12284. braces[1];
  12285. }
  12286. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  12287. }
  12288. // NOTE: These type checking functions intentionally don't use `instanceof`
  12289. // because it is fragile and can be easily faked with `Object.create()`.
  12290. function isArray(ar) {
  12291. return Array.isArray(ar);
  12292. }
  12293. exports.isArray = isArray;
  12294. function isBoolean(arg) {
  12295. return typeof arg === 'boolean';
  12296. }
  12297. exports.isBoolean = isBoolean;
  12298. function isNull(arg) {
  12299. return arg === null;
  12300. }
  12301. exports.isNull = isNull;
  12302. function isNullOrUndefined(arg) {
  12303. return arg == null;
  12304. }
  12305. exports.isNullOrUndefined = isNullOrUndefined;
  12306. function isNumber(arg) {
  12307. return typeof arg === 'number';
  12308. }
  12309. exports.isNumber = isNumber;
  12310. function isString(arg) {
  12311. return typeof arg === 'string';
  12312. }
  12313. exports.isString = isString;
  12314. function isSymbol(arg) {
  12315. return typeof arg === 'symbol';
  12316. }
  12317. exports.isSymbol = isSymbol;
  12318. function isUndefined(arg) {
  12319. return arg === void 0;
  12320. }
  12321. exports.isUndefined = isUndefined;
  12322. function isRegExp(re) {
  12323. return isObject(re) && objectToString(re) === '[object RegExp]';
  12324. }
  12325. exports.isRegExp = isRegExp;
  12326. function isObject(arg) {
  12327. return typeof arg === 'object' && arg !== null;
  12328. }
  12329. exports.isObject = isObject;
  12330. function isDate(d) {
  12331. return isObject(d) && objectToString(d) === '[object Date]';
  12332. }
  12333. exports.isDate = isDate;
  12334. function isError(e) {
  12335. return isObject(e) &&
  12336. (objectToString(e) === '[object Error]' || e instanceof Error);
  12337. }
  12338. exports.isError = isError;
  12339. function isFunction(arg) {
  12340. return typeof arg === 'function';
  12341. }
  12342. exports.isFunction = isFunction;
  12343. function isPrimitive(arg) {
  12344. return arg === null ||
  12345. typeof arg === 'boolean' ||
  12346. typeof arg === 'number' ||
  12347. typeof arg === 'string' ||
  12348. typeof arg === 'symbol' || // ES6 symbol
  12349. typeof arg === 'undefined';
  12350. }
  12351. exports.isPrimitive = isPrimitive;
  12352. exports.isBuffer = require('./support/isBuffer');
  12353. function objectToString(o) {
  12354. return Object.prototype.toString.call(o);
  12355. }
  12356. function pad(n) {
  12357. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  12358. }
  12359. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  12360. 'Oct', 'Nov', 'Dec'];
  12361. // 26 Feb 16:19:34
  12362. function timestamp() {
  12363. var d = new Date();
  12364. var time = [pad(d.getHours()),
  12365. pad(d.getMinutes()),
  12366. pad(d.getSeconds())].join(':');
  12367. return [d.getDate(), months[d.getMonth()], time].join(' ');
  12368. }
  12369. // log is just a thin wrapper to console.log that prepends a timestamp
  12370. exports.log = function() {
  12371. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  12372. };
  12373. /**
  12374. * Inherit the prototype methods from one constructor into another.
  12375. *
  12376. * The Function.prototype.inherits from lang.js rewritten as a standalone
  12377. * function (not on Function.prototype). NOTE: If this file is to be loaded
  12378. * during bootstrapping this function needs to be rewritten using some native
  12379. * functions as prototype setup using normal JavaScript does not work as
  12380. * expected during bootstrapping (see mirror.js in r114903).
  12381. *
  12382. * @param {function} ctor Constructor function which needs to inherit the
  12383. * prototype.
  12384. * @param {function} superCtor Constructor function to inherit prototype from.
  12385. */
  12386. exports.inherits = require('inherits');
  12387. exports._extend = function(origin, add) {
  12388. // Don't do anything if add isn't an object
  12389. if (!add || !isObject(add)) return origin;
  12390. var keys = Object.keys(add);
  12391. var i = keys.length;
  12392. while (i--) {
  12393. origin[keys[i]] = add[keys[i]];
  12394. }
  12395. return origin;
  12396. };
  12397. function hasOwnProperty(obj, prop) {
  12398. return Object.prototype.hasOwnProperty.call(obj, prop);
  12399. }
  12400. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12401. },{"./support/isBuffer":99,"_process":81,"inherits":78}],101:[function(require,module,exports){
  12402. 'use strict';
  12403. // private property
  12404. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  12405. // public method for encoding
  12406. exports.encode = function(input, utf8) {
  12407. var output = "";
  12408. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  12409. var i = 0;
  12410. while (i < input.length) {
  12411. chr1 = input.charCodeAt(i++);
  12412. chr2 = input.charCodeAt(i++);
  12413. chr3 = input.charCodeAt(i++);
  12414. enc1 = chr1 >> 2;
  12415. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  12416. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  12417. enc4 = chr3 & 63;
  12418. if (isNaN(chr2)) {
  12419. enc3 = enc4 = 64;
  12420. }
  12421. else if (isNaN(chr3)) {
  12422. enc4 = 64;
  12423. }
  12424. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  12425. }
  12426. return output;
  12427. };
  12428. // public method for decoding
  12429. exports.decode = function(input, utf8) {
  12430. var output = "";
  12431. var chr1, chr2, chr3;
  12432. var enc1, enc2, enc3, enc4;
  12433. var i = 0;
  12434. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  12435. while (i < input.length) {
  12436. enc1 = _keyStr.indexOf(input.charAt(i++));
  12437. enc2 = _keyStr.indexOf(input.charAt(i++));
  12438. enc3 = _keyStr.indexOf(input.charAt(i++));
  12439. enc4 = _keyStr.indexOf(input.charAt(i++));
  12440. chr1 = (enc1 << 2) | (enc2 >> 4);
  12441. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  12442. chr3 = ((enc3 & 3) << 6) | enc4;
  12443. output = output + String.fromCharCode(chr1);
  12444. if (enc3 != 64) {
  12445. output = output + String.fromCharCode(chr2);
  12446. }
  12447. if (enc4 != 64) {
  12448. output = output + String.fromCharCode(chr3);
  12449. }
  12450. }
  12451. return output;
  12452. };
  12453. },{}],102:[function(require,module,exports){
  12454. 'use strict';
  12455. function CompressedObject() {
  12456. this.compressedSize = 0;
  12457. this.uncompressedSize = 0;
  12458. this.crc32 = 0;
  12459. this.compressionMethod = null;
  12460. this.compressedContent = null;
  12461. }
  12462. CompressedObject.prototype = {
  12463. /**
  12464. * Return the decompressed content in an unspecified format.
  12465. * The format will depend on the decompressor.
  12466. * @return {Object} the decompressed content.
  12467. */
  12468. getContent: function() {
  12469. return null; // see implementation
  12470. },
  12471. /**
  12472. * Return the compressed content in an unspecified format.
  12473. * The format will depend on the compressed conten source.
  12474. * @return {Object} the compressed content.
  12475. */
  12476. getCompressedContent: function() {
  12477. return null; // see implementation
  12478. }
  12479. };
  12480. module.exports = CompressedObject;
  12481. },{}],103:[function(require,module,exports){
  12482. 'use strict';
  12483. exports.STORE = {
  12484. magic: "\x00\x00",
  12485. compress: function(content, compressionOptions) {
  12486. return content; // no compression
  12487. },
  12488. uncompress: function(content) {
  12489. return content; // no compression
  12490. },
  12491. compressInputType: null,
  12492. uncompressInputType: null
  12493. };
  12494. exports.DEFLATE = require('./flate');
  12495. },{"./flate":108}],104:[function(require,module,exports){
  12496. 'use strict';
  12497. var utils = require('./utils');
  12498. var table = [
  12499. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  12500. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  12501. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  12502. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  12503. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  12504. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  12505. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  12506. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  12507. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  12508. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  12509. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  12510. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  12511. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  12512. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  12513. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  12514. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  12515. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  12516. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  12517. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  12518. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  12519. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  12520. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  12521. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  12522. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  12523. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  12524. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  12525. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  12526. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  12527. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  12528. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  12529. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  12530. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  12531. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  12532. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  12533. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  12534. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  12535. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  12536. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  12537. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  12538. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  12539. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  12540. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  12541. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  12542. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  12543. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  12544. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  12545. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  12546. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  12547. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  12548. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  12549. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  12550. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  12551. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  12552. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  12553. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  12554. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  12555. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  12556. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  12557. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  12558. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  12559. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  12560. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  12561. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  12562. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  12563. ];
  12564. /**
  12565. *
  12566. * Javascript crc32
  12567. * http://www.webtoolkit.info/
  12568. *
  12569. */
  12570. module.exports = function crc32(input, crc) {
  12571. if (typeof input === "undefined" || !input.length) {
  12572. return 0;
  12573. }
  12574. var isArray = utils.getTypeOf(input) !== "string";
  12575. if (typeof(crc) == "undefined") {
  12576. crc = 0;
  12577. }
  12578. var x = 0;
  12579. var y = 0;
  12580. var b = 0;
  12581. crc = crc ^ (-1);
  12582. for (var i = 0, iTop = input.length; i < iTop; i++) {
  12583. b = isArray ? input[i] : input.charCodeAt(i);
  12584. y = (crc ^ b) & 0xFF;
  12585. x = table[y];
  12586. crc = (crc >>> 8) ^ x;
  12587. }
  12588. return crc ^ (-1);
  12589. };
  12590. // vim: set shiftwidth=4 softtabstop=4:
  12591. },{"./utils":121}],105:[function(require,module,exports){
  12592. 'use strict';
  12593. var utils = require('./utils');
  12594. function DataReader(data) {
  12595. this.data = null; // type : see implementation
  12596. this.length = 0;
  12597. this.index = 0;
  12598. }
  12599. DataReader.prototype = {
  12600. /**
  12601. * Check that the offset will not go too far.
  12602. * @param {string} offset the additional offset to check.
  12603. * @throws {Error} an Error if the offset is out of bounds.
  12604. */
  12605. checkOffset: function(offset) {
  12606. this.checkIndex(this.index + offset);
  12607. },
  12608. /**
  12609. * Check that the specifed index will not be too far.
  12610. * @param {string} newIndex the index to check.
  12611. * @throws {Error} an Error if the index is out of bounds.
  12612. */
  12613. checkIndex: function(newIndex) {
  12614. if (this.length < newIndex || newIndex < 0) {
  12615. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  12616. }
  12617. },
  12618. /**
  12619. * Change the index.
  12620. * @param {number} newIndex The new index.
  12621. * @throws {Error} if the new index is out of the data.
  12622. */
  12623. setIndex: function(newIndex) {
  12624. this.checkIndex(newIndex);
  12625. this.index = newIndex;
  12626. },
  12627. /**
  12628. * Skip the next n bytes.
  12629. * @param {number} n the number of bytes to skip.
  12630. * @throws {Error} if the new index is out of the data.
  12631. */
  12632. skip: function(n) {
  12633. this.setIndex(this.index + n);
  12634. },
  12635. /**
  12636. * Get the byte at the specified index.
  12637. * @param {number} i the index to use.
  12638. * @return {number} a byte.
  12639. */
  12640. byteAt: function(i) {
  12641. // see implementations
  12642. },
  12643. /**
  12644. * Get the next number with a given byte size.
  12645. * @param {number} size the number of bytes to read.
  12646. * @return {number} the corresponding number.
  12647. */
  12648. readInt: function(size) {
  12649. var result = 0,
  12650. i;
  12651. this.checkOffset(size);
  12652. for (i = this.index + size - 1; i >= this.index; i--) {
  12653. result = (result << 8) + this.byteAt(i);
  12654. }
  12655. this.index += size;
  12656. return result;
  12657. },
  12658. /**
  12659. * Get the next string with a given byte size.
  12660. * @param {number} size the number of bytes to read.
  12661. * @return {string} the corresponding string.
  12662. */
  12663. readString: function(size) {
  12664. return utils.transformTo("string", this.readData(size));
  12665. },
  12666. /**
  12667. * Get raw data without conversion, <size> bytes.
  12668. * @param {number} size the number of bytes to read.
  12669. * @return {Object} the raw data, implementation specific.
  12670. */
  12671. readData: function(size) {
  12672. // see implementations
  12673. },
  12674. /**
  12675. * Find the last occurence of a zip signature (4 bytes).
  12676. * @param {string} sig the signature to find.
  12677. * @return {number} the index of the last occurence, -1 if not found.
  12678. */
  12679. lastIndexOfSignature: function(sig) {
  12680. // see implementations
  12681. },
  12682. /**
  12683. * Get the next date.
  12684. * @return {Date} the date.
  12685. */
  12686. readDate: function() {
  12687. var dostime = this.readInt(4);
  12688. return new Date(
  12689. ((dostime >> 25) & 0x7f) + 1980, // year
  12690. ((dostime >> 21) & 0x0f) - 1, // month
  12691. (dostime >> 16) & 0x1f, // day
  12692. (dostime >> 11) & 0x1f, // hour
  12693. (dostime >> 5) & 0x3f, // minute
  12694. (dostime & 0x1f) << 1); // second
  12695. }
  12696. };
  12697. module.exports = DataReader;
  12698. },{"./utils":121}],106:[function(require,module,exports){
  12699. 'use strict';
  12700. exports.base64 = false;
  12701. exports.binary = false;
  12702. exports.dir = false;
  12703. exports.createFolders = false;
  12704. exports.date = null;
  12705. exports.compression = null;
  12706. exports.compressionOptions = null;
  12707. exports.comment = null;
  12708. exports.unixPermissions = null;
  12709. exports.dosPermissions = null;
  12710. },{}],107:[function(require,module,exports){
  12711. 'use strict';
  12712. var utils = require('./utils');
  12713. /**
  12714. * @deprecated
  12715. * This function will be removed in a future version without replacement.
  12716. */
  12717. exports.string2binary = function(str) {
  12718. return utils.string2binary(str);
  12719. };
  12720. /**
  12721. * @deprecated
  12722. * This function will be removed in a future version without replacement.
  12723. */
  12724. exports.string2Uint8Array = function(str) {
  12725. return utils.transformTo("uint8array", str);
  12726. };
  12727. /**
  12728. * @deprecated
  12729. * This function will be removed in a future version without replacement.
  12730. */
  12731. exports.uint8Array2String = function(array) {
  12732. return utils.transformTo("string", array);
  12733. };
  12734. /**
  12735. * @deprecated
  12736. * This function will be removed in a future version without replacement.
  12737. */
  12738. exports.string2Blob = function(str) {
  12739. var buffer = utils.transformTo("arraybuffer", str);
  12740. return utils.arrayBuffer2Blob(buffer);
  12741. };
  12742. /**
  12743. * @deprecated
  12744. * This function will be removed in a future version without replacement.
  12745. */
  12746. exports.arrayBuffer2Blob = function(buffer) {
  12747. return utils.arrayBuffer2Blob(buffer);
  12748. };
  12749. /**
  12750. * @deprecated
  12751. * This function will be removed in a future version without replacement.
  12752. */
  12753. exports.transformTo = function(outputType, input) {
  12754. return utils.transformTo(outputType, input);
  12755. };
  12756. /**
  12757. * @deprecated
  12758. * This function will be removed in a future version without replacement.
  12759. */
  12760. exports.getTypeOf = function(input) {
  12761. return utils.getTypeOf(input);
  12762. };
  12763. /**
  12764. * @deprecated
  12765. * This function will be removed in a future version without replacement.
  12766. */
  12767. exports.checkSupport = function(type) {
  12768. return utils.checkSupport(type);
  12769. };
  12770. /**
  12771. * @deprecated
  12772. * This value will be removed in a future version without replacement.
  12773. */
  12774. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  12775. /**
  12776. * @deprecated
  12777. * This value will be removed in a future version without replacement.
  12778. */
  12779. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  12780. /**
  12781. * @deprecated
  12782. * This function will be removed in a future version without replacement.
  12783. */
  12784. exports.pretty = function(str) {
  12785. return utils.pretty(str);
  12786. };
  12787. /**
  12788. * @deprecated
  12789. * This function will be removed in a future version without replacement.
  12790. */
  12791. exports.findCompression = function(compressionMethod) {
  12792. return utils.findCompression(compressionMethod);
  12793. };
  12794. /**
  12795. * @deprecated
  12796. * This function will be removed in a future version without replacement.
  12797. */
  12798. exports.isRegExp = function (object) {
  12799. return utils.isRegExp(object);
  12800. };
  12801. },{"./utils":121}],108:[function(require,module,exports){
  12802. 'use strict';
  12803. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  12804. var pako = require("pako");
  12805. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  12806. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  12807. exports.magic = "\x08\x00";
  12808. exports.compress = function(input, compressionOptions) {
  12809. return pako.deflateRaw(input, {
  12810. level : compressionOptions.level || -1 // default compression
  12811. });
  12812. };
  12813. exports.uncompress = function(input) {
  12814. return pako.inflateRaw(input);
  12815. };
  12816. },{"pako":124}],109:[function(require,module,exports){
  12817. 'use strict';
  12818. var base64 = require('./base64');
  12819. /**
  12820. Usage:
  12821. zip = new JSZip();
  12822. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  12823. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  12824. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  12825. zip.remove("tempfile");
  12826. base64zip = zip.generate();
  12827. **/
  12828. /**
  12829. * Representation a of zip file in js
  12830. * @constructor
  12831. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  12832. * @param {Object=} options the options for creating this objects (optional).
  12833. */
  12834. function JSZip(data, options) {
  12835. // if this constructor is used without `new`, it adds `new` before itself:
  12836. if(!(this instanceof JSZip)) return new JSZip(data, options);
  12837. // object containing the files :
  12838. // {
  12839. // "folder/" : {...},
  12840. // "folder/data.txt" : {...}
  12841. // }
  12842. this.files = {};
  12843. this.comment = null;
  12844. // Where we are in the hierarchy
  12845. this.root = "";
  12846. if (data) {
  12847. this.load(data, options);
  12848. }
  12849. this.clone = function() {
  12850. var newObj = new JSZip();
  12851. for (var i in this) {
  12852. if (typeof this[i] !== "function") {
  12853. newObj[i] = this[i];
  12854. }
  12855. }
  12856. return newObj;
  12857. };
  12858. }
  12859. JSZip.prototype = require('./object');
  12860. JSZip.prototype.load = require('./load');
  12861. JSZip.support = require('./support');
  12862. JSZip.defaults = require('./defaults');
  12863. /**
  12864. * @deprecated
  12865. * This namespace will be removed in a future version without replacement.
  12866. */
  12867. JSZip.utils = require('./deprecatedPublicUtils');
  12868. JSZip.base64 = {
  12869. /**
  12870. * @deprecated
  12871. * This method will be removed in a future version without replacement.
  12872. */
  12873. encode : function(input) {
  12874. return base64.encode(input);
  12875. },
  12876. /**
  12877. * @deprecated
  12878. * This method will be removed in a future version without replacement.
  12879. */
  12880. decode : function(input) {
  12881. return base64.decode(input);
  12882. }
  12883. };
  12884. JSZip.compressions = require('./compressions');
  12885. module.exports = JSZip;
  12886. },{"./base64":101,"./compressions":103,"./defaults":106,"./deprecatedPublicUtils":107,"./load":110,"./object":113,"./support":117}],110:[function(require,module,exports){
  12887. 'use strict';
  12888. var base64 = require('./base64');
  12889. var ZipEntries = require('./zipEntries');
  12890. module.exports = function(data, options) {
  12891. var files, zipEntries, i, input;
  12892. options = options || {};
  12893. if (options.base64) {
  12894. data = base64.decode(data);
  12895. }
  12896. zipEntries = new ZipEntries(data, options);
  12897. files = zipEntries.files;
  12898. for (i = 0; i < files.length; i++) {
  12899. input = files[i];
  12900. this.file(input.fileName, input.decompressed, {
  12901. binary: true,
  12902. optimizedBinaryString: true,
  12903. date: input.date,
  12904. dir: input.dir,
  12905. comment : input.fileComment.length ? input.fileComment : null,
  12906. unixPermissions : input.unixPermissions,
  12907. dosPermissions : input.dosPermissions,
  12908. createFolders: options.createFolders
  12909. });
  12910. }
  12911. if (zipEntries.zipComment.length) {
  12912. this.comment = zipEntries.zipComment;
  12913. }
  12914. return this;
  12915. };
  12916. },{"./base64":101,"./zipEntries":122}],111:[function(require,module,exports){
  12917. (function (Buffer){
  12918. 'use strict';
  12919. module.exports = function(data, encoding){
  12920. return new Buffer(data, encoding);
  12921. };
  12922. module.exports.test = function(b){
  12923. return Buffer.isBuffer(b);
  12924. };
  12925. }).call(this,require("buffer").Buffer)
  12926. },{"buffer":73}],112:[function(require,module,exports){
  12927. 'use strict';
  12928. var Uint8ArrayReader = require('./uint8ArrayReader');
  12929. function NodeBufferReader(data) {
  12930. this.data = data;
  12931. this.length = this.data.length;
  12932. this.index = 0;
  12933. }
  12934. NodeBufferReader.prototype = new Uint8ArrayReader();
  12935. /**
  12936. * @see DataReader.readData
  12937. */
  12938. NodeBufferReader.prototype.readData = function(size) {
  12939. this.checkOffset(size);
  12940. var result = this.data.slice(this.index, this.index + size);
  12941. this.index += size;
  12942. return result;
  12943. };
  12944. module.exports = NodeBufferReader;
  12945. },{"./uint8ArrayReader":118}],113:[function(require,module,exports){
  12946. 'use strict';
  12947. var support = require('./support');
  12948. var utils = require('./utils');
  12949. var crc32 = require('./crc32');
  12950. var signature = require('./signature');
  12951. var defaults = require('./defaults');
  12952. var base64 = require('./base64');
  12953. var compressions = require('./compressions');
  12954. var CompressedObject = require('./compressedObject');
  12955. var nodeBuffer = require('./nodeBuffer');
  12956. var utf8 = require('./utf8');
  12957. var StringWriter = require('./stringWriter');
  12958. var Uint8ArrayWriter = require('./uint8ArrayWriter');
  12959. /**
  12960. * Returns the raw data of a ZipObject, decompress the content if necessary.
  12961. * @param {ZipObject} file the file to use.
  12962. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  12963. */
  12964. var getRawData = function(file) {
  12965. if (file._data instanceof CompressedObject) {
  12966. file._data = file._data.getContent();
  12967. file.options.binary = true;
  12968. file.options.base64 = false;
  12969. if (utils.getTypeOf(file._data) === "uint8array") {
  12970. var copy = file._data;
  12971. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  12972. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  12973. file._data = new Uint8Array(copy.length);
  12974. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  12975. if (copy.length !== 0) {
  12976. file._data.set(copy, 0);
  12977. }
  12978. }
  12979. }
  12980. return file._data;
  12981. };
  12982. /**
  12983. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  12984. * @param {ZipObject} file the file to use.
  12985. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  12986. */
  12987. var getBinaryData = function(file) {
  12988. var result = getRawData(file),
  12989. type = utils.getTypeOf(result);
  12990. if (type === "string") {
  12991. if (!file.options.binary) {
  12992. // unicode text !
  12993. // unicode string => binary string is a painful process, check if we can avoid it.
  12994. if (support.nodebuffer) {
  12995. return nodeBuffer(result, "utf-8");
  12996. }
  12997. }
  12998. return file.asBinary();
  12999. }
  13000. return result;
  13001. };
  13002. /**
  13003. * Transform this._data into a string.
  13004. * @param {function} filter a function String -> String, applied if not null on the result.
  13005. * @return {String} the string representing this._data.
  13006. */
  13007. var dataToString = function(asUTF8) {
  13008. var result = getRawData(this);
  13009. if (result === null || typeof result === "undefined") {
  13010. return "";
  13011. }
  13012. // if the data is a base64 string, we decode it before checking the encoding !
  13013. if (this.options.base64) {
  13014. result = base64.decode(result);
  13015. }
  13016. if (asUTF8 && this.options.binary) {
  13017. // JSZip.prototype.utf8decode supports arrays as input
  13018. // skip to array => string step, utf8decode will do it.
  13019. result = out.utf8decode(result);
  13020. }
  13021. else {
  13022. // no utf8 transformation, do the array => string step.
  13023. result = utils.transformTo("string", result);
  13024. }
  13025. if (!asUTF8 && !this.options.binary) {
  13026. result = utils.transformTo("string", out.utf8encode(result));
  13027. }
  13028. return result;
  13029. };
  13030. /**
  13031. * A simple object representing a file in the zip file.
  13032. * @constructor
  13033. * @param {string} name the name of the file
  13034. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  13035. * @param {Object} options the options of the file
  13036. */
  13037. var ZipObject = function(name, data, options) {
  13038. this.name = name;
  13039. this.dir = options.dir;
  13040. this.date = options.date;
  13041. this.comment = options.comment;
  13042. this.unixPermissions = options.unixPermissions;
  13043. this.dosPermissions = options.dosPermissions;
  13044. this._data = data;
  13045. this.options = options;
  13046. /*
  13047. * This object contains initial values for dir and date.
  13048. * With them, we can check if the user changed the deprecated metadata in
  13049. * `ZipObject#options` or not.
  13050. */
  13051. this._initialMetadata = {
  13052. dir : options.dir,
  13053. date : options.date
  13054. };
  13055. };
  13056. ZipObject.prototype = {
  13057. /**
  13058. * Return the content as UTF8 string.
  13059. * @return {string} the UTF8 string.
  13060. */
  13061. asText: function() {
  13062. return dataToString.call(this, true);
  13063. },
  13064. /**
  13065. * Returns the binary content.
  13066. * @return {string} the content as binary.
  13067. */
  13068. asBinary: function() {
  13069. return dataToString.call(this, false);
  13070. },
  13071. /**
  13072. * Returns the content as a nodejs Buffer.
  13073. * @return {Buffer} the content as a Buffer.
  13074. */
  13075. asNodeBuffer: function() {
  13076. var result = getBinaryData(this);
  13077. return utils.transformTo("nodebuffer", result);
  13078. },
  13079. /**
  13080. * Returns the content as an Uint8Array.
  13081. * @return {Uint8Array} the content as an Uint8Array.
  13082. */
  13083. asUint8Array: function() {
  13084. var result = getBinaryData(this);
  13085. return utils.transformTo("uint8array", result);
  13086. },
  13087. /**
  13088. * Returns the content as an ArrayBuffer.
  13089. * @return {ArrayBuffer} the content as an ArrayBufer.
  13090. */
  13091. asArrayBuffer: function() {
  13092. return this.asUint8Array().buffer;
  13093. }
  13094. };
  13095. /**
  13096. * Transform an integer into a string in hexadecimal.
  13097. * @private
  13098. * @param {number} dec the number to convert.
  13099. * @param {number} bytes the number of bytes to generate.
  13100. * @returns {string} the result.
  13101. */
  13102. var decToHex = function(dec, bytes) {
  13103. var hex = "",
  13104. i;
  13105. for (i = 0; i < bytes; i++) {
  13106. hex += String.fromCharCode(dec & 0xff);
  13107. dec = dec >>> 8;
  13108. }
  13109. return hex;
  13110. };
  13111. /**
  13112. * Merge the objects passed as parameters into a new one.
  13113. * @private
  13114. * @param {...Object} var_args All objects to merge.
  13115. * @return {Object} a new object with the data of the others.
  13116. */
  13117. var extend = function() {
  13118. var result = {}, i, attr;
  13119. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  13120. for (attr in arguments[i]) {
  13121. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  13122. result[attr] = arguments[i][attr];
  13123. }
  13124. }
  13125. }
  13126. return result;
  13127. };
  13128. /**
  13129. * Transforms the (incomplete) options from the user into the complete
  13130. * set of options to create a file.
  13131. * @private
  13132. * @param {Object} o the options from the user.
  13133. * @return {Object} the complete set of options.
  13134. */
  13135. var prepareFileAttrs = function(o) {
  13136. o = o || {};
  13137. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  13138. o.binary = true;
  13139. }
  13140. o = extend(o, defaults);
  13141. o.date = o.date || new Date();
  13142. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  13143. return o;
  13144. };
  13145. /**
  13146. * Add a file in the current folder.
  13147. * @private
  13148. * @param {string} name the name of the file
  13149. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  13150. * @param {Object} o the options of the file
  13151. * @return {Object} the new file.
  13152. */
  13153. var fileAdd = function(name, data, o) {
  13154. // be sure sub folders exist
  13155. var dataType = utils.getTypeOf(data),
  13156. parent;
  13157. o = prepareFileAttrs(o);
  13158. if (typeof o.unixPermissions === "string") {
  13159. o.unixPermissions = parseInt(o.unixPermissions, 8);
  13160. }
  13161. // UNX_IFDIR 0040000 see zipinfo.c
  13162. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  13163. o.dir = true;
  13164. }
  13165. // Bit 4 Directory
  13166. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  13167. o.dir = true;
  13168. }
  13169. if (o.dir) {
  13170. name = forceTrailingSlash(name);
  13171. }
  13172. if (o.createFolders && (parent = parentFolder(name))) {
  13173. folderAdd.call(this, parent, true);
  13174. }
  13175. if (o.dir || data === null || typeof data === "undefined") {
  13176. o.base64 = false;
  13177. o.binary = false;
  13178. data = null;
  13179. dataType = null;
  13180. }
  13181. else if (dataType === "string") {
  13182. if (o.binary && !o.base64) {
  13183. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  13184. if (o.optimizedBinaryString !== true) {
  13185. // this is a string, not in a base64 format.
  13186. // Be sure that this is a correct "binary string"
  13187. data = utils.string2binary(data);
  13188. }
  13189. }
  13190. }
  13191. else { // arraybuffer, uint8array, ...
  13192. o.base64 = false;
  13193. o.binary = true;
  13194. if (!dataType && !(data instanceof CompressedObject)) {
  13195. throw new Error("The data of '" + name + "' is in an unsupported format !");
  13196. }
  13197. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  13198. if (dataType === "arraybuffer") {
  13199. data = utils.transformTo("uint8array", data);
  13200. }
  13201. }
  13202. var object = new ZipObject(name, data, o);
  13203. this.files[name] = object;
  13204. return object;
  13205. };
  13206. /**
  13207. * Find the parent folder of the path.
  13208. * @private
  13209. * @param {string} path the path to use
  13210. * @return {string} the parent folder, or ""
  13211. */
  13212. var parentFolder = function (path) {
  13213. if (path.slice(-1) == '/') {
  13214. path = path.substring(0, path.length - 1);
  13215. }
  13216. var lastSlash = path.lastIndexOf('/');
  13217. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  13218. };
  13219. /**
  13220. * Returns the path with a slash at the end.
  13221. * @private
  13222. * @param {String} path the path to check.
  13223. * @return {String} the path with a trailing slash.
  13224. */
  13225. var forceTrailingSlash = function(path) {
  13226. // Check the name ends with a /
  13227. if (path.slice(-1) != "/") {
  13228. path += "/"; // IE doesn't like substr(-1)
  13229. }
  13230. return path;
  13231. };
  13232. /**
  13233. * Add a (sub) folder in the current folder.
  13234. * @private
  13235. * @param {string} name the folder's name
  13236. * @param {boolean=} [createFolders] If true, automatically create sub
  13237. * folders. Defaults to false.
  13238. * @return {Object} the new folder.
  13239. */
  13240. var folderAdd = function(name, createFolders) {
  13241. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  13242. name = forceTrailingSlash(name);
  13243. // Does this folder already exist?
  13244. if (!this.files[name]) {
  13245. fileAdd.call(this, name, null, {
  13246. dir: true,
  13247. createFolders: createFolders
  13248. });
  13249. }
  13250. return this.files[name];
  13251. };
  13252. /**
  13253. * Generate a JSZip.CompressedObject for a given zipOject.
  13254. * @param {ZipObject} file the object to read.
  13255. * @param {JSZip.compression} compression the compression to use.
  13256. * @param {Object} compressionOptions the options to use when compressing.
  13257. * @return {JSZip.CompressedObject} the compressed result.
  13258. */
  13259. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  13260. var result = new CompressedObject(),
  13261. content;
  13262. // the data has not been decompressed, we might reuse things !
  13263. if (file._data instanceof CompressedObject) {
  13264. result.uncompressedSize = file._data.uncompressedSize;
  13265. result.crc32 = file._data.crc32;
  13266. if (result.uncompressedSize === 0 || file.dir) {
  13267. compression = compressions['STORE'];
  13268. result.compressedContent = "";
  13269. result.crc32 = 0;
  13270. }
  13271. else if (file._data.compressionMethod === compression.magic) {
  13272. result.compressedContent = file._data.getCompressedContent();
  13273. }
  13274. else {
  13275. content = file._data.getContent();
  13276. // need to decompress / recompress
  13277. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  13278. }
  13279. }
  13280. else {
  13281. // have uncompressed data
  13282. content = getBinaryData(file);
  13283. if (!content || content.length === 0 || file.dir) {
  13284. compression = compressions['STORE'];
  13285. content = "";
  13286. }
  13287. result.uncompressedSize = content.length;
  13288. result.crc32 = crc32(content);
  13289. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  13290. }
  13291. result.compressedSize = result.compressedContent.length;
  13292. result.compressionMethod = compression.magic;
  13293. return result;
  13294. };
  13295. /**
  13296. * Generate the UNIX part of the external file attributes.
  13297. * @param {Object} unixPermissions the unix permissions or null.
  13298. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  13299. * @return {Number} a 32 bit integer.
  13300. *
  13301. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  13302. *
  13303. * TTTTsstrwxrwxrwx0000000000ADVSHR
  13304. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  13305. * ^^^_________________________ setuid, setgid, sticky
  13306. * ^^^^^^^^^________________ permissions
  13307. * ^^^^^^^^^^______ not used ?
  13308. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  13309. */
  13310. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  13311. var result = unixPermissions;
  13312. if (!unixPermissions) {
  13313. // I can't use octal values in strict mode, hence the hexa.
  13314. // 040775 => 0x41fd
  13315. // 0100664 => 0x81b4
  13316. result = isDir ? 0x41fd : 0x81b4;
  13317. }
  13318. return (result & 0xFFFF) << 16;
  13319. };
  13320. /**
  13321. * Generate the DOS part of the external file attributes.
  13322. * @param {Object} dosPermissions the dos permissions or null.
  13323. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  13324. * @return {Number} a 32 bit integer.
  13325. *
  13326. * Bit 0 Read-Only
  13327. * Bit 1 Hidden
  13328. * Bit 2 System
  13329. * Bit 3 Volume Label
  13330. * Bit 4 Directory
  13331. * Bit 5 Archive
  13332. */
  13333. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  13334. // the dir flag is already set for compatibility
  13335. return (dosPermissions || 0) & 0x3F;
  13336. };
  13337. /**
  13338. * Generate the various parts used in the construction of the final zip file.
  13339. * @param {string} name the file name.
  13340. * @param {ZipObject} file the file content.
  13341. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  13342. * @param {number} offset the current offset from the start of the zip file.
  13343. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  13344. * @return {object} the zip parts.
  13345. */
  13346. var generateZipParts = function(name, file, compressedObject, offset, platform) {
  13347. var data = compressedObject.compressedContent,
  13348. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  13349. comment = file.comment || "",
  13350. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  13351. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  13352. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  13353. o = file.options,
  13354. dosTime,
  13355. dosDate,
  13356. extraFields = "",
  13357. unicodePathExtraField = "",
  13358. unicodeCommentExtraField = "",
  13359. dir, date;
  13360. // handle the deprecated options.dir
  13361. if (file._initialMetadata.dir !== file.dir) {
  13362. dir = file.dir;
  13363. } else {
  13364. dir = o.dir;
  13365. }
  13366. // handle the deprecated options.date
  13367. if(file._initialMetadata.date !== file.date) {
  13368. date = file.date;
  13369. } else {
  13370. date = o.date;
  13371. }
  13372. var extFileAttr = 0;
  13373. var versionMadeBy = 0;
  13374. if (dir) {
  13375. // dos or unix, we set the dos dir flag
  13376. extFileAttr |= 0x00010;
  13377. }
  13378. if(platform === "UNIX") {
  13379. versionMadeBy = 0x031E; // UNIX, version 3.0
  13380. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  13381. } else { // DOS or other, fallback to DOS
  13382. versionMadeBy = 0x0014; // DOS, version 2.0
  13383. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  13384. }
  13385. // date
  13386. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  13387. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  13388. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  13389. dosTime = date.getHours();
  13390. dosTime = dosTime << 6;
  13391. dosTime = dosTime | date.getMinutes();
  13392. dosTime = dosTime << 5;
  13393. dosTime = dosTime | date.getSeconds() / 2;
  13394. dosDate = date.getFullYear() - 1980;
  13395. dosDate = dosDate << 4;
  13396. dosDate = dosDate | (date.getMonth() + 1);
  13397. dosDate = dosDate << 5;
  13398. dosDate = dosDate | date.getDate();
  13399. if (useUTF8ForFileName) {
  13400. // set the unicode path extra field. unzip needs at least one extra
  13401. // field to correctly handle unicode path, so using the path is as good
  13402. // as any other information. This could improve the situation with
  13403. // other archive managers too.
  13404. // This field is usually used without the utf8 flag, with a non
  13405. // unicode path in the header (winrar, winzip). This helps (a bit)
  13406. // with the messy Windows' default compressed folders feature but
  13407. // breaks on p7zip which doesn't seek the unicode path extra field.
  13408. // So for now, UTF-8 everywhere !
  13409. unicodePathExtraField =
  13410. // Version
  13411. decToHex(1, 1) +
  13412. // NameCRC32
  13413. decToHex(crc32(utfEncodedFileName), 4) +
  13414. // UnicodeName
  13415. utfEncodedFileName;
  13416. extraFields +=
  13417. // Info-ZIP Unicode Path Extra Field
  13418. "\x75\x70" +
  13419. // size
  13420. decToHex(unicodePathExtraField.length, 2) +
  13421. // content
  13422. unicodePathExtraField;
  13423. }
  13424. if(useUTF8ForComment) {
  13425. unicodeCommentExtraField =
  13426. // Version
  13427. decToHex(1, 1) +
  13428. // CommentCRC32
  13429. decToHex(this.crc32(utfEncodedComment), 4) +
  13430. // UnicodeName
  13431. utfEncodedComment;
  13432. extraFields +=
  13433. // Info-ZIP Unicode Path Extra Field
  13434. "\x75\x63" +
  13435. // size
  13436. decToHex(unicodeCommentExtraField.length, 2) +
  13437. // content
  13438. unicodeCommentExtraField;
  13439. }
  13440. var header = "";
  13441. // version needed to extract
  13442. header += "\x0A\x00";
  13443. // general purpose bit flag
  13444. // set bit 11 if utf8
  13445. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  13446. // compression method
  13447. header += compressedObject.compressionMethod;
  13448. // last mod file time
  13449. header += decToHex(dosTime, 2);
  13450. // last mod file date
  13451. header += decToHex(dosDate, 2);
  13452. // crc-32
  13453. header += decToHex(compressedObject.crc32, 4);
  13454. // compressed size
  13455. header += decToHex(compressedObject.compressedSize, 4);
  13456. // uncompressed size
  13457. header += decToHex(compressedObject.uncompressedSize, 4);
  13458. // file name length
  13459. header += decToHex(utfEncodedFileName.length, 2);
  13460. // extra field length
  13461. header += decToHex(extraFields.length, 2);
  13462. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  13463. var dirRecord = signature.CENTRAL_FILE_HEADER +
  13464. // version made by (00: DOS)
  13465. decToHex(versionMadeBy, 2) +
  13466. // file header (common to file and central directory)
  13467. header +
  13468. // file comment length
  13469. decToHex(utfEncodedComment.length, 2) +
  13470. // disk number start
  13471. "\x00\x00" +
  13472. // internal file attributes TODO
  13473. "\x00\x00" +
  13474. // external file attributes
  13475. decToHex(extFileAttr, 4) +
  13476. // relative offset of local header
  13477. decToHex(offset, 4) +
  13478. // file name
  13479. utfEncodedFileName +
  13480. // extra field
  13481. extraFields +
  13482. // file comment
  13483. utfEncodedComment;
  13484. return {
  13485. fileRecord: fileRecord,
  13486. dirRecord: dirRecord,
  13487. compressedObject: compressedObject
  13488. };
  13489. };
  13490. // return the actual prototype of JSZip
  13491. var out = {
  13492. /**
  13493. * Read an existing zip and merge the data in the current JSZip object.
  13494. * The implementation is in jszip-load.js, don't forget to include it.
  13495. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  13496. * @param {Object} options Options for loading the stream.
  13497. * options.base64 : is the stream in base64 ? default : false
  13498. * @return {JSZip} the current JSZip object
  13499. */
  13500. load: function(stream, options) {
  13501. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  13502. },
  13503. /**
  13504. * Filter nested files/folders with the specified function.
  13505. * @param {Function} search the predicate to use :
  13506. * function (relativePath, file) {...}
  13507. * It takes 2 arguments : the relative path and the file.
  13508. * @return {Array} An array of matching elements.
  13509. */
  13510. filter: function(search) {
  13511. var result = [],
  13512. filename, relativePath, file, fileClone;
  13513. for (filename in this.files) {
  13514. if (!this.files.hasOwnProperty(filename)) {
  13515. continue;
  13516. }
  13517. file = this.files[filename];
  13518. // return a new object, don't let the user mess with our internal objects :)
  13519. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  13520. relativePath = filename.slice(this.root.length, filename.length);
  13521. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  13522. search(relativePath, fileClone)) { // and the file matches the function
  13523. result.push(fileClone);
  13524. }
  13525. }
  13526. return result;
  13527. },
  13528. /**
  13529. * Add a file to the zip file, or search a file.
  13530. * @param {string|RegExp} name The name of the file to add (if data is defined),
  13531. * the name of the file to find (if no data) or a regex to match files.
  13532. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  13533. * @param {Object} o File options
  13534. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  13535. * a file (when searching by string) or an array of files (when searching by regex).
  13536. */
  13537. file: function(name, data, o) {
  13538. if (arguments.length === 1) {
  13539. if (utils.isRegExp(name)) {
  13540. var regexp = name;
  13541. return this.filter(function(relativePath, file) {
  13542. return !file.dir && regexp.test(relativePath);
  13543. });
  13544. }
  13545. else { // text
  13546. return this.filter(function(relativePath, file) {
  13547. return !file.dir && relativePath === name;
  13548. })[0] || null;
  13549. }
  13550. }
  13551. else { // more than one argument : we have data !
  13552. name = this.root + name;
  13553. fileAdd.call(this, name, data, o);
  13554. }
  13555. return this;
  13556. },
  13557. /**
  13558. * Add a directory to the zip file, or search.
  13559. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  13560. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  13561. */
  13562. folder: function(arg) {
  13563. if (!arg) {
  13564. return this;
  13565. }
  13566. if (utils.isRegExp(arg)) {
  13567. return this.filter(function(relativePath, file) {
  13568. return file.dir && arg.test(relativePath);
  13569. });
  13570. }
  13571. // else, name is a new folder
  13572. var name = this.root + arg;
  13573. var newFolder = folderAdd.call(this, name);
  13574. // Allow chaining by returning a new object with this folder as the root
  13575. var ret = this.clone();
  13576. ret.root = newFolder.name;
  13577. return ret;
  13578. },
  13579. /**
  13580. * Delete a file, or a directory and all sub-files, from the zip
  13581. * @param {string} name the name of the file to delete
  13582. * @return {JSZip} this JSZip object
  13583. */
  13584. remove: function(name) {
  13585. name = this.root + name;
  13586. var file = this.files[name];
  13587. if (!file) {
  13588. // Look for any folders
  13589. if (name.slice(-1) != "/") {
  13590. name += "/";
  13591. }
  13592. file = this.files[name];
  13593. }
  13594. if (file && !file.dir) {
  13595. // file
  13596. delete this.files[name];
  13597. } else {
  13598. // maybe a folder, delete recursively
  13599. var kids = this.filter(function(relativePath, file) {
  13600. return file.name.slice(0, name.length) === name;
  13601. });
  13602. for (var i = 0; i < kids.length; i++) {
  13603. delete this.files[kids[i].name];
  13604. }
  13605. }
  13606. return this;
  13607. },
  13608. /**
  13609. * Generate the complete zip file
  13610. * @param {Object} options the options to generate the zip file :
  13611. * - base64, (deprecated, use type instead) true to generate base64.
  13612. * - compression, "STORE" by default.
  13613. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  13614. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  13615. */
  13616. generate: function(options) {
  13617. options = extend(options || {}, {
  13618. base64: true,
  13619. compression: "STORE",
  13620. compressionOptions : null,
  13621. type: "base64",
  13622. platform: "DOS",
  13623. comment: null,
  13624. mimeType: 'application/zip'
  13625. });
  13626. utils.checkSupport(options.type);
  13627. // accept nodejs `process.platform`
  13628. if(
  13629. options.platform === 'darwin' ||
  13630. options.platform === 'freebsd' ||
  13631. options.platform === 'linux' ||
  13632. options.platform === 'sunos'
  13633. ) {
  13634. options.platform = "UNIX";
  13635. }
  13636. if (options.platform === 'win32') {
  13637. options.platform = "DOS";
  13638. }
  13639. var zipData = [],
  13640. localDirLength = 0,
  13641. centralDirLength = 0,
  13642. writer, i,
  13643. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  13644. // first, generate all the zip parts.
  13645. for (var name in this.files) {
  13646. if (!this.files.hasOwnProperty(name)) {
  13647. continue;
  13648. }
  13649. var file = this.files[name];
  13650. var compressionName = file.options.compression || options.compression.toUpperCase();
  13651. var compression = compressions[compressionName];
  13652. if (!compression) {
  13653. throw new Error(compressionName + " is not a valid compression method !");
  13654. }
  13655. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  13656. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  13657. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
  13658. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  13659. centralDirLength += zipPart.dirRecord.length;
  13660. zipData.push(zipPart);
  13661. }
  13662. var dirEnd = "";
  13663. // end of central dir signature
  13664. dirEnd = signature.CENTRAL_DIRECTORY_END +
  13665. // number of this disk
  13666. "\x00\x00" +
  13667. // number of the disk with the start of the central directory
  13668. "\x00\x00" +
  13669. // total number of entries in the central directory on this disk
  13670. decToHex(zipData.length, 2) +
  13671. // total number of entries in the central directory
  13672. decToHex(zipData.length, 2) +
  13673. // size of the central directory 4 bytes
  13674. decToHex(centralDirLength, 4) +
  13675. // offset of start of central directory with respect to the starting disk number
  13676. decToHex(localDirLength, 4) +
  13677. // .ZIP file comment length
  13678. decToHex(utfEncodedComment.length, 2) +
  13679. // .ZIP file comment
  13680. utfEncodedComment;
  13681. // we have all the parts (and the total length)
  13682. // time to create a writer !
  13683. var typeName = options.type.toLowerCase();
  13684. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  13685. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  13686. }else{
  13687. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  13688. }
  13689. for (i = 0; i < zipData.length; i++) {
  13690. writer.append(zipData[i].fileRecord);
  13691. writer.append(zipData[i].compressedObject.compressedContent);
  13692. }
  13693. for (i = 0; i < zipData.length; i++) {
  13694. writer.append(zipData[i].dirRecord);
  13695. }
  13696. writer.append(dirEnd);
  13697. var zip = writer.finalize();
  13698. switch(options.type.toLowerCase()) {
  13699. // case "zip is an Uint8Array"
  13700. case "uint8array" :
  13701. case "arraybuffer" :
  13702. case "nodebuffer" :
  13703. return utils.transformTo(options.type.toLowerCase(), zip);
  13704. case "blob" :
  13705. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  13706. // case "zip is a string"
  13707. case "base64" :
  13708. return (options.base64) ? base64.encode(zip) : zip;
  13709. default : // case "string" :
  13710. return zip;
  13711. }
  13712. },
  13713. /**
  13714. * @deprecated
  13715. * This method will be removed in a future version without replacement.
  13716. */
  13717. crc32: function (input, crc) {
  13718. return crc32(input, crc);
  13719. },
  13720. /**
  13721. * @deprecated
  13722. * This method will be removed in a future version without replacement.
  13723. */
  13724. utf8encode: function (string) {
  13725. return utils.transformTo("string", utf8.utf8encode(string));
  13726. },
  13727. /**
  13728. * @deprecated
  13729. * This method will be removed in a future version without replacement.
  13730. */
  13731. utf8decode: function (input) {
  13732. return utf8.utf8decode(input);
  13733. }
  13734. };
  13735. module.exports = out;
  13736. },{"./base64":101,"./compressedObject":102,"./compressions":103,"./crc32":104,"./defaults":106,"./nodeBuffer":111,"./signature":114,"./stringWriter":116,"./support":117,"./uint8ArrayWriter":119,"./utf8":120,"./utils":121}],114:[function(require,module,exports){
  13737. 'use strict';
  13738. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  13739. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  13740. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  13741. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  13742. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  13743. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  13744. },{}],115:[function(require,module,exports){
  13745. 'use strict';
  13746. var DataReader = require('./dataReader');
  13747. var utils = require('./utils');
  13748. function StringReader(data, optimizedBinaryString) {
  13749. this.data = data;
  13750. if (!optimizedBinaryString) {
  13751. this.data = utils.string2binary(this.data);
  13752. }
  13753. this.length = this.data.length;
  13754. this.index = 0;
  13755. }
  13756. StringReader.prototype = new DataReader();
  13757. /**
  13758. * @see DataReader.byteAt
  13759. */
  13760. StringReader.prototype.byteAt = function(i) {
  13761. return this.data.charCodeAt(i);
  13762. };
  13763. /**
  13764. * @see DataReader.lastIndexOfSignature
  13765. */
  13766. StringReader.prototype.lastIndexOfSignature = function(sig) {
  13767. return this.data.lastIndexOf(sig);
  13768. };
  13769. /**
  13770. * @see DataReader.readData
  13771. */
  13772. StringReader.prototype.readData = function(size) {
  13773. this.checkOffset(size);
  13774. // this will work because the constructor applied the "& 0xff" mask.
  13775. var result = this.data.slice(this.index, this.index + size);
  13776. this.index += size;
  13777. return result;
  13778. };
  13779. module.exports = StringReader;
  13780. },{"./dataReader":105,"./utils":121}],116:[function(require,module,exports){
  13781. 'use strict';
  13782. var utils = require('./utils');
  13783. /**
  13784. * An object to write any content to a string.
  13785. * @constructor
  13786. */
  13787. var StringWriter = function() {
  13788. this.data = [];
  13789. };
  13790. StringWriter.prototype = {
  13791. /**
  13792. * Append any content to the current string.
  13793. * @param {Object} input the content to add.
  13794. */
  13795. append: function(input) {
  13796. input = utils.transformTo("string", input);
  13797. this.data.push(input);
  13798. },
  13799. /**
  13800. * Finalize the construction an return the result.
  13801. * @return {string} the generated string.
  13802. */
  13803. finalize: function() {
  13804. return this.data.join("");
  13805. }
  13806. };
  13807. module.exports = StringWriter;
  13808. },{"./utils":121}],117:[function(require,module,exports){
  13809. (function (Buffer){
  13810. 'use strict';
  13811. exports.base64 = true;
  13812. exports.array = true;
  13813. exports.string = true;
  13814. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  13815. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  13816. // Browserify will provide a Buffer implementation for browsers, which is
  13817. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  13818. exports.nodebuffer = typeof Buffer !== "undefined";
  13819. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  13820. exports.uint8array = typeof Uint8Array !== "undefined";
  13821. if (typeof ArrayBuffer === "undefined") {
  13822. exports.blob = false;
  13823. }
  13824. else {
  13825. var buffer = new ArrayBuffer(0);
  13826. try {
  13827. exports.blob = new Blob([buffer], {
  13828. type: "application/zip"
  13829. }).size === 0;
  13830. }
  13831. catch (e) {
  13832. try {
  13833. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  13834. var builder = new Builder();
  13835. builder.append(buffer);
  13836. exports.blob = builder.getBlob('application/zip').size === 0;
  13837. }
  13838. catch (e) {
  13839. exports.blob = false;
  13840. }
  13841. }
  13842. }
  13843. }).call(this,require("buffer").Buffer)
  13844. },{"buffer":73}],118:[function(require,module,exports){
  13845. 'use strict';
  13846. var DataReader = require('./dataReader');
  13847. function Uint8ArrayReader(data) {
  13848. if (data) {
  13849. this.data = data;
  13850. this.length = this.data.length;
  13851. this.index = 0;
  13852. }
  13853. }
  13854. Uint8ArrayReader.prototype = new DataReader();
  13855. /**
  13856. * @see DataReader.byteAt
  13857. */
  13858. Uint8ArrayReader.prototype.byteAt = function(i) {
  13859. return this.data[i];
  13860. };
  13861. /**
  13862. * @see DataReader.lastIndexOfSignature
  13863. */
  13864. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  13865. var sig0 = sig.charCodeAt(0),
  13866. sig1 = sig.charCodeAt(1),
  13867. sig2 = sig.charCodeAt(2),
  13868. sig3 = sig.charCodeAt(3);
  13869. for (var i = this.length - 4; i >= 0; --i) {
  13870. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  13871. return i;
  13872. }
  13873. }
  13874. return -1;
  13875. };
  13876. /**
  13877. * @see DataReader.readData
  13878. */
  13879. Uint8ArrayReader.prototype.readData = function(size) {
  13880. this.checkOffset(size);
  13881. if(size === 0) {
  13882. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  13883. return new Uint8Array(0);
  13884. }
  13885. var result = this.data.subarray(this.index, this.index + size);
  13886. this.index += size;
  13887. return result;
  13888. };
  13889. module.exports = Uint8ArrayReader;
  13890. },{"./dataReader":105}],119:[function(require,module,exports){
  13891. 'use strict';
  13892. var utils = require('./utils');
  13893. /**
  13894. * An object to write any content to an Uint8Array.
  13895. * @constructor
  13896. * @param {number} length The length of the array.
  13897. */
  13898. var Uint8ArrayWriter = function(length) {
  13899. this.data = new Uint8Array(length);
  13900. this.index = 0;
  13901. };
  13902. Uint8ArrayWriter.prototype = {
  13903. /**
  13904. * Append any content to the current array.
  13905. * @param {Object} input the content to add.
  13906. */
  13907. append: function(input) {
  13908. if (input.length !== 0) {
  13909. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  13910. input = utils.transformTo("uint8array", input);
  13911. this.data.set(input, this.index);
  13912. this.index += input.length;
  13913. }
  13914. },
  13915. /**
  13916. * Finalize the construction an return the result.
  13917. * @return {Uint8Array} the generated array.
  13918. */
  13919. finalize: function() {
  13920. return this.data;
  13921. }
  13922. };
  13923. module.exports = Uint8ArrayWriter;
  13924. },{"./utils":121}],120:[function(require,module,exports){
  13925. 'use strict';
  13926. var utils = require('./utils');
  13927. var support = require('./support');
  13928. var nodeBuffer = require('./nodeBuffer');
  13929. /**
  13930. * The following functions come from pako, from pako/lib/utils/strings
  13931. * released under the MIT license, see pako https://github.com/nodeca/pako/
  13932. */
  13933. // Table with utf8 lengths (calculated by first byte of sequence)
  13934. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13935. // because max possible codepoint is 0x10ffff
  13936. var _utf8len = new Array(256);
  13937. for (var i=0; i<256; i++) {
  13938. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  13939. }
  13940. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13941. // convert string to array (typed, when possible)
  13942. var string2buf = function (str) {
  13943. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13944. // count binary size
  13945. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13946. c = str.charCodeAt(m_pos);
  13947. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13948. c2 = str.charCodeAt(m_pos+1);
  13949. if ((c2 & 0xfc00) === 0xdc00) {
  13950. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13951. m_pos++;
  13952. }
  13953. }
  13954. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13955. }
  13956. // allocate buffer
  13957. if (support.uint8array) {
  13958. buf = new Uint8Array(buf_len);
  13959. } else {
  13960. buf = new Array(buf_len);
  13961. }
  13962. // convert
  13963. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13964. c = str.charCodeAt(m_pos);
  13965. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13966. c2 = str.charCodeAt(m_pos+1);
  13967. if ((c2 & 0xfc00) === 0xdc00) {
  13968. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13969. m_pos++;
  13970. }
  13971. }
  13972. if (c < 0x80) {
  13973. /* one byte */
  13974. buf[i++] = c;
  13975. } else if (c < 0x800) {
  13976. /* two bytes */
  13977. buf[i++] = 0xC0 | (c >>> 6);
  13978. buf[i++] = 0x80 | (c & 0x3f);
  13979. } else if (c < 0x10000) {
  13980. /* three bytes */
  13981. buf[i++] = 0xE0 | (c >>> 12);
  13982. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13983. buf[i++] = 0x80 | (c & 0x3f);
  13984. } else {
  13985. /* four bytes */
  13986. buf[i++] = 0xf0 | (c >>> 18);
  13987. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13988. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13989. buf[i++] = 0x80 | (c & 0x3f);
  13990. }
  13991. }
  13992. return buf;
  13993. };
  13994. // Calculate max possible position in utf8 buffer,
  13995. // that will not break sequence. If that's not possible
  13996. // - (very small limits) return max size as is.
  13997. //
  13998. // buf[] - utf8 bytes array
  13999. // max - length limit (mandatory);
  14000. var utf8border = function(buf, max) {
  14001. var pos;
  14002. max = max || buf.length;
  14003. if (max > buf.length) { max = buf.length; }
  14004. // go back from last position, until start of sequence found
  14005. pos = max-1;
  14006. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14007. // Fuckup - very small and broken sequence,
  14008. // return max, because we should return something anyway.
  14009. if (pos < 0) { return max; }
  14010. // If we came to start of buffer - that means vuffer is too small,
  14011. // return max too.
  14012. if (pos === 0) { return max; }
  14013. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14014. };
  14015. // convert array to string
  14016. var buf2string = function (buf) {
  14017. var str, i, out, c, c_len;
  14018. var len = buf.length;
  14019. // Reserve max possible length (2 words per char)
  14020. // NB: by unknown reasons, Array is significantly faster for
  14021. // String.fromCharCode.apply than Uint16Array.
  14022. var utf16buf = new Array(len*2);
  14023. for (out=0, i=0; i<len;) {
  14024. c = buf[i++];
  14025. // quick process ascii
  14026. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14027. c_len = _utf8len[c];
  14028. // skip 5 & 6 byte codes
  14029. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14030. // apply mask on first byte
  14031. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14032. // join the rest
  14033. while (c_len > 1 && i < len) {
  14034. c = (c << 6) | (buf[i++] & 0x3f);
  14035. c_len--;
  14036. }
  14037. // terminated by end of string?
  14038. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14039. if (c < 0x10000) {
  14040. utf16buf[out++] = c;
  14041. } else {
  14042. c -= 0x10000;
  14043. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14044. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14045. }
  14046. }
  14047. // shrinkBuf(utf16buf, out)
  14048. if (utf16buf.length !== out) {
  14049. if(utf16buf.subarray) {
  14050. utf16buf = utf16buf.subarray(0, out);
  14051. } else {
  14052. utf16buf.length = out;
  14053. }
  14054. }
  14055. // return String.fromCharCode.apply(null, utf16buf);
  14056. return utils.applyFromCharCode(utf16buf);
  14057. };
  14058. // That's all for the pako functions.
  14059. /**
  14060. * Transform a javascript string into an array (typed if possible) of bytes,
  14061. * UTF-8 encoded.
  14062. * @param {String} str the string to encode
  14063. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  14064. */
  14065. exports.utf8encode = function utf8encode(str) {
  14066. if (support.nodebuffer) {
  14067. return nodeBuffer(str, "utf-8");
  14068. }
  14069. return string2buf(str);
  14070. };
  14071. /**
  14072. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  14073. * string into a javascript string.
  14074. * @param {Array|Uint8Array|Buffer} buf the data de decode
  14075. * @return {String} the decoded string.
  14076. */
  14077. exports.utf8decode = function utf8decode(buf) {
  14078. if (support.nodebuffer) {
  14079. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  14080. }
  14081. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  14082. // return buf2string(buf);
  14083. // Chrome prefers to work with "small" chunks of data
  14084. // for the method buf2string.
  14085. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  14086. var result = [], k = 0, len = buf.length, chunk = 65536;
  14087. while (k < len) {
  14088. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  14089. if (support.uint8array) {
  14090. result.push(buf2string(buf.subarray(k, nextBoundary)));
  14091. } else {
  14092. result.push(buf2string(buf.slice(k, nextBoundary)));
  14093. }
  14094. k = nextBoundary;
  14095. }
  14096. return result.join("");
  14097. };
  14098. // vim: set shiftwidth=4 softtabstop=4:
  14099. },{"./nodeBuffer":111,"./support":117,"./utils":121}],121:[function(require,module,exports){
  14100. 'use strict';
  14101. var support = require('./support');
  14102. var compressions = require('./compressions');
  14103. var nodeBuffer = require('./nodeBuffer');
  14104. /**
  14105. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  14106. * @param {string} str the string to transform.
  14107. * @return {String} the binary string.
  14108. */
  14109. exports.string2binary = function(str) {
  14110. var result = "";
  14111. for (var i = 0; i < str.length; i++) {
  14112. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  14113. }
  14114. return result;
  14115. };
  14116. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  14117. exports.checkSupport("blob");
  14118. mimeType = mimeType || 'application/zip';
  14119. try {
  14120. // Blob constructor
  14121. return new Blob([buffer], {
  14122. type: mimeType
  14123. });
  14124. }
  14125. catch (e) {
  14126. try {
  14127. // deprecated, browser only, old way
  14128. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  14129. var builder = new Builder();
  14130. builder.append(buffer);
  14131. return builder.getBlob(mimeType);
  14132. }
  14133. catch (e) {
  14134. // well, fuck ?!
  14135. throw new Error("Bug : can't construct the Blob.");
  14136. }
  14137. }
  14138. };
  14139. /**
  14140. * The identity function.
  14141. * @param {Object} input the input.
  14142. * @return {Object} the same input.
  14143. */
  14144. function identity(input) {
  14145. return input;
  14146. }
  14147. /**
  14148. * Fill in an array with a string.
  14149. * @param {String} str the string to use.
  14150. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  14151. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  14152. */
  14153. function stringToArrayLike(str, array) {
  14154. for (var i = 0; i < str.length; ++i) {
  14155. array[i] = str.charCodeAt(i) & 0xFF;
  14156. }
  14157. return array;
  14158. }
  14159. /**
  14160. * Transform an array-like object to a string.
  14161. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  14162. * @return {String} the result.
  14163. */
  14164. function arrayLikeToString(array) {
  14165. // Performances notes :
  14166. // --------------------
  14167. // String.fromCharCode.apply(null, array) is the fastest, see
  14168. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  14169. // but the stack is limited (and we can get huge arrays !).
  14170. //
  14171. // result += String.fromCharCode(array[i]); generate too many strings !
  14172. //
  14173. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  14174. var chunk = 65536;
  14175. var result = [],
  14176. len = array.length,
  14177. type = exports.getTypeOf(array),
  14178. k = 0,
  14179. canUseApply = true;
  14180. try {
  14181. switch(type) {
  14182. case "uint8array":
  14183. String.fromCharCode.apply(null, new Uint8Array(0));
  14184. break;
  14185. case "nodebuffer":
  14186. String.fromCharCode.apply(null, nodeBuffer(0));
  14187. break;
  14188. }
  14189. } catch(e) {
  14190. canUseApply = false;
  14191. }
  14192. // no apply : slow and painful algorithm
  14193. // default browser on android 4.*
  14194. if (!canUseApply) {
  14195. var resultStr = "";
  14196. for(var i = 0; i < array.length;i++) {
  14197. resultStr += String.fromCharCode(array[i]);
  14198. }
  14199. return resultStr;
  14200. }
  14201. while (k < len && chunk > 1) {
  14202. try {
  14203. if (type === "array" || type === "nodebuffer") {
  14204. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  14205. }
  14206. else {
  14207. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  14208. }
  14209. k += chunk;
  14210. }
  14211. catch (e) {
  14212. chunk = Math.floor(chunk / 2);
  14213. }
  14214. }
  14215. return result.join("");
  14216. }
  14217. exports.applyFromCharCode = arrayLikeToString;
  14218. /**
  14219. * Copy the data from an array-like to an other array-like.
  14220. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  14221. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  14222. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  14223. */
  14224. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  14225. for (var i = 0; i < arrayFrom.length; i++) {
  14226. arrayTo[i] = arrayFrom[i];
  14227. }
  14228. return arrayTo;
  14229. }
  14230. // a matrix containing functions to transform everything into everything.
  14231. var transform = {};
  14232. // string to ?
  14233. transform["string"] = {
  14234. "string": identity,
  14235. "array": function(input) {
  14236. return stringToArrayLike(input, new Array(input.length));
  14237. },
  14238. "arraybuffer": function(input) {
  14239. return transform["string"]["uint8array"](input).buffer;
  14240. },
  14241. "uint8array": function(input) {
  14242. return stringToArrayLike(input, new Uint8Array(input.length));
  14243. },
  14244. "nodebuffer": function(input) {
  14245. return stringToArrayLike(input, nodeBuffer(input.length));
  14246. }
  14247. };
  14248. // array to ?
  14249. transform["array"] = {
  14250. "string": arrayLikeToString,
  14251. "array": identity,
  14252. "arraybuffer": function(input) {
  14253. return (new Uint8Array(input)).buffer;
  14254. },
  14255. "uint8array": function(input) {
  14256. return new Uint8Array(input);
  14257. },
  14258. "nodebuffer": function(input) {
  14259. return nodeBuffer(input);
  14260. }
  14261. };
  14262. // arraybuffer to ?
  14263. transform["arraybuffer"] = {
  14264. "string": function(input) {
  14265. return arrayLikeToString(new Uint8Array(input));
  14266. },
  14267. "array": function(input) {
  14268. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  14269. },
  14270. "arraybuffer": identity,
  14271. "uint8array": function(input) {
  14272. return new Uint8Array(input);
  14273. },
  14274. "nodebuffer": function(input) {
  14275. return nodeBuffer(new Uint8Array(input));
  14276. }
  14277. };
  14278. // uint8array to ?
  14279. transform["uint8array"] = {
  14280. "string": arrayLikeToString,
  14281. "array": function(input) {
  14282. return arrayLikeToArrayLike(input, new Array(input.length));
  14283. },
  14284. "arraybuffer": function(input) {
  14285. return input.buffer;
  14286. },
  14287. "uint8array": identity,
  14288. "nodebuffer": function(input) {
  14289. return nodeBuffer(input);
  14290. }
  14291. };
  14292. // nodebuffer to ?
  14293. transform["nodebuffer"] = {
  14294. "string": arrayLikeToString,
  14295. "array": function(input) {
  14296. return arrayLikeToArrayLike(input, new Array(input.length));
  14297. },
  14298. "arraybuffer": function(input) {
  14299. return transform["nodebuffer"]["uint8array"](input).buffer;
  14300. },
  14301. "uint8array": function(input) {
  14302. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  14303. },
  14304. "nodebuffer": identity
  14305. };
  14306. /**
  14307. * Transform an input into any type.
  14308. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  14309. * If no output type is specified, the unmodified input will be returned.
  14310. * @param {String} outputType the output type.
  14311. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  14312. * @throws {Error} an Error if the browser doesn't support the requested output type.
  14313. */
  14314. exports.transformTo = function(outputType, input) {
  14315. if (!input) {
  14316. // undefined, null, etc
  14317. // an empty string won't harm.
  14318. input = "";
  14319. }
  14320. if (!outputType) {
  14321. return input;
  14322. }
  14323. exports.checkSupport(outputType);
  14324. var inputType = exports.getTypeOf(input);
  14325. var result = transform[inputType][outputType](input);
  14326. return result;
  14327. };
  14328. /**
  14329. * Return the type of the input.
  14330. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  14331. * @param {Object} input the input to identify.
  14332. * @return {String} the (lowercase) type of the input.
  14333. */
  14334. exports.getTypeOf = function(input) {
  14335. if (typeof input === "string") {
  14336. return "string";
  14337. }
  14338. if (Object.prototype.toString.call(input) === "[object Array]") {
  14339. return "array";
  14340. }
  14341. if (support.nodebuffer && nodeBuffer.test(input)) {
  14342. return "nodebuffer";
  14343. }
  14344. if (support.uint8array && input instanceof Uint8Array) {
  14345. return "uint8array";
  14346. }
  14347. if (support.arraybuffer && input instanceof ArrayBuffer) {
  14348. return "arraybuffer";
  14349. }
  14350. };
  14351. /**
  14352. * Throw an exception if the type is not supported.
  14353. * @param {String} type the type to check.
  14354. * @throws {Error} an Error if the browser doesn't support the requested type.
  14355. */
  14356. exports.checkSupport = function(type) {
  14357. var supported = support[type.toLowerCase()];
  14358. if (!supported) {
  14359. throw new Error(type + " is not supported by this browser");
  14360. }
  14361. };
  14362. exports.MAX_VALUE_16BITS = 65535;
  14363. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  14364. /**
  14365. * Prettify a string read as binary.
  14366. * @param {string} str the string to prettify.
  14367. * @return {string} a pretty string.
  14368. */
  14369. exports.pretty = function(str) {
  14370. var res = '',
  14371. code, i;
  14372. for (i = 0; i < (str || "").length; i++) {
  14373. code = str.charCodeAt(i);
  14374. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  14375. }
  14376. return res;
  14377. };
  14378. /**
  14379. * Find a compression registered in JSZip.
  14380. * @param {string} compressionMethod the method magic to find.
  14381. * @return {Object|null} the JSZip compression object, null if none found.
  14382. */
  14383. exports.findCompression = function(compressionMethod) {
  14384. for (var method in compressions) {
  14385. if (!compressions.hasOwnProperty(method)) {
  14386. continue;
  14387. }
  14388. if (compressions[method].magic === compressionMethod) {
  14389. return compressions[method];
  14390. }
  14391. }
  14392. return null;
  14393. };
  14394. /**
  14395. * Cross-window, cross-Node-context regular expression detection
  14396. * @param {Object} object Anything
  14397. * @return {Boolean} true if the object is a regular expression,
  14398. * false otherwise
  14399. */
  14400. exports.isRegExp = function (object) {
  14401. return Object.prototype.toString.call(object) === "[object RegExp]";
  14402. };
  14403. },{"./compressions":103,"./nodeBuffer":111,"./support":117}],122:[function(require,module,exports){
  14404. 'use strict';
  14405. var StringReader = require('./stringReader');
  14406. var NodeBufferReader = require('./nodeBufferReader');
  14407. var Uint8ArrayReader = require('./uint8ArrayReader');
  14408. var utils = require('./utils');
  14409. var sig = require('./signature');
  14410. var ZipEntry = require('./zipEntry');
  14411. var support = require('./support');
  14412. var jszipProto = require('./object');
  14413. // class ZipEntries {{{
  14414. /**
  14415. * All the entries in the zip file.
  14416. * @constructor
  14417. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  14418. * @param {Object} loadOptions Options for loading the stream.
  14419. */
  14420. function ZipEntries(data, loadOptions) {
  14421. this.files = [];
  14422. this.loadOptions = loadOptions;
  14423. if (data) {
  14424. this.load(data);
  14425. }
  14426. }
  14427. ZipEntries.prototype = {
  14428. /**
  14429. * Check that the reader is on the speficied signature.
  14430. * @param {string} expectedSignature the expected signature.
  14431. * @throws {Error} if it is an other signature.
  14432. */
  14433. checkSignature: function(expectedSignature) {
  14434. var signature = this.reader.readString(4);
  14435. if (signature !== expectedSignature) {
  14436. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  14437. }
  14438. },
  14439. /**
  14440. * Read the end of the central directory.
  14441. */
  14442. readBlockEndOfCentral: function() {
  14443. this.diskNumber = this.reader.readInt(2);
  14444. this.diskWithCentralDirStart = this.reader.readInt(2);
  14445. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  14446. this.centralDirRecords = this.reader.readInt(2);
  14447. this.centralDirSize = this.reader.readInt(4);
  14448. this.centralDirOffset = this.reader.readInt(4);
  14449. this.zipCommentLength = this.reader.readInt(2);
  14450. // warning : the encoding depends of the system locale
  14451. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  14452. // On a windows machine, this field is encoded with the localized windows code page.
  14453. this.zipComment = this.reader.readString(this.zipCommentLength);
  14454. // To get consistent behavior with the generation part, we will assume that
  14455. // this is utf8 encoded.
  14456. this.zipComment = jszipProto.utf8decode(this.zipComment);
  14457. },
  14458. /**
  14459. * Read the end of the Zip 64 central directory.
  14460. * Not merged with the method readEndOfCentral :
  14461. * The end of central can coexist with its Zip64 brother,
  14462. * I don't want to read the wrong number of bytes !
  14463. */
  14464. readBlockZip64EndOfCentral: function() {
  14465. this.zip64EndOfCentralSize = this.reader.readInt(8);
  14466. this.versionMadeBy = this.reader.readString(2);
  14467. this.versionNeeded = this.reader.readInt(2);
  14468. this.diskNumber = this.reader.readInt(4);
  14469. this.diskWithCentralDirStart = this.reader.readInt(4);
  14470. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  14471. this.centralDirRecords = this.reader.readInt(8);
  14472. this.centralDirSize = this.reader.readInt(8);
  14473. this.centralDirOffset = this.reader.readInt(8);
  14474. this.zip64ExtensibleData = {};
  14475. var extraDataSize = this.zip64EndOfCentralSize - 44,
  14476. index = 0,
  14477. extraFieldId,
  14478. extraFieldLength,
  14479. extraFieldValue;
  14480. while (index < extraDataSize) {
  14481. extraFieldId = this.reader.readInt(2);
  14482. extraFieldLength = this.reader.readInt(4);
  14483. extraFieldValue = this.reader.readString(extraFieldLength);
  14484. this.zip64ExtensibleData[extraFieldId] = {
  14485. id: extraFieldId,
  14486. length: extraFieldLength,
  14487. value: extraFieldValue
  14488. };
  14489. }
  14490. },
  14491. /**
  14492. * Read the end of the Zip 64 central directory locator.
  14493. */
  14494. readBlockZip64EndOfCentralLocator: function() {
  14495. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  14496. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  14497. this.disksCount = this.reader.readInt(4);
  14498. if (this.disksCount > 1) {
  14499. throw new Error("Multi-volumes zip are not supported");
  14500. }
  14501. },
  14502. /**
  14503. * Read the local files, based on the offset read in the central part.
  14504. */
  14505. readLocalFiles: function() {
  14506. var i, file;
  14507. for (i = 0; i < this.files.length; i++) {
  14508. file = this.files[i];
  14509. this.reader.setIndex(file.localHeaderOffset);
  14510. this.checkSignature(sig.LOCAL_FILE_HEADER);
  14511. file.readLocalPart(this.reader);
  14512. file.handleUTF8();
  14513. file.processAttributes();
  14514. }
  14515. },
  14516. /**
  14517. * Read the central directory.
  14518. */
  14519. readCentralDir: function() {
  14520. var file;
  14521. this.reader.setIndex(this.centralDirOffset);
  14522. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  14523. file = new ZipEntry({
  14524. zip64: this.zip64
  14525. }, this.loadOptions);
  14526. file.readCentralPart(this.reader);
  14527. this.files.push(file);
  14528. }
  14529. },
  14530. /**
  14531. * Read the end of central directory.
  14532. */
  14533. readEndOfCentral: function() {
  14534. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  14535. if (offset === -1) {
  14536. // Check if the content is a truncated zip or complete garbage.
  14537. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  14538. // extractible zip for example) but it can give a good hint.
  14539. // If an ajax request was used without responseType, we will also
  14540. // get unreadable data.
  14541. var isGarbage = true;
  14542. try {
  14543. this.reader.setIndex(0);
  14544. this.checkSignature(sig.LOCAL_FILE_HEADER);
  14545. isGarbage = false;
  14546. } catch (e) {}
  14547. if (isGarbage) {
  14548. throw new Error("Can't find end of central directory : is this a zip file ? " +
  14549. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  14550. } else {
  14551. throw new Error("Corrupted zip : can't find end of central directory");
  14552. }
  14553. }
  14554. this.reader.setIndex(offset);
  14555. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  14556. this.readBlockEndOfCentral();
  14557. /* extract from the zip spec :
  14558. 4) If one of the fields in the end of central directory
  14559. record is too small to hold required data, the field
  14560. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  14561. ZIP64 format record should be created.
  14562. 5) The end of central directory record and the
  14563. Zip64 end of central directory locator record must
  14564. reside on the same disk when splitting or spanning
  14565. an archive.
  14566. */
  14567. 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) {
  14568. this.zip64 = true;
  14569. /*
  14570. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  14571. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  14572. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  14573. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  14574. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  14575. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  14576. */
  14577. // should look for a zip64 EOCD locator
  14578. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  14579. if (offset === -1) {
  14580. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  14581. }
  14582. this.reader.setIndex(offset);
  14583. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  14584. this.readBlockZip64EndOfCentralLocator();
  14585. // now the zip64 EOCD record
  14586. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  14587. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  14588. this.readBlockZip64EndOfCentral();
  14589. }
  14590. },
  14591. prepareReader: function(data) {
  14592. var type = utils.getTypeOf(data);
  14593. if (type === "string" && !support.uint8array) {
  14594. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  14595. }
  14596. else if (type === "nodebuffer") {
  14597. this.reader = new NodeBufferReader(data);
  14598. }
  14599. else {
  14600. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  14601. }
  14602. },
  14603. /**
  14604. * Read a zip file and create ZipEntries.
  14605. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  14606. */
  14607. load: function(data) {
  14608. this.prepareReader(data);
  14609. this.readEndOfCentral();
  14610. this.readCentralDir();
  14611. this.readLocalFiles();
  14612. }
  14613. };
  14614. // }}} end of ZipEntries
  14615. module.exports = ZipEntries;
  14616. },{"./nodeBufferReader":112,"./object":113,"./signature":114,"./stringReader":115,"./support":117,"./uint8ArrayReader":118,"./utils":121,"./zipEntry":123}],123:[function(require,module,exports){
  14617. 'use strict';
  14618. var StringReader = require('./stringReader');
  14619. var utils = require('./utils');
  14620. var CompressedObject = require('./compressedObject');
  14621. var jszipProto = require('./object');
  14622. var MADE_BY_DOS = 0x00;
  14623. var MADE_BY_UNIX = 0x03;
  14624. // class ZipEntry {{{
  14625. /**
  14626. * An entry in the zip file.
  14627. * @constructor
  14628. * @param {Object} options Options of the current file.
  14629. * @param {Object} loadOptions Options for loading the stream.
  14630. */
  14631. function ZipEntry(options, loadOptions) {
  14632. this.options = options;
  14633. this.loadOptions = loadOptions;
  14634. }
  14635. ZipEntry.prototype = {
  14636. /**
  14637. * say if the file is encrypted.
  14638. * @return {boolean} true if the file is encrypted, false otherwise.
  14639. */
  14640. isEncrypted: function() {
  14641. // bit 1 is set
  14642. return (this.bitFlag & 0x0001) === 0x0001;
  14643. },
  14644. /**
  14645. * say if the file has utf-8 filename/comment.
  14646. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  14647. */
  14648. useUTF8: function() {
  14649. // bit 11 is set
  14650. return (this.bitFlag & 0x0800) === 0x0800;
  14651. },
  14652. /**
  14653. * Prepare the function used to generate the compressed content from this ZipFile.
  14654. * @param {DataReader} reader the reader to use.
  14655. * @param {number} from the offset from where we should read the data.
  14656. * @param {number} length the length of the data to read.
  14657. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  14658. */
  14659. prepareCompressedContent: function(reader, from, length) {
  14660. return function() {
  14661. var previousIndex = reader.index;
  14662. reader.setIndex(from);
  14663. var compressedFileData = reader.readData(length);
  14664. reader.setIndex(previousIndex);
  14665. return compressedFileData;
  14666. };
  14667. },
  14668. /**
  14669. * Prepare the function used to generate the uncompressed content from this ZipFile.
  14670. * @param {DataReader} reader the reader to use.
  14671. * @param {number} from the offset from where we should read the data.
  14672. * @param {number} length the length of the data to read.
  14673. * @param {JSZip.compression} compression the compression used on this file.
  14674. * @param {number} uncompressedSize the uncompressed size to expect.
  14675. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  14676. */
  14677. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  14678. return function() {
  14679. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  14680. var uncompressedFileData = compression.uncompress(compressedFileData);
  14681. if (uncompressedFileData.length !== uncompressedSize) {
  14682. throw new Error("Bug : uncompressed data size mismatch");
  14683. }
  14684. return uncompressedFileData;
  14685. };
  14686. },
  14687. /**
  14688. * Read the local part of a zip file and add the info in this object.
  14689. * @param {DataReader} reader the reader to use.
  14690. */
  14691. readLocalPart: function(reader) {
  14692. var compression, localExtraFieldsLength;
  14693. // we already know everything from the central dir !
  14694. // If the central dir data are false, we are doomed.
  14695. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  14696. // The less data we get here, the more reliable this should be.
  14697. // Let's skip the whole header and dash to the data !
  14698. reader.skip(22);
  14699. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  14700. // Strangely, the filename here is OK.
  14701. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  14702. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  14703. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  14704. // the internet.
  14705. //
  14706. // I think I see the logic here : the central directory is used to display
  14707. // content and the local directory is used to extract the files. Mixing / and \
  14708. // may be used to display \ to windows users and use / when extracting the files.
  14709. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  14710. this.fileNameLength = reader.readInt(2);
  14711. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  14712. this.fileName = reader.readString(this.fileNameLength);
  14713. reader.skip(localExtraFieldsLength);
  14714. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  14715. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  14716. }
  14717. compression = utils.findCompression(this.compressionMethod);
  14718. if (compression === null) { // no compression found
  14719. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  14720. }
  14721. this.decompressed = new CompressedObject();
  14722. this.decompressed.compressedSize = this.compressedSize;
  14723. this.decompressed.uncompressedSize = this.uncompressedSize;
  14724. this.decompressed.crc32 = this.crc32;
  14725. this.decompressed.compressionMethod = this.compressionMethod;
  14726. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  14727. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  14728. // we need to compute the crc32...
  14729. if (this.loadOptions.checkCRC32) {
  14730. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  14731. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  14732. throw new Error("Corrupted zip : CRC32 mismatch");
  14733. }
  14734. }
  14735. },
  14736. /**
  14737. * Read the central part of a zip file and add the info in this object.
  14738. * @param {DataReader} reader the reader to use.
  14739. */
  14740. readCentralPart: function(reader) {
  14741. this.versionMadeBy = reader.readInt(2);
  14742. this.versionNeeded = reader.readInt(2);
  14743. this.bitFlag = reader.readInt(2);
  14744. this.compressionMethod = reader.readString(2);
  14745. this.date = reader.readDate();
  14746. this.crc32 = reader.readInt(4);
  14747. this.compressedSize = reader.readInt(4);
  14748. this.uncompressedSize = reader.readInt(4);
  14749. this.fileNameLength = reader.readInt(2);
  14750. this.extraFieldsLength = reader.readInt(2);
  14751. this.fileCommentLength = reader.readInt(2);
  14752. this.diskNumberStart = reader.readInt(2);
  14753. this.internalFileAttributes = reader.readInt(2);
  14754. this.externalFileAttributes = reader.readInt(4);
  14755. this.localHeaderOffset = reader.readInt(4);
  14756. if (this.isEncrypted()) {
  14757. throw new Error("Encrypted zip are not supported");
  14758. }
  14759. this.fileName = reader.readString(this.fileNameLength);
  14760. this.readExtraFields(reader);
  14761. this.parseZIP64ExtraField(reader);
  14762. this.fileComment = reader.readString(this.fileCommentLength);
  14763. },
  14764. /**
  14765. * Parse the external file attributes and get the unix/dos permissions.
  14766. */
  14767. processAttributes: function () {
  14768. this.unixPermissions = null;
  14769. this.dosPermissions = null;
  14770. var madeBy = this.versionMadeBy >> 8;
  14771. // Check if we have the DOS directory flag set.
  14772. // We look for it in the DOS and UNIX permissions
  14773. // but some unknown platform could set it as a compatibility flag.
  14774. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  14775. if(madeBy === MADE_BY_DOS) {
  14776. // first 6 bits (0 to 5)
  14777. this.dosPermissions = this.externalFileAttributes & 0x3F;
  14778. }
  14779. if(madeBy === MADE_BY_UNIX) {
  14780. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  14781. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  14782. }
  14783. // fail safe : if the name ends with a / it probably means a folder
  14784. if (!this.dir && this.fileName.slice(-1) === '/') {
  14785. this.dir = true;
  14786. }
  14787. },
  14788. /**
  14789. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  14790. * @param {DataReader} reader the reader to use.
  14791. */
  14792. parseZIP64ExtraField: function(reader) {
  14793. if (!this.extraFields[0x0001]) {
  14794. return;
  14795. }
  14796. // should be something, preparing the extra reader
  14797. var extraReader = new StringReader(this.extraFields[0x0001].value);
  14798. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  14799. // won't let us have more.
  14800. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  14801. this.uncompressedSize = extraReader.readInt(8);
  14802. }
  14803. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  14804. this.compressedSize = extraReader.readInt(8);
  14805. }
  14806. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  14807. this.localHeaderOffset = extraReader.readInt(8);
  14808. }
  14809. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  14810. this.diskNumberStart = extraReader.readInt(4);
  14811. }
  14812. },
  14813. /**
  14814. * Read the central part of a zip file and add the info in this object.
  14815. * @param {DataReader} reader the reader to use.
  14816. */
  14817. readExtraFields: function(reader) {
  14818. var start = reader.index,
  14819. extraFieldId,
  14820. extraFieldLength,
  14821. extraFieldValue;
  14822. this.extraFields = this.extraFields || {};
  14823. while (reader.index < start + this.extraFieldsLength) {
  14824. extraFieldId = reader.readInt(2);
  14825. extraFieldLength = reader.readInt(2);
  14826. extraFieldValue = reader.readString(extraFieldLength);
  14827. this.extraFields[extraFieldId] = {
  14828. id: extraFieldId,
  14829. length: extraFieldLength,
  14830. value: extraFieldValue
  14831. };
  14832. }
  14833. },
  14834. /**
  14835. * Apply an UTF8 transformation if needed.
  14836. */
  14837. handleUTF8: function() {
  14838. if (this.useUTF8()) {
  14839. this.fileName = jszipProto.utf8decode(this.fileName);
  14840. this.fileComment = jszipProto.utf8decode(this.fileComment);
  14841. } else {
  14842. var upath = this.findExtraFieldUnicodePath();
  14843. if (upath !== null) {
  14844. this.fileName = upath;
  14845. }
  14846. var ucomment = this.findExtraFieldUnicodeComment();
  14847. if (ucomment !== null) {
  14848. this.fileComment = ucomment;
  14849. }
  14850. }
  14851. },
  14852. /**
  14853. * Find the unicode path declared in the extra field, if any.
  14854. * @return {String} the unicode path, null otherwise.
  14855. */
  14856. findExtraFieldUnicodePath: function() {
  14857. var upathField = this.extraFields[0x7075];
  14858. if (upathField) {
  14859. var extraReader = new StringReader(upathField.value);
  14860. // wrong version
  14861. if (extraReader.readInt(1) !== 1) {
  14862. return null;
  14863. }
  14864. // the crc of the filename changed, this field is out of date.
  14865. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  14866. return null;
  14867. }
  14868. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  14869. }
  14870. return null;
  14871. },
  14872. /**
  14873. * Find the unicode comment declared in the extra field, if any.
  14874. * @return {String} the unicode comment, null otherwise.
  14875. */
  14876. findExtraFieldUnicodeComment: function() {
  14877. var ucommentField = this.extraFields[0x6375];
  14878. if (ucommentField) {
  14879. var extraReader = new StringReader(ucommentField.value);
  14880. // wrong version
  14881. if (extraReader.readInt(1) !== 1) {
  14882. return null;
  14883. }
  14884. // the crc of the comment changed, this field is out of date.
  14885. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  14886. return null;
  14887. }
  14888. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  14889. }
  14890. return null;
  14891. }
  14892. };
  14893. module.exports = ZipEntry;
  14894. },{"./compressedObject":102,"./object":113,"./stringReader":115,"./utils":121}],124:[function(require,module,exports){
  14895. // Top level file is just a mixin of submodules & constants
  14896. 'use strict';
  14897. var assign = require('./lib/utils/common').assign;
  14898. var deflate = require('./lib/deflate');
  14899. var inflate = require('./lib/inflate');
  14900. var constants = require('./lib/zlib/constants');
  14901. var pako = {};
  14902. assign(pako, deflate, inflate, constants);
  14903. module.exports = pako;
  14904. },{"./lib/deflate":125,"./lib/inflate":126,"./lib/utils/common":127,"./lib/zlib/constants":130}],125:[function(require,module,exports){
  14905. 'use strict';
  14906. var zlib_deflate = require('./zlib/deflate.js');
  14907. var utils = require('./utils/common');
  14908. var strings = require('./utils/strings');
  14909. var msg = require('./zlib/messages');
  14910. var zstream = require('./zlib/zstream');
  14911. var toString = Object.prototype.toString;
  14912. /* Public constants ==========================================================*/
  14913. /* ===========================================================================*/
  14914. var Z_NO_FLUSH = 0;
  14915. var Z_FINISH = 4;
  14916. var Z_OK = 0;
  14917. var Z_STREAM_END = 1;
  14918. var Z_SYNC_FLUSH = 2;
  14919. var Z_DEFAULT_COMPRESSION = -1;
  14920. var Z_DEFAULT_STRATEGY = 0;
  14921. var Z_DEFLATED = 8;
  14922. /* ===========================================================================*/
  14923. /**
  14924. * class Deflate
  14925. *
  14926. * Generic JS-style wrapper for zlib calls. If you don't need
  14927. * streaming behaviour - use more simple functions: [[deflate]],
  14928. * [[deflateRaw]] and [[gzip]].
  14929. **/
  14930. /* internal
  14931. * Deflate.chunks -> Array
  14932. *
  14933. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14934. **/
  14935. /**
  14936. * Deflate.result -> Uint8Array|Array
  14937. *
  14938. * Compressed result, generated by default [[Deflate#onData]]
  14939. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14940. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14941. * push a chunk with explicit flush (call [[Deflate#push]] with
  14942. * `Z_SYNC_FLUSH` param).
  14943. **/
  14944. /**
  14945. * Deflate.err -> Number
  14946. *
  14947. * Error code after deflate finished. 0 (Z_OK) on success.
  14948. * You will not need it in real life, because deflate errors
  14949. * are possible only on wrong options or bad `onData` / `onEnd`
  14950. * custom handlers.
  14951. **/
  14952. /**
  14953. * Deflate.msg -> String
  14954. *
  14955. * Error message, if [[Deflate.err]] != 0
  14956. **/
  14957. /**
  14958. * new Deflate(options)
  14959. * - options (Object): zlib deflate options.
  14960. *
  14961. * Creates new deflator instance with specified params. Throws exception
  14962. * on bad params. Supported options:
  14963. *
  14964. * - `level`
  14965. * - `windowBits`
  14966. * - `memLevel`
  14967. * - `strategy`
  14968. *
  14969. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14970. * for more information on these.
  14971. *
  14972. * Additional options, for internal needs:
  14973. *
  14974. * - `chunkSize` - size of generated data chunks (16K by default)
  14975. * - `raw` (Boolean) - do raw deflate
  14976. * - `gzip` (Boolean) - create gzip wrapper
  14977. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14978. * (each char code [0..255])
  14979. * - `header` (Object) - custom header for gzip
  14980. * - `text` (Boolean) - true if compressed data believed to be text
  14981. * - `time` (Number) - modification time, unix timestamp
  14982. * - `os` (Number) - operation system code
  14983. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14984. * - `name` (String) - file name (binary string)
  14985. * - `comment` (String) - comment (binary string)
  14986. * - `hcrc` (Boolean) - true if header crc should be added
  14987. *
  14988. * ##### Example:
  14989. *
  14990. * ```javascript
  14991. * var pako = require('pako')
  14992. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14993. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14994. *
  14995. * var deflate = new pako.Deflate({ level: 3});
  14996. *
  14997. * deflate.push(chunk1, false);
  14998. * deflate.push(chunk2, true); // true -> last chunk
  14999. *
  15000. * if (deflate.err) { throw new Error(deflate.err); }
  15001. *
  15002. * console.log(deflate.result);
  15003. * ```
  15004. **/
  15005. var Deflate = function(options) {
  15006. this.options = utils.assign({
  15007. level: Z_DEFAULT_COMPRESSION,
  15008. method: Z_DEFLATED,
  15009. chunkSize: 16384,
  15010. windowBits: 15,
  15011. memLevel: 8,
  15012. strategy: Z_DEFAULT_STRATEGY,
  15013. to: ''
  15014. }, options || {});
  15015. var opt = this.options;
  15016. if (opt.raw && (opt.windowBits > 0)) {
  15017. opt.windowBits = -opt.windowBits;
  15018. }
  15019. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  15020. opt.windowBits += 16;
  15021. }
  15022. this.err = 0; // error code, if happens (0 = Z_OK)
  15023. this.msg = ''; // error message
  15024. this.ended = false; // used to avoid multiple onEnd() calls
  15025. this.chunks = []; // chunks of compressed data
  15026. this.strm = new zstream();
  15027. this.strm.avail_out = 0;
  15028. var status = zlib_deflate.deflateInit2(
  15029. this.strm,
  15030. opt.level,
  15031. opt.method,
  15032. opt.windowBits,
  15033. opt.memLevel,
  15034. opt.strategy
  15035. );
  15036. if (status !== Z_OK) {
  15037. throw new Error(msg[status]);
  15038. }
  15039. if (opt.header) {
  15040. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  15041. }
  15042. };
  15043. /**
  15044. * Deflate#push(data[, mode]) -> Boolean
  15045. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  15046. * converted to utf8 byte sequence.
  15047. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15048. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15049. *
  15050. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  15051. * new compressed chunks. Returns `true` on success. The last data block must have
  15052. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15053. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15054. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  15055. *
  15056. * On fail call [[Deflate#onEnd]] with error code and return false.
  15057. *
  15058. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15059. * array format is detected automatically). Also, don't skip last param and always
  15060. * use the same type in your code (boolean or number). That will improve JS speed.
  15061. *
  15062. * For regular `Array`-s make sure all elements are [0..255].
  15063. *
  15064. * ##### Example
  15065. *
  15066. * ```javascript
  15067. * push(chunk, false); // push one of data chunks
  15068. * ...
  15069. * push(chunk, true); // push last chunk
  15070. * ```
  15071. **/
  15072. Deflate.prototype.push = function(data, mode) {
  15073. var strm = this.strm;
  15074. var chunkSize = this.options.chunkSize;
  15075. var status, _mode;
  15076. if (this.ended) { return false; }
  15077. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  15078. // Convert data if needed
  15079. if (typeof data === 'string') {
  15080. // If we need to compress text, change encoding to utf8.
  15081. strm.input = strings.string2buf(data);
  15082. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15083. strm.input = new Uint8Array(data);
  15084. } else {
  15085. strm.input = data;
  15086. }
  15087. strm.next_in = 0;
  15088. strm.avail_in = strm.input.length;
  15089. do {
  15090. if (strm.avail_out === 0) {
  15091. strm.output = new utils.Buf8(chunkSize);
  15092. strm.next_out = 0;
  15093. strm.avail_out = chunkSize;
  15094. }
  15095. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  15096. if (status !== Z_STREAM_END && status !== Z_OK) {
  15097. this.onEnd(status);
  15098. this.ended = true;
  15099. return false;
  15100. }
  15101. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  15102. if (this.options.to === 'string') {
  15103. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  15104. } else {
  15105. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15106. }
  15107. }
  15108. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  15109. // Finalize on the last chunk.
  15110. if (_mode === Z_FINISH) {
  15111. status = zlib_deflate.deflateEnd(this.strm);
  15112. this.onEnd(status);
  15113. this.ended = true;
  15114. return status === Z_OK;
  15115. }
  15116. // callback interim results if Z_SYNC_FLUSH.
  15117. if (_mode === Z_SYNC_FLUSH) {
  15118. this.onEnd(Z_OK);
  15119. strm.avail_out = 0;
  15120. return true;
  15121. }
  15122. return true;
  15123. };
  15124. /**
  15125. * Deflate#onData(chunk) -> Void
  15126. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15127. * on js engine support. When string output requested, each chunk
  15128. * will be string.
  15129. *
  15130. * By default, stores data blocks in `chunks[]` property and glue
  15131. * those in `onEnd`. Override this handler, if you need another behaviour.
  15132. **/
  15133. Deflate.prototype.onData = function(chunk) {
  15134. this.chunks.push(chunk);
  15135. };
  15136. /**
  15137. * Deflate#onEnd(status) -> Void
  15138. * - status (Number): deflate status. 0 (Z_OK) on success,
  15139. * other if not.
  15140. *
  15141. * Called once after you tell deflate that the input stream is
  15142. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15143. * or if an error happened. By default - join collected chunks,
  15144. * free memory and fill `results` / `err` properties.
  15145. **/
  15146. Deflate.prototype.onEnd = function(status) {
  15147. // On success - join
  15148. if (status === Z_OK) {
  15149. if (this.options.to === 'string') {
  15150. this.result = this.chunks.join('');
  15151. } else {
  15152. this.result = utils.flattenChunks(this.chunks);
  15153. }
  15154. }
  15155. this.chunks = [];
  15156. this.err = status;
  15157. this.msg = this.strm.msg;
  15158. };
  15159. /**
  15160. * deflate(data[, options]) -> Uint8Array|Array|String
  15161. * - data (Uint8Array|Array|String): input data to compress.
  15162. * - options (Object): zlib deflate options.
  15163. *
  15164. * Compress `data` with deflate alrorythm and `options`.
  15165. *
  15166. * Supported options are:
  15167. *
  15168. * - level
  15169. * - windowBits
  15170. * - memLevel
  15171. * - strategy
  15172. *
  15173. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15174. * for more information on these.
  15175. *
  15176. * Sugar (options):
  15177. *
  15178. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15179. * negative windowBits implicitly.
  15180. * - `to` (String) - if equal to 'string', then result will be "binary string"
  15181. * (each char code [0..255])
  15182. *
  15183. * ##### Example:
  15184. *
  15185. * ```javascript
  15186. * var pako = require('pako')
  15187. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  15188. *
  15189. * console.log(pako.deflate(data));
  15190. * ```
  15191. **/
  15192. function deflate(input, options) {
  15193. var deflator = new Deflate(options);
  15194. deflator.push(input, true);
  15195. // That will never happens, if you don't cheat with options :)
  15196. if (deflator.err) { throw deflator.msg; }
  15197. return deflator.result;
  15198. }
  15199. /**
  15200. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  15201. * - data (Uint8Array|Array|String): input data to compress.
  15202. * - options (Object): zlib deflate options.
  15203. *
  15204. * The same as [[deflate]], but creates raw data, without wrapper
  15205. * (header and adler32 crc).
  15206. **/
  15207. function deflateRaw(input, options) {
  15208. options = options || {};
  15209. options.raw = true;
  15210. return deflate(input, options);
  15211. }
  15212. /**
  15213. * gzip(data[, options]) -> Uint8Array|Array|String
  15214. * - data (Uint8Array|Array|String): input data to compress.
  15215. * - options (Object): zlib deflate options.
  15216. *
  15217. * The same as [[deflate]], but create gzip wrapper instead of
  15218. * deflate one.
  15219. **/
  15220. function gzip(input, options) {
  15221. options = options || {};
  15222. options.gzip = true;
  15223. return deflate(input, options);
  15224. }
  15225. exports.Deflate = Deflate;
  15226. exports.deflate = deflate;
  15227. exports.deflateRaw = deflateRaw;
  15228. exports.gzip = gzip;
  15229. },{"./utils/common":127,"./utils/strings":128,"./zlib/deflate.js":132,"./zlib/messages":137,"./zlib/zstream":139}],126:[function(require,module,exports){
  15230. 'use strict';
  15231. var zlib_inflate = require('./zlib/inflate.js');
  15232. var utils = require('./utils/common');
  15233. var strings = require('./utils/strings');
  15234. var c = require('./zlib/constants');
  15235. var msg = require('./zlib/messages');
  15236. var zstream = require('./zlib/zstream');
  15237. var gzheader = require('./zlib/gzheader');
  15238. var toString = Object.prototype.toString;
  15239. /**
  15240. * class Inflate
  15241. *
  15242. * Generic JS-style wrapper for zlib calls. If you don't need
  15243. * streaming behaviour - use more simple functions: [[inflate]]
  15244. * and [[inflateRaw]].
  15245. **/
  15246. /* internal
  15247. * inflate.chunks -> Array
  15248. *
  15249. * Chunks of output data, if [[Inflate#onData]] not overriden.
  15250. **/
  15251. /**
  15252. * Inflate.result -> Uint8Array|Array|String
  15253. *
  15254. * Uncompressed result, generated by default [[Inflate#onData]]
  15255. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  15256. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  15257. * push a chunk with explicit flush (call [[Inflate#push]] with
  15258. * `Z_SYNC_FLUSH` param).
  15259. **/
  15260. /**
  15261. * Inflate.err -> Number
  15262. *
  15263. * Error code after inflate finished. 0 (Z_OK) on success.
  15264. * Should be checked if broken data possible.
  15265. **/
  15266. /**
  15267. * Inflate.msg -> String
  15268. *
  15269. * Error message, if [[Inflate.err]] != 0
  15270. **/
  15271. /**
  15272. * new Inflate(options)
  15273. * - options (Object): zlib inflate options.
  15274. *
  15275. * Creates new inflator instance with specified params. Throws exception
  15276. * on bad params. Supported options:
  15277. *
  15278. * - `windowBits`
  15279. *
  15280. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15281. * for more information on these.
  15282. *
  15283. * Additional options, for internal needs:
  15284. *
  15285. * - `chunkSize` - size of generated data chunks (16K by default)
  15286. * - `raw` (Boolean) - do raw inflate
  15287. * - `to` (String) - if equal to 'string', then result will be converted
  15288. * from utf8 to utf16 (javascript) string. When string output requested,
  15289. * chunk length can differ from `chunkSize`, depending on content.
  15290. *
  15291. * By default, when no options set, autodetect deflate/gzip data format via
  15292. * wrapper header.
  15293. *
  15294. * ##### Example:
  15295. *
  15296. * ```javascript
  15297. * var pako = require('pako')
  15298. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  15299. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  15300. *
  15301. * var inflate = new pako.Inflate({ level: 3});
  15302. *
  15303. * inflate.push(chunk1, false);
  15304. * inflate.push(chunk2, true); // true -> last chunk
  15305. *
  15306. * if (inflate.err) { throw new Error(inflate.err); }
  15307. *
  15308. * console.log(inflate.result);
  15309. * ```
  15310. **/
  15311. var Inflate = function(options) {
  15312. this.options = utils.assign({
  15313. chunkSize: 16384,
  15314. windowBits: 0,
  15315. to: ''
  15316. }, options || {});
  15317. var opt = this.options;
  15318. // Force window size for `raw` data, if not set directly,
  15319. // because we have no header for autodetect.
  15320. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  15321. opt.windowBits = -opt.windowBits;
  15322. if (opt.windowBits === 0) { opt.windowBits = -15; }
  15323. }
  15324. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  15325. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  15326. !(options && options.windowBits)) {
  15327. opt.windowBits += 32;
  15328. }
  15329. // Gzip header has no info about windows size, we can do autodetect only
  15330. // for deflate. So, if window size not set, force it to max when gzip possible
  15331. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  15332. // bit 3 (16) -> gzipped data
  15333. // bit 4 (32) -> autodetect gzip/deflate
  15334. if ((opt.windowBits & 15) === 0) {
  15335. opt.windowBits |= 15;
  15336. }
  15337. }
  15338. this.err = 0; // error code, if happens (0 = Z_OK)
  15339. this.msg = ''; // error message
  15340. this.ended = false; // used to avoid multiple onEnd() calls
  15341. this.chunks = []; // chunks of compressed data
  15342. this.strm = new zstream();
  15343. this.strm.avail_out = 0;
  15344. var status = zlib_inflate.inflateInit2(
  15345. this.strm,
  15346. opt.windowBits
  15347. );
  15348. if (status !== c.Z_OK) {
  15349. throw new Error(msg[status]);
  15350. }
  15351. this.header = new gzheader();
  15352. zlib_inflate.inflateGetHeader(this.strm, this.header);
  15353. };
  15354. /**
  15355. * Inflate#push(data[, mode]) -> Boolean
  15356. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  15357. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15358. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15359. *
  15360. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  15361. * new output chunks. Returns `true` on success. The last data block must have
  15362. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15363. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15364. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15365. *
  15366. * On fail call [[Inflate#onEnd]] with error code and return false.
  15367. *
  15368. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15369. * format is detected automatically). Also, don't skip last param and always
  15370. * use the same type in your code (boolean or number). That will improve JS speed.
  15371. *
  15372. * For regular `Array`-s make sure all elements are [0..255].
  15373. *
  15374. * ##### Example
  15375. *
  15376. * ```javascript
  15377. * push(chunk, false); // push one of data chunks
  15378. * ...
  15379. * push(chunk, true); // push last chunk
  15380. * ```
  15381. **/
  15382. Inflate.prototype.push = function(data, mode) {
  15383. var strm = this.strm;
  15384. var chunkSize = this.options.chunkSize;
  15385. var status, _mode;
  15386. var next_out_utf8, tail, utf8str;
  15387. if (this.ended) { return false; }
  15388. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15389. // Convert data if needed
  15390. if (typeof data === 'string') {
  15391. // Only binary strings can be decompressed on practice
  15392. strm.input = strings.binstring2buf(data);
  15393. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15394. strm.input = new Uint8Array(data);
  15395. } else {
  15396. strm.input = data;
  15397. }
  15398. strm.next_in = 0;
  15399. strm.avail_in = strm.input.length;
  15400. do {
  15401. if (strm.avail_out === 0) {
  15402. strm.output = new utils.Buf8(chunkSize);
  15403. strm.next_out = 0;
  15404. strm.avail_out = chunkSize;
  15405. }
  15406. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15407. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15408. this.onEnd(status);
  15409. this.ended = true;
  15410. return false;
  15411. }
  15412. if (strm.next_out) {
  15413. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15414. if (this.options.to === 'string') {
  15415. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15416. tail = strm.next_out - next_out_utf8;
  15417. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15418. // move tail
  15419. strm.next_out = tail;
  15420. strm.avail_out = chunkSize - tail;
  15421. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15422. this.onData(utf8str);
  15423. } else {
  15424. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15425. }
  15426. }
  15427. }
  15428. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  15429. if (status === c.Z_STREAM_END) {
  15430. _mode = c.Z_FINISH;
  15431. }
  15432. // Finalize on the last chunk.
  15433. if (_mode === c.Z_FINISH) {
  15434. status = zlib_inflate.inflateEnd(this.strm);
  15435. this.onEnd(status);
  15436. this.ended = true;
  15437. return status === c.Z_OK;
  15438. }
  15439. // callback interim results if Z_SYNC_FLUSH.
  15440. if (_mode === c.Z_SYNC_FLUSH) {
  15441. this.onEnd(c.Z_OK);
  15442. strm.avail_out = 0;
  15443. return true;
  15444. }
  15445. return true;
  15446. };
  15447. /**
  15448. * Inflate#onData(chunk) -> Void
  15449. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15450. * on js engine support. When string output requested, each chunk
  15451. * will be string.
  15452. *
  15453. * By default, stores data blocks in `chunks[]` property and glue
  15454. * those in `onEnd`. Override this handler, if you need another behaviour.
  15455. **/
  15456. Inflate.prototype.onData = function(chunk) {
  15457. this.chunks.push(chunk);
  15458. };
  15459. /**
  15460. * Inflate#onEnd(status) -> Void
  15461. * - status (Number): inflate status. 0 (Z_OK) on success,
  15462. * other if not.
  15463. *
  15464. * Called either after you tell inflate that the input stream is
  15465. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15466. * or if an error happened. By default - join collected chunks,
  15467. * free memory and fill `results` / `err` properties.
  15468. **/
  15469. Inflate.prototype.onEnd = function(status) {
  15470. // On success - join
  15471. if (status === c.Z_OK) {
  15472. if (this.options.to === 'string') {
  15473. // Glue & convert here, until we teach pako to send
  15474. // utf8 alligned strings to onData
  15475. this.result = this.chunks.join('');
  15476. } else {
  15477. this.result = utils.flattenChunks(this.chunks);
  15478. }
  15479. }
  15480. this.chunks = [];
  15481. this.err = status;
  15482. this.msg = this.strm.msg;
  15483. };
  15484. /**
  15485. * inflate(data[, options]) -> Uint8Array|Array|String
  15486. * - data (Uint8Array|Array|String): input data to decompress.
  15487. * - options (Object): zlib inflate options.
  15488. *
  15489. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15490. * format via wrapper header by default. That's why we don't provide
  15491. * separate `ungzip` method.
  15492. *
  15493. * Supported options are:
  15494. *
  15495. * - windowBits
  15496. *
  15497. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15498. * for more information.
  15499. *
  15500. * Sugar (options):
  15501. *
  15502. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15503. * negative windowBits implicitly.
  15504. * - `to` (String) - if equal to 'string', then result will be converted
  15505. * from utf8 to utf16 (javascript) string. When string output requested,
  15506. * chunk length can differ from `chunkSize`, depending on content.
  15507. *
  15508. *
  15509. * ##### Example:
  15510. *
  15511. * ```javascript
  15512. * var pako = require('pako')
  15513. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15514. * , output;
  15515. *
  15516. * try {
  15517. * output = pako.inflate(input);
  15518. * } catch (err)
  15519. * console.log(err);
  15520. * }
  15521. * ```
  15522. **/
  15523. function inflate(input, options) {
  15524. var inflator = new Inflate(options);
  15525. inflator.push(input, true);
  15526. // That will never happens, if you don't cheat with options :)
  15527. if (inflator.err) { throw inflator.msg; }
  15528. return inflator.result;
  15529. }
  15530. /**
  15531. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15532. * - data (Uint8Array|Array|String): input data to decompress.
  15533. * - options (Object): zlib inflate options.
  15534. *
  15535. * The same as [[inflate]], but creates raw data, without wrapper
  15536. * (header and adler32 crc).
  15537. **/
  15538. function inflateRaw(input, options) {
  15539. options = options || {};
  15540. options.raw = true;
  15541. return inflate(input, options);
  15542. }
  15543. /**
  15544. * ungzip(data[, options]) -> Uint8Array|Array|String
  15545. * - data (Uint8Array|Array|String): input data to decompress.
  15546. * - options (Object): zlib inflate options.
  15547. *
  15548. * Just shortcut to [[inflate]], because it autodetects format
  15549. * by header.content. Done for convenience.
  15550. **/
  15551. exports.Inflate = Inflate;
  15552. exports.inflate = inflate;
  15553. exports.inflateRaw = inflateRaw;
  15554. exports.ungzip = inflate;
  15555. },{"./utils/common":127,"./utils/strings":128,"./zlib/constants":130,"./zlib/gzheader":133,"./zlib/inflate.js":135,"./zlib/messages":137,"./zlib/zstream":139}],127:[function(require,module,exports){
  15556. 'use strict';
  15557. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15558. (typeof Uint16Array !== 'undefined') &&
  15559. (typeof Int32Array !== 'undefined');
  15560. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15561. var sources = Array.prototype.slice.call(arguments, 1);
  15562. while (sources.length) {
  15563. var source = sources.shift();
  15564. if (!source) { continue; }
  15565. if (typeof source !== 'object') {
  15566. throw new TypeError(source + 'must be non-object');
  15567. }
  15568. for (var p in source) {
  15569. if (source.hasOwnProperty(p)) {
  15570. obj[p] = source[p];
  15571. }
  15572. }
  15573. }
  15574. return obj;
  15575. };
  15576. // reduce buffer size, avoiding mem copy
  15577. exports.shrinkBuf = function (buf, size) {
  15578. if (buf.length === size) { return buf; }
  15579. if (buf.subarray) { return buf.subarray(0, size); }
  15580. buf.length = size;
  15581. return buf;
  15582. };
  15583. var fnTyped = {
  15584. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15585. if (src.subarray && dest.subarray) {
  15586. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15587. return;
  15588. }
  15589. // Fallback to ordinary array
  15590. for (var i=0; i<len; i++) {
  15591. dest[dest_offs + i] = src[src_offs + i];
  15592. }
  15593. },
  15594. // Join array of chunks to single array.
  15595. flattenChunks: function(chunks) {
  15596. var i, l, len, pos, chunk, result;
  15597. // calculate data length
  15598. len = 0;
  15599. for (i=0, l=chunks.length; i<l; i++) {
  15600. len += chunks[i].length;
  15601. }
  15602. // join chunks
  15603. result = new Uint8Array(len);
  15604. pos = 0;
  15605. for (i=0, l=chunks.length; i<l; i++) {
  15606. chunk = chunks[i];
  15607. result.set(chunk, pos);
  15608. pos += chunk.length;
  15609. }
  15610. return result;
  15611. }
  15612. };
  15613. var fnUntyped = {
  15614. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15615. for (var i=0; i<len; i++) {
  15616. dest[dest_offs + i] = src[src_offs + i];
  15617. }
  15618. },
  15619. // Join array of chunks to single array.
  15620. flattenChunks: function(chunks) {
  15621. return [].concat.apply([], chunks);
  15622. }
  15623. };
  15624. // Enable/Disable typed arrays use, for testing
  15625. //
  15626. exports.setTyped = function (on) {
  15627. if (on) {
  15628. exports.Buf8 = Uint8Array;
  15629. exports.Buf16 = Uint16Array;
  15630. exports.Buf32 = Int32Array;
  15631. exports.assign(exports, fnTyped);
  15632. } else {
  15633. exports.Buf8 = Array;
  15634. exports.Buf16 = Array;
  15635. exports.Buf32 = Array;
  15636. exports.assign(exports, fnUntyped);
  15637. }
  15638. };
  15639. exports.setTyped(TYPED_OK);
  15640. },{}],128:[function(require,module,exports){
  15641. // String encode/decode helpers
  15642. 'use strict';
  15643. var utils = require('./common');
  15644. // Quick check if we can use fast array to bin string conversion
  15645. //
  15646. // - apply(Array) can fail on Android 2.2
  15647. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15648. //
  15649. var STR_APPLY_OK = true;
  15650. var STR_APPLY_UIA_OK = true;
  15651. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15652. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15653. // Table with utf8 lengths (calculated by first byte of sequence)
  15654. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15655. // because max possible codepoint is 0x10ffff
  15656. var _utf8len = new utils.Buf8(256);
  15657. for (var q=0; q<256; q++) {
  15658. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15659. }
  15660. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15661. // convert string to array (typed, when possible)
  15662. exports.string2buf = function (str) {
  15663. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15664. // count binary size
  15665. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15666. c = str.charCodeAt(m_pos);
  15667. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15668. c2 = str.charCodeAt(m_pos+1);
  15669. if ((c2 & 0xfc00) === 0xdc00) {
  15670. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15671. m_pos++;
  15672. }
  15673. }
  15674. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15675. }
  15676. // allocate buffer
  15677. buf = new utils.Buf8(buf_len);
  15678. // convert
  15679. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15680. c = str.charCodeAt(m_pos);
  15681. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15682. c2 = str.charCodeAt(m_pos+1);
  15683. if ((c2 & 0xfc00) === 0xdc00) {
  15684. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15685. m_pos++;
  15686. }
  15687. }
  15688. if (c < 0x80) {
  15689. /* one byte */
  15690. buf[i++] = c;
  15691. } else if (c < 0x800) {
  15692. /* two bytes */
  15693. buf[i++] = 0xC0 | (c >>> 6);
  15694. buf[i++] = 0x80 | (c & 0x3f);
  15695. } else if (c < 0x10000) {
  15696. /* three bytes */
  15697. buf[i++] = 0xE0 | (c >>> 12);
  15698. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15699. buf[i++] = 0x80 | (c & 0x3f);
  15700. } else {
  15701. /* four bytes */
  15702. buf[i++] = 0xf0 | (c >>> 18);
  15703. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15704. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15705. buf[i++] = 0x80 | (c & 0x3f);
  15706. }
  15707. }
  15708. return buf;
  15709. };
  15710. // Helper (used in 2 places)
  15711. function buf2binstring(buf, len) {
  15712. // use fallback for big arrays to avoid stack overflow
  15713. if (len < 65537) {
  15714. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15715. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15716. }
  15717. }
  15718. var result = '';
  15719. for (var i=0; i < len; i++) {
  15720. result += String.fromCharCode(buf[i]);
  15721. }
  15722. return result;
  15723. }
  15724. // Convert byte array to binary string
  15725. exports.buf2binstring = function(buf) {
  15726. return buf2binstring(buf, buf.length);
  15727. };
  15728. // Convert binary string (typed, when possible)
  15729. exports.binstring2buf = function(str) {
  15730. var buf = new utils.Buf8(str.length);
  15731. for (var i=0, len=buf.length; i < len; i++) {
  15732. buf[i] = str.charCodeAt(i);
  15733. }
  15734. return buf;
  15735. };
  15736. // convert array to string
  15737. exports.buf2string = function (buf, max) {
  15738. var i, out, c, c_len;
  15739. var len = max || buf.length;
  15740. // Reserve max possible length (2 words per char)
  15741. // NB: by unknown reasons, Array is significantly faster for
  15742. // String.fromCharCode.apply than Uint16Array.
  15743. var utf16buf = new Array(len*2);
  15744. for (out=0, i=0; i<len;) {
  15745. c = buf[i++];
  15746. // quick process ascii
  15747. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15748. c_len = _utf8len[c];
  15749. // skip 5 & 6 byte codes
  15750. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15751. // apply mask on first byte
  15752. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15753. // join the rest
  15754. while (c_len > 1 && i < len) {
  15755. c = (c << 6) | (buf[i++] & 0x3f);
  15756. c_len--;
  15757. }
  15758. // terminated by end of string?
  15759. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15760. if (c < 0x10000) {
  15761. utf16buf[out++] = c;
  15762. } else {
  15763. c -= 0x10000;
  15764. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15765. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15766. }
  15767. }
  15768. return buf2binstring(utf16buf, out);
  15769. };
  15770. // Calculate max possible position in utf8 buffer,
  15771. // that will not break sequence. If that's not possible
  15772. // - (very small limits) return max size as is.
  15773. //
  15774. // buf[] - utf8 bytes array
  15775. // max - length limit (mandatory);
  15776. exports.utf8border = function(buf, max) {
  15777. var pos;
  15778. max = max || buf.length;
  15779. if (max > buf.length) { max = buf.length; }
  15780. // go back from last position, until start of sequence found
  15781. pos = max-1;
  15782. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15783. // Fuckup - very small and broken sequence,
  15784. // return max, because we should return something anyway.
  15785. if (pos < 0) { return max; }
  15786. // If we came to start of buffer - that means vuffer is too small,
  15787. // return max too.
  15788. if (pos === 0) { return max; }
  15789. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15790. };
  15791. },{"./common":127}],129:[function(require,module,exports){
  15792. 'use strict';
  15793. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15794. // It doesn't worth to make additional optimizationa as in original.
  15795. // Small size is preferable.
  15796. function adler32(adler, buf, len, pos) {
  15797. var s1 = (adler & 0xffff) |0,
  15798. s2 = ((adler >>> 16) & 0xffff) |0,
  15799. n = 0;
  15800. while (len !== 0) {
  15801. // Set limit ~ twice less than 5552, to keep
  15802. // s2 in 31-bits, because we force signed ints.
  15803. // in other case %= will fail.
  15804. n = len > 2000 ? 2000 : len;
  15805. len -= n;
  15806. do {
  15807. s1 = (s1 + buf[pos++]) |0;
  15808. s2 = (s2 + s1) |0;
  15809. } while (--n);
  15810. s1 %= 65521;
  15811. s2 %= 65521;
  15812. }
  15813. return (s1 | (s2 << 16)) |0;
  15814. }
  15815. module.exports = adler32;
  15816. },{}],130:[function(require,module,exports){
  15817. module.exports = {
  15818. /* Allowed flush values; see deflate() and inflate() below for details */
  15819. Z_NO_FLUSH: 0,
  15820. Z_PARTIAL_FLUSH: 1,
  15821. Z_SYNC_FLUSH: 2,
  15822. Z_FULL_FLUSH: 3,
  15823. Z_FINISH: 4,
  15824. Z_BLOCK: 5,
  15825. Z_TREES: 6,
  15826. /* Return codes for the compression/decompression functions. Negative values
  15827. * are errors, positive values are used for special but normal events.
  15828. */
  15829. Z_OK: 0,
  15830. Z_STREAM_END: 1,
  15831. Z_NEED_DICT: 2,
  15832. Z_ERRNO: -1,
  15833. Z_STREAM_ERROR: -2,
  15834. Z_DATA_ERROR: -3,
  15835. //Z_MEM_ERROR: -4,
  15836. Z_BUF_ERROR: -5,
  15837. //Z_VERSION_ERROR: -6,
  15838. /* compression levels */
  15839. Z_NO_COMPRESSION: 0,
  15840. Z_BEST_SPEED: 1,
  15841. Z_BEST_COMPRESSION: 9,
  15842. Z_DEFAULT_COMPRESSION: -1,
  15843. Z_FILTERED: 1,
  15844. Z_HUFFMAN_ONLY: 2,
  15845. Z_RLE: 3,
  15846. Z_FIXED: 4,
  15847. Z_DEFAULT_STRATEGY: 0,
  15848. /* Possible values of the data_type field (though see inflate()) */
  15849. Z_BINARY: 0,
  15850. Z_TEXT: 1,
  15851. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15852. Z_UNKNOWN: 2,
  15853. /* The deflate compression method */
  15854. Z_DEFLATED: 8
  15855. //Z_NULL: null // Use -1 or null inline, depending on var type
  15856. };
  15857. },{}],131:[function(require,module,exports){
  15858. 'use strict';
  15859. // Note: we can't get significant speed boost here.
  15860. // So write code to minimize size - no pregenerated tables
  15861. // and array tools dependencies.
  15862. // Use ordinary array, since untyped makes no boost here
  15863. function makeTable() {
  15864. var c, table = [];
  15865. for (var n =0; n < 256; n++) {
  15866. c = n;
  15867. for (var k =0; k < 8; k++) {
  15868. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15869. }
  15870. table[n] = c;
  15871. }
  15872. return table;
  15873. }
  15874. // Create table on load. Just 255 signed longs. Not a problem.
  15875. var crcTable = makeTable();
  15876. function crc32(crc, buf, len, pos) {
  15877. var t = crcTable,
  15878. end = pos + len;
  15879. crc = crc ^ (-1);
  15880. for (var i = pos; i < end; i++) {
  15881. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15882. }
  15883. return (crc ^ (-1)); // >>> 0;
  15884. }
  15885. module.exports = crc32;
  15886. },{}],132:[function(require,module,exports){
  15887. 'use strict';
  15888. var utils = require('../utils/common');
  15889. var trees = require('./trees');
  15890. var adler32 = require('./adler32');
  15891. var crc32 = require('./crc32');
  15892. var msg = require('./messages');
  15893. /* Public constants ==========================================================*/
  15894. /* ===========================================================================*/
  15895. /* Allowed flush values; see deflate() and inflate() below for details */
  15896. var Z_NO_FLUSH = 0;
  15897. var Z_PARTIAL_FLUSH = 1;
  15898. //var Z_SYNC_FLUSH = 2;
  15899. var Z_FULL_FLUSH = 3;
  15900. var Z_FINISH = 4;
  15901. var Z_BLOCK = 5;
  15902. //var Z_TREES = 6;
  15903. /* Return codes for the compression/decompression functions. Negative values
  15904. * are errors, positive values are used for special but normal events.
  15905. */
  15906. var Z_OK = 0;
  15907. var Z_STREAM_END = 1;
  15908. //var Z_NEED_DICT = 2;
  15909. //var Z_ERRNO = -1;
  15910. var Z_STREAM_ERROR = -2;
  15911. var Z_DATA_ERROR = -3;
  15912. //var Z_MEM_ERROR = -4;
  15913. var Z_BUF_ERROR = -5;
  15914. //var Z_VERSION_ERROR = -6;
  15915. /* compression levels */
  15916. //var Z_NO_COMPRESSION = 0;
  15917. //var Z_BEST_SPEED = 1;
  15918. //var Z_BEST_COMPRESSION = 9;
  15919. var Z_DEFAULT_COMPRESSION = -1;
  15920. var Z_FILTERED = 1;
  15921. var Z_HUFFMAN_ONLY = 2;
  15922. var Z_RLE = 3;
  15923. var Z_FIXED = 4;
  15924. var Z_DEFAULT_STRATEGY = 0;
  15925. /* Possible values of the data_type field (though see inflate()) */
  15926. //var Z_BINARY = 0;
  15927. //var Z_TEXT = 1;
  15928. //var Z_ASCII = 1; // = Z_TEXT
  15929. var Z_UNKNOWN = 2;
  15930. /* The deflate compression method */
  15931. var Z_DEFLATED = 8;
  15932. /*============================================================================*/
  15933. var MAX_MEM_LEVEL = 9;
  15934. /* Maximum value for memLevel in deflateInit2 */
  15935. var MAX_WBITS = 15;
  15936. /* 32K LZ77 window */
  15937. var DEF_MEM_LEVEL = 8;
  15938. var LENGTH_CODES = 29;
  15939. /* number of length codes, not counting the special END_BLOCK code */
  15940. var LITERALS = 256;
  15941. /* number of literal bytes 0..255 */
  15942. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15943. /* number of Literal or Length codes, including the END_BLOCK code */
  15944. var D_CODES = 30;
  15945. /* number of distance codes */
  15946. var BL_CODES = 19;
  15947. /* number of codes used to transfer the bit lengths */
  15948. var HEAP_SIZE = 2*L_CODES + 1;
  15949. /* maximum heap size */
  15950. var MAX_BITS = 15;
  15951. /* All codes must not exceed MAX_BITS bits */
  15952. var MIN_MATCH = 3;
  15953. var MAX_MATCH = 258;
  15954. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15955. var PRESET_DICT = 0x20;
  15956. var INIT_STATE = 42;
  15957. var EXTRA_STATE = 69;
  15958. var NAME_STATE = 73;
  15959. var COMMENT_STATE = 91;
  15960. var HCRC_STATE = 103;
  15961. var BUSY_STATE = 113;
  15962. var FINISH_STATE = 666;
  15963. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15964. var BS_BLOCK_DONE = 2; /* block flush performed */
  15965. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15966. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15967. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15968. function err(strm, errorCode) {
  15969. strm.msg = msg[errorCode];
  15970. return errorCode;
  15971. }
  15972. function rank(f) {
  15973. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15974. }
  15975. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15976. /* =========================================================================
  15977. * Flush as much pending output as possible. All deflate() output goes
  15978. * through this function so some applications may wish to modify it
  15979. * to avoid allocating a large strm->output buffer and copying into it.
  15980. * (See also read_buf()).
  15981. */
  15982. function flush_pending(strm) {
  15983. var s = strm.state;
  15984. //_tr_flush_bits(s);
  15985. var len = s.pending;
  15986. if (len > strm.avail_out) {
  15987. len = strm.avail_out;
  15988. }
  15989. if (len === 0) { return; }
  15990. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15991. strm.next_out += len;
  15992. s.pending_out += len;
  15993. strm.total_out += len;
  15994. strm.avail_out -= len;
  15995. s.pending -= len;
  15996. if (s.pending === 0) {
  15997. s.pending_out = 0;
  15998. }
  15999. }
  16000. function flush_block_only (s, last) {
  16001. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  16002. s.block_start = s.strstart;
  16003. flush_pending(s.strm);
  16004. }
  16005. function put_byte(s, b) {
  16006. s.pending_buf[s.pending++] = b;
  16007. }
  16008. /* =========================================================================
  16009. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  16010. * IN assertion: the stream state is correct and there is enough room in
  16011. * pending_buf.
  16012. */
  16013. function putShortMSB(s, b) {
  16014. // put_byte(s, (Byte)(b >> 8));
  16015. // put_byte(s, (Byte)(b & 0xff));
  16016. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  16017. s.pending_buf[s.pending++] = b & 0xff;
  16018. }
  16019. /* ===========================================================================
  16020. * Read a new buffer from the current input stream, update the adler32
  16021. * and total number of bytes read. All deflate() input goes through
  16022. * this function so some applications may wish to modify it to avoid
  16023. * allocating a large strm->input buffer and copying from it.
  16024. * (See also flush_pending()).
  16025. */
  16026. function read_buf(strm, buf, start, size) {
  16027. var len = strm.avail_in;
  16028. if (len > size) { len = size; }
  16029. if (len === 0) { return 0; }
  16030. strm.avail_in -= len;
  16031. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  16032. if (strm.state.wrap === 1) {
  16033. strm.adler = adler32(strm.adler, buf, len, start);
  16034. }
  16035. else if (strm.state.wrap === 2) {
  16036. strm.adler = crc32(strm.adler, buf, len, start);
  16037. }
  16038. strm.next_in += len;
  16039. strm.total_in += len;
  16040. return len;
  16041. }
  16042. /* ===========================================================================
  16043. * Set match_start to the longest match starting at the given string and
  16044. * return its length. Matches shorter or equal to prev_length are discarded,
  16045. * in which case the result is equal to prev_length and match_start is
  16046. * garbage.
  16047. * IN assertions: cur_match is the head of the hash chain for the current
  16048. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  16049. * OUT assertion: the match length is not greater than s->lookahead.
  16050. */
  16051. function longest_match(s, cur_match) {
  16052. var chain_length = s.max_chain_length; /* max hash chain length */
  16053. var scan = s.strstart; /* current string */
  16054. var match; /* matched string */
  16055. var len; /* length of current match */
  16056. var best_len = s.prev_length; /* best match length so far */
  16057. var nice_match = s.nice_match; /* stop if match long enough */
  16058. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  16059. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  16060. var _win = s.window; // shortcut
  16061. var wmask = s.w_mask;
  16062. var prev = s.prev;
  16063. /* Stop when cur_match becomes <= limit. To simplify the code,
  16064. * we prevent matches with the string of window index 0.
  16065. */
  16066. var strend = s.strstart + MAX_MATCH;
  16067. var scan_end1 = _win[scan + best_len - 1];
  16068. var scan_end = _win[scan + best_len];
  16069. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  16070. * It is easy to get rid of this optimization if necessary.
  16071. */
  16072. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  16073. /* Do not waste too much time if we already have a good match: */
  16074. if (s.prev_length >= s.good_match) {
  16075. chain_length >>= 2;
  16076. }
  16077. /* Do not look for matches beyond the end of the input. This is necessary
  16078. * to make deflate deterministic.
  16079. */
  16080. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  16081. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  16082. do {
  16083. // Assert(cur_match < s->strstart, "no future");
  16084. match = cur_match;
  16085. /* Skip to next match if the match length cannot increase
  16086. * or if the match length is less than 2. Note that the checks below
  16087. * for insufficient lookahead only occur occasionally for performance
  16088. * reasons. Therefore uninitialized memory will be accessed, and
  16089. * conditional jumps will be made that depend on those values.
  16090. * However the length of the match is limited to the lookahead, so
  16091. * the output of deflate is not affected by the uninitialized values.
  16092. */
  16093. if (_win[match + best_len] !== scan_end ||
  16094. _win[match + best_len - 1] !== scan_end1 ||
  16095. _win[match] !== _win[scan] ||
  16096. _win[++match] !== _win[scan + 1]) {
  16097. continue;
  16098. }
  16099. /* The check at best_len-1 can be removed because it will be made
  16100. * again later. (This heuristic is not always a win.)
  16101. * It is not necessary to compare scan[2] and match[2] since they
  16102. * are always equal when the other bytes match, given that
  16103. * the hash keys are equal and that HASH_BITS >= 8.
  16104. */
  16105. scan += 2;
  16106. match++;
  16107. // Assert(*scan == *match, "match[2]?");
  16108. /* We check for insufficient lookahead only every 8th comparison;
  16109. * the 256th check will be made at strstart+258.
  16110. */
  16111. do {
  16112. /*jshint noempty:false*/
  16113. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16114. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16115. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16116. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16117. scan < strend);
  16118. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  16119. len = MAX_MATCH - (strend - scan);
  16120. scan = strend - MAX_MATCH;
  16121. if (len > best_len) {
  16122. s.match_start = cur_match;
  16123. best_len = len;
  16124. if (len >= nice_match) {
  16125. break;
  16126. }
  16127. scan_end1 = _win[scan + best_len - 1];
  16128. scan_end = _win[scan + best_len];
  16129. }
  16130. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  16131. if (best_len <= s.lookahead) {
  16132. return best_len;
  16133. }
  16134. return s.lookahead;
  16135. }
  16136. /* ===========================================================================
  16137. * Fill the window when the lookahead becomes insufficient.
  16138. * Updates strstart and lookahead.
  16139. *
  16140. * IN assertion: lookahead < MIN_LOOKAHEAD
  16141. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  16142. * At least one byte has been read, or avail_in == 0; reads are
  16143. * performed for at least two bytes (required for the zip translate_eol
  16144. * option -- not supported here).
  16145. */
  16146. function fill_window(s) {
  16147. var _w_size = s.w_size;
  16148. var p, n, m, more, str;
  16149. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  16150. do {
  16151. more = s.window_size - s.lookahead - s.strstart;
  16152. // JS ints have 32 bit, block below not needed
  16153. /* Deal with !@#$% 64K limit: */
  16154. //if (sizeof(int) <= 2) {
  16155. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  16156. // more = wsize;
  16157. //
  16158. // } else if (more == (unsigned)(-1)) {
  16159. // /* Very unlikely, but possible on 16 bit machine if
  16160. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  16161. // */
  16162. // more--;
  16163. // }
  16164. //}
  16165. /* If the window is almost full and there is insufficient lookahead,
  16166. * move the upper half to the lower one to make room in the upper half.
  16167. */
  16168. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  16169. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  16170. s.match_start -= _w_size;
  16171. s.strstart -= _w_size;
  16172. /* we now have strstart >= MAX_DIST */
  16173. s.block_start -= _w_size;
  16174. /* Slide the hash table (could be avoided with 32 bit values
  16175. at the expense of memory usage). We slide even when level == 0
  16176. to keep the hash table consistent if we switch back to level > 0
  16177. later. (Using level 0 permanently is not an optimal usage of
  16178. zlib, so we don't care about this pathological case.)
  16179. */
  16180. n = s.hash_size;
  16181. p = n;
  16182. do {
  16183. m = s.head[--p];
  16184. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  16185. } while (--n);
  16186. n = _w_size;
  16187. p = n;
  16188. do {
  16189. m = s.prev[--p];
  16190. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  16191. /* If n is not on any hash chain, prev[n] is garbage but
  16192. * its value will never be used.
  16193. */
  16194. } while (--n);
  16195. more += _w_size;
  16196. }
  16197. if (s.strm.avail_in === 0) {
  16198. break;
  16199. }
  16200. /* If there was no sliding:
  16201. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  16202. * more == window_size - lookahead - strstart
  16203. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  16204. * => more >= window_size - 2*WSIZE + 2
  16205. * In the BIG_MEM or MMAP case (not yet supported),
  16206. * window_size == input_size + MIN_LOOKAHEAD &&
  16207. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  16208. * Otherwise, window_size == 2*WSIZE so more >= 2.
  16209. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  16210. */
  16211. //Assert(more >= 2, "more < 2");
  16212. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  16213. s.lookahead += n;
  16214. /* Initialize the hash value now that we have some input: */
  16215. if (s.lookahead + s.insert >= MIN_MATCH) {
  16216. str = s.strstart - s.insert;
  16217. s.ins_h = s.window[str];
  16218. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  16219. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  16220. //#if MIN_MATCH != 3
  16221. // Call update_hash() MIN_MATCH-3 more times
  16222. //#endif
  16223. while (s.insert) {
  16224. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  16225. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  16226. s.prev[str & s.w_mask] = s.head[s.ins_h];
  16227. s.head[s.ins_h] = str;
  16228. str++;
  16229. s.insert--;
  16230. if (s.lookahead + s.insert < MIN_MATCH) {
  16231. break;
  16232. }
  16233. }
  16234. }
  16235. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  16236. * but this is not important since only literal bytes will be emitted.
  16237. */
  16238. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  16239. /* If the WIN_INIT bytes after the end of the current data have never been
  16240. * written, then zero those bytes in order to avoid memory check reports of
  16241. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  16242. * the longest match routines. Update the high water mark for the next
  16243. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  16244. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  16245. */
  16246. // if (s.high_water < s.window_size) {
  16247. // var curr = s.strstart + s.lookahead;
  16248. // var init = 0;
  16249. //
  16250. // if (s.high_water < curr) {
  16251. // /* Previous high water mark below current data -- zero WIN_INIT
  16252. // * bytes or up to end of window, whichever is less.
  16253. // */
  16254. // init = s.window_size - curr;
  16255. // if (init > WIN_INIT)
  16256. // init = WIN_INIT;
  16257. // zmemzero(s->window + curr, (unsigned)init);
  16258. // s->high_water = curr + init;
  16259. // }
  16260. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  16261. // /* High water mark at or above current data, but below current data
  16262. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  16263. // * to end of window, whichever is less.
  16264. // */
  16265. // init = (ulg)curr + WIN_INIT - s->high_water;
  16266. // if (init > s->window_size - s->high_water)
  16267. // init = s->window_size - s->high_water;
  16268. // zmemzero(s->window + s->high_water, (unsigned)init);
  16269. // s->high_water += init;
  16270. // }
  16271. // }
  16272. //
  16273. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  16274. // "not enough room for search");
  16275. }
  16276. /* ===========================================================================
  16277. * Copy without compression as much as possible from the input stream, return
  16278. * the current block state.
  16279. * This function does not insert new strings in the dictionary since
  16280. * uncompressible data is probably not useful. This function is used
  16281. * only for the level=0 compression option.
  16282. * NOTE: this function should be optimized to avoid extra copying from
  16283. * window to pending_buf.
  16284. */
  16285. function deflate_stored(s, flush) {
  16286. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  16287. * to pending_buf_size, and each stored block has a 5 byte header:
  16288. */
  16289. var max_block_size = 0xffff;
  16290. if (max_block_size > s.pending_buf_size - 5) {
  16291. max_block_size = s.pending_buf_size - 5;
  16292. }
  16293. /* Copy as much as possible from input to output: */
  16294. for (;;) {
  16295. /* Fill the window as much as possible: */
  16296. if (s.lookahead <= 1) {
  16297. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  16298. // s->block_start >= (long)s->w_size, "slide too late");
  16299. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  16300. // s.block_start >= s.w_size)) {
  16301. // throw new Error("slide too late");
  16302. // }
  16303. fill_window(s);
  16304. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  16305. return BS_NEED_MORE;
  16306. }
  16307. if (s.lookahead === 0) {
  16308. break;
  16309. }
  16310. /* flush the current block */
  16311. }
  16312. //Assert(s->block_start >= 0L, "block gone");
  16313. // if (s.block_start < 0) throw new Error("block gone");
  16314. s.strstart += s.lookahead;
  16315. s.lookahead = 0;
  16316. /* Emit a stored block if pending_buf will be full: */
  16317. var max_start = s.block_start + max_block_size;
  16318. if (s.strstart === 0 || s.strstart >= max_start) {
  16319. /* strstart == 0 is possible when wraparound on 16-bit machine */
  16320. s.lookahead = s.strstart - max_start;
  16321. s.strstart = max_start;
  16322. /*** FLUSH_BLOCK(s, 0); ***/
  16323. flush_block_only(s, false);
  16324. if (s.strm.avail_out === 0) {
  16325. return BS_NEED_MORE;
  16326. }
  16327. /***/
  16328. }
  16329. /* Flush if we may have to slide, otherwise block_start may become
  16330. * negative and the data will be gone:
  16331. */
  16332. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16333. /*** FLUSH_BLOCK(s, 0); ***/
  16334. flush_block_only(s, false);
  16335. if (s.strm.avail_out === 0) {
  16336. return BS_NEED_MORE;
  16337. }
  16338. /***/
  16339. }
  16340. }
  16341. s.insert = 0;
  16342. if (flush === Z_FINISH) {
  16343. /*** FLUSH_BLOCK(s, 1); ***/
  16344. flush_block_only(s, true);
  16345. if (s.strm.avail_out === 0) {
  16346. return BS_FINISH_STARTED;
  16347. }
  16348. /***/
  16349. return BS_FINISH_DONE;
  16350. }
  16351. if (s.strstart > s.block_start) {
  16352. /*** FLUSH_BLOCK(s, 0); ***/
  16353. flush_block_only(s, false);
  16354. if (s.strm.avail_out === 0) {
  16355. return BS_NEED_MORE;
  16356. }
  16357. /***/
  16358. }
  16359. return BS_NEED_MORE;
  16360. }
  16361. /* ===========================================================================
  16362. * Compress as much as possible from the input stream, return the current
  16363. * block state.
  16364. * This function does not perform lazy evaluation of matches and inserts
  16365. * new strings in the dictionary only for unmatched strings or for short
  16366. * matches. It is used only for the fast compression options.
  16367. */
  16368. function deflate_fast(s, flush) {
  16369. var hash_head; /* head of the hash chain */
  16370. var bflush; /* set if current block must be flushed */
  16371. for (;;) {
  16372. /* Make sure that we always have enough lookahead, except
  16373. * at the end of the input file. We need MAX_MATCH bytes
  16374. * for the next match, plus MIN_MATCH bytes to insert the
  16375. * string following the next match.
  16376. */
  16377. if (s.lookahead < MIN_LOOKAHEAD) {
  16378. fill_window(s);
  16379. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16380. return BS_NEED_MORE;
  16381. }
  16382. if (s.lookahead === 0) {
  16383. break; /* flush the current block */
  16384. }
  16385. }
  16386. /* Insert the string window[strstart .. strstart+2] in the
  16387. * dictionary, and set hash_head to the head of the hash chain:
  16388. */
  16389. hash_head = 0/*NIL*/;
  16390. if (s.lookahead >= MIN_MATCH) {
  16391. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16392. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16393. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16394. s.head[s.ins_h] = s.strstart;
  16395. /***/
  16396. }
  16397. /* Find the longest match, discarding those <= prev_length.
  16398. * At this point we have always match_length < MIN_MATCH
  16399. */
  16400. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16401. /* To simplify the code, we prevent matches with the string
  16402. * of window index 0 (in particular we have to avoid a match
  16403. * of the string with itself at the start of the input file).
  16404. */
  16405. s.match_length = longest_match(s, hash_head);
  16406. /* longest_match() sets match_start */
  16407. }
  16408. if (s.match_length >= MIN_MATCH) {
  16409. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16410. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16411. s.match_length - MIN_MATCH, bflush); ***/
  16412. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16413. s.lookahead -= s.match_length;
  16414. /* Insert new strings in the hash table only if the match length
  16415. * is not too large. This saves time but degrades compression.
  16416. */
  16417. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16418. s.match_length--; /* string at strstart already in table */
  16419. do {
  16420. s.strstart++;
  16421. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16422. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16423. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16424. s.head[s.ins_h] = s.strstart;
  16425. /***/
  16426. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16427. * always MIN_MATCH bytes ahead.
  16428. */
  16429. } while (--s.match_length !== 0);
  16430. s.strstart++;
  16431. } else
  16432. {
  16433. s.strstart += s.match_length;
  16434. s.match_length = 0;
  16435. s.ins_h = s.window[s.strstart];
  16436. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16437. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16438. //#if MIN_MATCH != 3
  16439. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16440. //#endif
  16441. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16442. * matter since it will be recomputed at next deflate call.
  16443. */
  16444. }
  16445. } else {
  16446. /* No match, output a literal byte */
  16447. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16448. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16449. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16450. s.lookahead--;
  16451. s.strstart++;
  16452. }
  16453. if (bflush) {
  16454. /*** FLUSH_BLOCK(s, 0); ***/
  16455. flush_block_only(s, false);
  16456. if (s.strm.avail_out === 0) {
  16457. return BS_NEED_MORE;
  16458. }
  16459. /***/
  16460. }
  16461. }
  16462. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  16463. if (flush === Z_FINISH) {
  16464. /*** FLUSH_BLOCK(s, 1); ***/
  16465. flush_block_only(s, true);
  16466. if (s.strm.avail_out === 0) {
  16467. return BS_FINISH_STARTED;
  16468. }
  16469. /***/
  16470. return BS_FINISH_DONE;
  16471. }
  16472. if (s.last_lit) {
  16473. /*** FLUSH_BLOCK(s, 0); ***/
  16474. flush_block_only(s, false);
  16475. if (s.strm.avail_out === 0) {
  16476. return BS_NEED_MORE;
  16477. }
  16478. /***/
  16479. }
  16480. return BS_BLOCK_DONE;
  16481. }
  16482. /* ===========================================================================
  16483. * Same as above, but achieves better compression. We use a lazy
  16484. * evaluation for matches: a match is finally adopted only if there is
  16485. * no better match at the next window position.
  16486. */
  16487. function deflate_slow(s, flush) {
  16488. var hash_head; /* head of hash chain */
  16489. var bflush; /* set if current block must be flushed */
  16490. var max_insert;
  16491. /* Process the input block. */
  16492. for (;;) {
  16493. /* Make sure that we always have enough lookahead, except
  16494. * at the end of the input file. We need MAX_MATCH bytes
  16495. * for the next match, plus MIN_MATCH bytes to insert the
  16496. * string following the next match.
  16497. */
  16498. if (s.lookahead < MIN_LOOKAHEAD) {
  16499. fill_window(s);
  16500. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16501. return BS_NEED_MORE;
  16502. }
  16503. if (s.lookahead === 0) { break; } /* flush the current block */
  16504. }
  16505. /* Insert the string window[strstart .. strstart+2] in the
  16506. * dictionary, and set hash_head to the head of the hash chain:
  16507. */
  16508. hash_head = 0/*NIL*/;
  16509. if (s.lookahead >= MIN_MATCH) {
  16510. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16511. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16512. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16513. s.head[s.ins_h] = s.strstart;
  16514. /***/
  16515. }
  16516. /* Find the longest match, discarding those <= prev_length.
  16517. */
  16518. s.prev_length = s.match_length;
  16519. s.prev_match = s.match_start;
  16520. s.match_length = MIN_MATCH-1;
  16521. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16522. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16523. /* To simplify the code, we prevent matches with the string
  16524. * of window index 0 (in particular we have to avoid a match
  16525. * of the string with itself at the start of the input file).
  16526. */
  16527. s.match_length = longest_match(s, hash_head);
  16528. /* longest_match() sets match_start */
  16529. if (s.match_length <= 5 &&
  16530. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16531. /* If prev_match is also MIN_MATCH, match_start is garbage
  16532. * but we will ignore the current match anyway.
  16533. */
  16534. s.match_length = MIN_MATCH-1;
  16535. }
  16536. }
  16537. /* If there was a match at the previous step and the current
  16538. * match is not better, output the previous match:
  16539. */
  16540. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16541. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16542. /* Do not insert strings in hash table beyond this. */
  16543. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16544. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16545. s.prev_length - MIN_MATCH, bflush);***/
  16546. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16547. /* Insert in hash table all strings up to the end of the match.
  16548. * strstart-1 and strstart are already inserted. If there is not
  16549. * enough lookahead, the last two strings are not inserted in
  16550. * the hash table.
  16551. */
  16552. s.lookahead -= s.prev_length-1;
  16553. s.prev_length -= 2;
  16554. do {
  16555. if (++s.strstart <= max_insert) {
  16556. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16557. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16558. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16559. s.head[s.ins_h] = s.strstart;
  16560. /***/
  16561. }
  16562. } while (--s.prev_length !== 0);
  16563. s.match_available = 0;
  16564. s.match_length = MIN_MATCH-1;
  16565. s.strstart++;
  16566. if (bflush) {
  16567. /*** FLUSH_BLOCK(s, 0); ***/
  16568. flush_block_only(s, false);
  16569. if (s.strm.avail_out === 0) {
  16570. return BS_NEED_MORE;
  16571. }
  16572. /***/
  16573. }
  16574. } else if (s.match_available) {
  16575. /* If there was no match at the previous position, output a
  16576. * single literal. If there was a match but the current match
  16577. * is longer, truncate the previous match to a single literal.
  16578. */
  16579. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16580. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16581. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16582. if (bflush) {
  16583. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16584. flush_block_only(s, false);
  16585. /***/
  16586. }
  16587. s.strstart++;
  16588. s.lookahead--;
  16589. if (s.strm.avail_out === 0) {
  16590. return BS_NEED_MORE;
  16591. }
  16592. } else {
  16593. /* There is no previous match to compare with, wait for
  16594. * the next step to decide.
  16595. */
  16596. s.match_available = 1;
  16597. s.strstart++;
  16598. s.lookahead--;
  16599. }
  16600. }
  16601. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16602. if (s.match_available) {
  16603. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16604. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16605. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16606. s.match_available = 0;
  16607. }
  16608. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16609. if (flush === Z_FINISH) {
  16610. /*** FLUSH_BLOCK(s, 1); ***/
  16611. flush_block_only(s, true);
  16612. if (s.strm.avail_out === 0) {
  16613. return BS_FINISH_STARTED;
  16614. }
  16615. /***/
  16616. return BS_FINISH_DONE;
  16617. }
  16618. if (s.last_lit) {
  16619. /*** FLUSH_BLOCK(s, 0); ***/
  16620. flush_block_only(s, false);
  16621. if (s.strm.avail_out === 0) {
  16622. return BS_NEED_MORE;
  16623. }
  16624. /***/
  16625. }
  16626. return BS_BLOCK_DONE;
  16627. }
  16628. /* ===========================================================================
  16629. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16630. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16631. * deflate switches away from Z_RLE.)
  16632. */
  16633. function deflate_rle(s, flush) {
  16634. var bflush; /* set if current block must be flushed */
  16635. var prev; /* byte at distance one to match */
  16636. var scan, strend; /* scan goes up to strend for length of run */
  16637. var _win = s.window;
  16638. for (;;) {
  16639. /* Make sure that we always have enough lookahead, except
  16640. * at the end of the input file. We need MAX_MATCH bytes
  16641. * for the longest run, plus one for the unrolled loop.
  16642. */
  16643. if (s.lookahead <= MAX_MATCH) {
  16644. fill_window(s);
  16645. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16646. return BS_NEED_MORE;
  16647. }
  16648. if (s.lookahead === 0) { break; } /* flush the current block */
  16649. }
  16650. /* See how many times the previous byte repeats */
  16651. s.match_length = 0;
  16652. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16653. scan = s.strstart - 1;
  16654. prev = _win[scan];
  16655. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16656. strend = s.strstart + MAX_MATCH;
  16657. do {
  16658. /*jshint noempty:false*/
  16659. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16660. prev === _win[++scan] && prev === _win[++scan] &&
  16661. prev === _win[++scan] && prev === _win[++scan] &&
  16662. prev === _win[++scan] && prev === _win[++scan] &&
  16663. scan < strend);
  16664. s.match_length = MAX_MATCH - (strend - scan);
  16665. if (s.match_length > s.lookahead) {
  16666. s.match_length = s.lookahead;
  16667. }
  16668. }
  16669. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16670. }
  16671. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16672. if (s.match_length >= MIN_MATCH) {
  16673. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16674. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16675. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16676. s.lookahead -= s.match_length;
  16677. s.strstart += s.match_length;
  16678. s.match_length = 0;
  16679. } else {
  16680. /* No match, output a literal byte */
  16681. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16682. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16683. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16684. s.lookahead--;
  16685. s.strstart++;
  16686. }
  16687. if (bflush) {
  16688. /*** FLUSH_BLOCK(s, 0); ***/
  16689. flush_block_only(s, false);
  16690. if (s.strm.avail_out === 0) {
  16691. return BS_NEED_MORE;
  16692. }
  16693. /***/
  16694. }
  16695. }
  16696. s.insert = 0;
  16697. if (flush === Z_FINISH) {
  16698. /*** FLUSH_BLOCK(s, 1); ***/
  16699. flush_block_only(s, true);
  16700. if (s.strm.avail_out === 0) {
  16701. return BS_FINISH_STARTED;
  16702. }
  16703. /***/
  16704. return BS_FINISH_DONE;
  16705. }
  16706. if (s.last_lit) {
  16707. /*** FLUSH_BLOCK(s, 0); ***/
  16708. flush_block_only(s, false);
  16709. if (s.strm.avail_out === 0) {
  16710. return BS_NEED_MORE;
  16711. }
  16712. /***/
  16713. }
  16714. return BS_BLOCK_DONE;
  16715. }
  16716. /* ===========================================================================
  16717. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16718. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16719. */
  16720. function deflate_huff(s, flush) {
  16721. var bflush; /* set if current block must be flushed */
  16722. for (;;) {
  16723. /* Make sure that we have a literal to write. */
  16724. if (s.lookahead === 0) {
  16725. fill_window(s);
  16726. if (s.lookahead === 0) {
  16727. if (flush === Z_NO_FLUSH) {
  16728. return BS_NEED_MORE;
  16729. }
  16730. break; /* flush the current block */
  16731. }
  16732. }
  16733. /* Output a literal byte */
  16734. s.match_length = 0;
  16735. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16736. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16737. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16738. s.lookahead--;
  16739. s.strstart++;
  16740. if (bflush) {
  16741. /*** FLUSH_BLOCK(s, 0); ***/
  16742. flush_block_only(s, false);
  16743. if (s.strm.avail_out === 0) {
  16744. return BS_NEED_MORE;
  16745. }
  16746. /***/
  16747. }
  16748. }
  16749. s.insert = 0;
  16750. if (flush === Z_FINISH) {
  16751. /*** FLUSH_BLOCK(s, 1); ***/
  16752. flush_block_only(s, true);
  16753. if (s.strm.avail_out === 0) {
  16754. return BS_FINISH_STARTED;
  16755. }
  16756. /***/
  16757. return BS_FINISH_DONE;
  16758. }
  16759. if (s.last_lit) {
  16760. /*** FLUSH_BLOCK(s, 0); ***/
  16761. flush_block_only(s, false);
  16762. if (s.strm.avail_out === 0) {
  16763. return BS_NEED_MORE;
  16764. }
  16765. /***/
  16766. }
  16767. return BS_BLOCK_DONE;
  16768. }
  16769. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16770. * the desired pack level (0..9). The values given below have been tuned to
  16771. * exclude worst case performance for pathological files. Better values may be
  16772. * found for specific files.
  16773. */
  16774. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16775. this.good_length = good_length;
  16776. this.max_lazy = max_lazy;
  16777. this.nice_length = nice_length;
  16778. this.max_chain = max_chain;
  16779. this.func = func;
  16780. };
  16781. var configuration_table;
  16782. configuration_table = [
  16783. /* good lazy nice chain */
  16784. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16785. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16786. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16787. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16788. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16789. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16790. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16791. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16792. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16793. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16794. ];
  16795. /* ===========================================================================
  16796. * Initialize the "longest match" routines for a new zlib stream
  16797. */
  16798. function lm_init(s) {
  16799. s.window_size = 2 * s.w_size;
  16800. /*** CLEAR_HASH(s); ***/
  16801. zero(s.head); // Fill with NIL (= 0);
  16802. /* Set the default configuration parameters:
  16803. */
  16804. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16805. s.good_match = configuration_table[s.level].good_length;
  16806. s.nice_match = configuration_table[s.level].nice_length;
  16807. s.max_chain_length = configuration_table[s.level].max_chain;
  16808. s.strstart = 0;
  16809. s.block_start = 0;
  16810. s.lookahead = 0;
  16811. s.insert = 0;
  16812. s.match_length = s.prev_length = MIN_MATCH - 1;
  16813. s.match_available = 0;
  16814. s.ins_h = 0;
  16815. }
  16816. function DeflateState() {
  16817. this.strm = null; /* pointer back to this zlib stream */
  16818. this.status = 0; /* as the name implies */
  16819. this.pending_buf = null; /* output still pending */
  16820. this.pending_buf_size = 0; /* size of pending_buf */
  16821. this.pending_out = 0; /* next pending byte to output to the stream */
  16822. this.pending = 0; /* nb of bytes in the pending buffer */
  16823. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16824. this.gzhead = null; /* gzip header information to write */
  16825. this.gzindex = 0; /* where in extra, name, or comment */
  16826. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16827. this.last_flush = -1; /* value of flush param for previous deflate call */
  16828. this.w_size = 0; /* LZ77 window size (32K by default) */
  16829. this.w_bits = 0; /* log2(w_size) (8..16) */
  16830. this.w_mask = 0; /* w_size - 1 */
  16831. this.window = null;
  16832. /* Sliding window. Input bytes are read into the second half of the window,
  16833. * and move to the first half later to keep a dictionary of at least wSize
  16834. * bytes. With this organization, matches are limited to a distance of
  16835. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16836. * performed with a length multiple of the block size.
  16837. */
  16838. this.window_size = 0;
  16839. /* Actual size of window: 2*wSize, except when the user input buffer
  16840. * is directly used as sliding window.
  16841. */
  16842. this.prev = null;
  16843. /* Link to older string with same hash index. To limit the size of this
  16844. * array to 64K, this link is maintained only for the last 32K strings.
  16845. * An index in this array is thus a window index modulo 32K.
  16846. */
  16847. this.head = null; /* Heads of the hash chains or NIL. */
  16848. this.ins_h = 0; /* hash index of string to be inserted */
  16849. this.hash_size = 0; /* number of elements in hash table */
  16850. this.hash_bits = 0; /* log2(hash_size) */
  16851. this.hash_mask = 0; /* hash_size-1 */
  16852. this.hash_shift = 0;
  16853. /* Number of bits by which ins_h must be shifted at each input
  16854. * step. It must be such that after MIN_MATCH steps, the oldest
  16855. * byte no longer takes part in the hash key, that is:
  16856. * hash_shift * MIN_MATCH >= hash_bits
  16857. */
  16858. this.block_start = 0;
  16859. /* Window position at the beginning of the current output block. Gets
  16860. * negative when the window is moved backwards.
  16861. */
  16862. this.match_length = 0; /* length of best match */
  16863. this.prev_match = 0; /* previous match */
  16864. this.match_available = 0; /* set if previous match exists */
  16865. this.strstart = 0; /* start of string to insert */
  16866. this.match_start = 0; /* start of matching string */
  16867. this.lookahead = 0; /* number of valid bytes ahead in window */
  16868. this.prev_length = 0;
  16869. /* Length of the best match at previous step. Matches not greater than this
  16870. * are discarded. This is used in the lazy match evaluation.
  16871. */
  16872. this.max_chain_length = 0;
  16873. /* To speed up deflation, hash chains are never searched beyond this
  16874. * length. A higher limit improves compression ratio but degrades the
  16875. * speed.
  16876. */
  16877. this.max_lazy_match = 0;
  16878. /* Attempt to find a better match only when the current match is strictly
  16879. * smaller than this value. This mechanism is used only for compression
  16880. * levels >= 4.
  16881. */
  16882. // That's alias to max_lazy_match, don't use directly
  16883. //this.max_insert_length = 0;
  16884. /* Insert new strings in the hash table only if the match length is not
  16885. * greater than this length. This saves time but degrades compression.
  16886. * max_insert_length is used only for compression levels <= 3.
  16887. */
  16888. this.level = 0; /* compression level (1..9) */
  16889. this.strategy = 0; /* favor or force Huffman coding*/
  16890. this.good_match = 0;
  16891. /* Use a faster search when the previous match is longer than this */
  16892. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16893. /* used by trees.c: */
  16894. /* Didn't use ct_data typedef below to suppress compiler warning */
  16895. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16896. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16897. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16898. // Use flat array of DOUBLE size, with interleaved fata,
  16899. // because JS does not support effective
  16900. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16901. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16902. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16903. zero(this.dyn_ltree);
  16904. zero(this.dyn_dtree);
  16905. zero(this.bl_tree);
  16906. this.l_desc = null; /* desc. for literal tree */
  16907. this.d_desc = null; /* desc. for distance tree */
  16908. this.bl_desc = null; /* desc. for bit length tree */
  16909. //ush bl_count[MAX_BITS+1];
  16910. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16911. /* number of codes at each bit length for an optimal tree */
  16912. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16913. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16914. zero(this.heap);
  16915. this.heap_len = 0; /* number of elements in the heap */
  16916. this.heap_max = 0; /* element of largest frequency */
  16917. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16918. * The same heap array is used to build all trees.
  16919. */
  16920. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16921. zero(this.depth);
  16922. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16923. */
  16924. this.l_buf = 0; /* buffer index for literals or lengths */
  16925. this.lit_bufsize = 0;
  16926. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16927. * limiting lit_bufsize to 64K:
  16928. * - frequencies can be kept in 16 bit counters
  16929. * - if compression is not successful for the first block, all input
  16930. * data is still in the window so we can still emit a stored block even
  16931. * when input comes from standard input. (This can also be done for
  16932. * all blocks if lit_bufsize is not greater than 32K.)
  16933. * - if compression is not successful for a file smaller than 64K, we can
  16934. * even emit a stored file instead of a stored block (saving 5 bytes).
  16935. * This is applicable only for zip (not gzip or zlib).
  16936. * - creating new Huffman trees less frequently may not provide fast
  16937. * adaptation to changes in the input data statistics. (Take for
  16938. * example a binary file with poorly compressible code followed by
  16939. * a highly compressible string table.) Smaller buffer sizes give
  16940. * fast adaptation but have of course the overhead of transmitting
  16941. * trees more frequently.
  16942. * - I can't count above 4
  16943. */
  16944. this.last_lit = 0; /* running index in l_buf */
  16945. this.d_buf = 0;
  16946. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16947. * the same number of elements. To use different lengths, an extra flag
  16948. * array would be necessary.
  16949. */
  16950. this.opt_len = 0; /* bit length of current block with optimal trees */
  16951. this.static_len = 0; /* bit length of current block with static trees */
  16952. this.matches = 0; /* number of string matches in current block */
  16953. this.insert = 0; /* bytes at end of window left to insert */
  16954. this.bi_buf = 0;
  16955. /* Output buffer. bits are inserted starting at the bottom (least
  16956. * significant bits).
  16957. */
  16958. this.bi_valid = 0;
  16959. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16960. * are always zero.
  16961. */
  16962. // Used for window memory init. We safely ignore it for JS. That makes
  16963. // sense only for pointers and memory check tools.
  16964. //this.high_water = 0;
  16965. /* High water mark offset in window for initialized bytes -- bytes above
  16966. * this are set to zero in order to avoid memory check warnings when
  16967. * longest match routines access bytes past the input. This is then
  16968. * updated to the new high water mark.
  16969. */
  16970. }
  16971. function deflateResetKeep(strm) {
  16972. var s;
  16973. if (!strm || !strm.state) {
  16974. return err(strm, Z_STREAM_ERROR);
  16975. }
  16976. strm.total_in = strm.total_out = 0;
  16977. strm.data_type = Z_UNKNOWN;
  16978. s = strm.state;
  16979. s.pending = 0;
  16980. s.pending_out = 0;
  16981. if (s.wrap < 0) {
  16982. s.wrap = -s.wrap;
  16983. /* was made negative by deflate(..., Z_FINISH); */
  16984. }
  16985. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16986. strm.adler = (s.wrap === 2) ?
  16987. 0 // crc32(0, Z_NULL, 0)
  16988. :
  16989. 1; // adler32(0, Z_NULL, 0)
  16990. s.last_flush = Z_NO_FLUSH;
  16991. trees._tr_init(s);
  16992. return Z_OK;
  16993. }
  16994. function deflateReset(strm) {
  16995. var ret = deflateResetKeep(strm);
  16996. if (ret === Z_OK) {
  16997. lm_init(strm.state);
  16998. }
  16999. return ret;
  17000. }
  17001. function deflateSetHeader(strm, head) {
  17002. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17003. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  17004. strm.state.gzhead = head;
  17005. return Z_OK;
  17006. }
  17007. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  17008. if (!strm) { // === Z_NULL
  17009. return Z_STREAM_ERROR;
  17010. }
  17011. var wrap = 1;
  17012. if (level === Z_DEFAULT_COMPRESSION) {
  17013. level = 6;
  17014. }
  17015. if (windowBits < 0) { /* suppress zlib wrapper */
  17016. wrap = 0;
  17017. windowBits = -windowBits;
  17018. }
  17019. else if (windowBits > 15) {
  17020. wrap = 2; /* write gzip wrapper instead */
  17021. windowBits -= 16;
  17022. }
  17023. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  17024. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  17025. strategy < 0 || strategy > Z_FIXED) {
  17026. return err(strm, Z_STREAM_ERROR);
  17027. }
  17028. if (windowBits === 8) {
  17029. windowBits = 9;
  17030. }
  17031. /* until 256-byte window bug fixed */
  17032. var s = new DeflateState();
  17033. strm.state = s;
  17034. s.strm = strm;
  17035. s.wrap = wrap;
  17036. s.gzhead = null;
  17037. s.w_bits = windowBits;
  17038. s.w_size = 1 << s.w_bits;
  17039. s.w_mask = s.w_size - 1;
  17040. s.hash_bits = memLevel + 7;
  17041. s.hash_size = 1 << s.hash_bits;
  17042. s.hash_mask = s.hash_size - 1;
  17043. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  17044. s.window = new utils.Buf8(s.w_size * 2);
  17045. s.head = new utils.Buf16(s.hash_size);
  17046. s.prev = new utils.Buf16(s.w_size);
  17047. // Don't need mem init magic for JS.
  17048. //s.high_water = 0; /* nothing written to s->window yet */
  17049. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  17050. s.pending_buf_size = s.lit_bufsize * 4;
  17051. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  17052. s.d_buf = s.lit_bufsize >> 1;
  17053. s.l_buf = (1 + 2) * s.lit_bufsize;
  17054. s.level = level;
  17055. s.strategy = strategy;
  17056. s.method = method;
  17057. return deflateReset(strm);
  17058. }
  17059. function deflateInit(strm, level) {
  17060. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  17061. }
  17062. function deflate(strm, flush) {
  17063. var old_flush, s;
  17064. var beg, val; // for gzip header write only
  17065. if (!strm || !strm.state ||
  17066. flush > Z_BLOCK || flush < 0) {
  17067. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  17068. }
  17069. s = strm.state;
  17070. if (!strm.output ||
  17071. (!strm.input && strm.avail_in !== 0) ||
  17072. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  17073. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  17074. }
  17075. s.strm = strm; /* just in case */
  17076. old_flush = s.last_flush;
  17077. s.last_flush = flush;
  17078. /* Write the header */
  17079. if (s.status === INIT_STATE) {
  17080. if (s.wrap === 2) { // GZIP header
  17081. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17082. put_byte(s, 31);
  17083. put_byte(s, 139);
  17084. put_byte(s, 8);
  17085. if (!s.gzhead) { // s->gzhead == Z_NULL
  17086. put_byte(s, 0);
  17087. put_byte(s, 0);
  17088. put_byte(s, 0);
  17089. put_byte(s, 0);
  17090. put_byte(s, 0);
  17091. put_byte(s, s.level === 9 ? 2 :
  17092. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17093. 4 : 0));
  17094. put_byte(s, OS_CODE);
  17095. s.status = BUSY_STATE;
  17096. }
  17097. else {
  17098. put_byte(s, (s.gzhead.text ? 1 : 0) +
  17099. (s.gzhead.hcrc ? 2 : 0) +
  17100. (!s.gzhead.extra ? 0 : 4) +
  17101. (!s.gzhead.name ? 0 : 8) +
  17102. (!s.gzhead.comment ? 0 : 16)
  17103. );
  17104. put_byte(s, s.gzhead.time & 0xff);
  17105. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  17106. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  17107. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  17108. put_byte(s, s.level === 9 ? 2 :
  17109. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17110. 4 : 0));
  17111. put_byte(s, s.gzhead.os & 0xff);
  17112. if (s.gzhead.extra && s.gzhead.extra.length) {
  17113. put_byte(s, s.gzhead.extra.length & 0xff);
  17114. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  17115. }
  17116. if (s.gzhead.hcrc) {
  17117. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  17118. }
  17119. s.gzindex = 0;
  17120. s.status = EXTRA_STATE;
  17121. }
  17122. }
  17123. else // DEFLATE header
  17124. {
  17125. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  17126. var level_flags = -1;
  17127. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  17128. level_flags = 0;
  17129. } else if (s.level < 6) {
  17130. level_flags = 1;
  17131. } else if (s.level === 6) {
  17132. level_flags = 2;
  17133. } else {
  17134. level_flags = 3;
  17135. }
  17136. header |= (level_flags << 6);
  17137. if (s.strstart !== 0) { header |= PRESET_DICT; }
  17138. header += 31 - (header % 31);
  17139. s.status = BUSY_STATE;
  17140. putShortMSB(s, header);
  17141. /* Save the adler32 of the preset dictionary: */
  17142. if (s.strstart !== 0) {
  17143. putShortMSB(s, strm.adler >>> 16);
  17144. putShortMSB(s, strm.adler & 0xffff);
  17145. }
  17146. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  17147. }
  17148. }
  17149. //#ifdef GZIP
  17150. if (s.status === EXTRA_STATE) {
  17151. if (s.gzhead.extra/* != Z_NULL*/) {
  17152. beg = s.pending; /* start of bytes to update crc */
  17153. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  17154. if (s.pending === s.pending_buf_size) {
  17155. if (s.gzhead.hcrc && s.pending > beg) {
  17156. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17157. }
  17158. flush_pending(strm);
  17159. beg = s.pending;
  17160. if (s.pending === s.pending_buf_size) {
  17161. break;
  17162. }
  17163. }
  17164. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  17165. s.gzindex++;
  17166. }
  17167. if (s.gzhead.hcrc && s.pending > beg) {
  17168. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17169. }
  17170. if (s.gzindex === s.gzhead.extra.length) {
  17171. s.gzindex = 0;
  17172. s.status = NAME_STATE;
  17173. }
  17174. }
  17175. else {
  17176. s.status = NAME_STATE;
  17177. }
  17178. }
  17179. if (s.status === NAME_STATE) {
  17180. if (s.gzhead.name/* != Z_NULL*/) {
  17181. beg = s.pending; /* start of bytes to update crc */
  17182. //int val;
  17183. do {
  17184. if (s.pending === s.pending_buf_size) {
  17185. if (s.gzhead.hcrc && s.pending > beg) {
  17186. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17187. }
  17188. flush_pending(strm);
  17189. beg = s.pending;
  17190. if (s.pending === s.pending_buf_size) {
  17191. val = 1;
  17192. break;
  17193. }
  17194. }
  17195. // JS specific: little magic to add zero terminator to end of string
  17196. if (s.gzindex < s.gzhead.name.length) {
  17197. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  17198. } else {
  17199. val = 0;
  17200. }
  17201. put_byte(s, val);
  17202. } while (val !== 0);
  17203. if (s.gzhead.hcrc && s.pending > beg) {
  17204. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17205. }
  17206. if (val === 0) {
  17207. s.gzindex = 0;
  17208. s.status = COMMENT_STATE;
  17209. }
  17210. }
  17211. else {
  17212. s.status = COMMENT_STATE;
  17213. }
  17214. }
  17215. if (s.status === COMMENT_STATE) {
  17216. if (s.gzhead.comment/* != Z_NULL*/) {
  17217. beg = s.pending; /* start of bytes to update crc */
  17218. //int val;
  17219. do {
  17220. if (s.pending === s.pending_buf_size) {
  17221. if (s.gzhead.hcrc && s.pending > beg) {
  17222. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17223. }
  17224. flush_pending(strm);
  17225. beg = s.pending;
  17226. if (s.pending === s.pending_buf_size) {
  17227. val = 1;
  17228. break;
  17229. }
  17230. }
  17231. // JS specific: little magic to add zero terminator to end of string
  17232. if (s.gzindex < s.gzhead.comment.length) {
  17233. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  17234. } else {
  17235. val = 0;
  17236. }
  17237. put_byte(s, val);
  17238. } while (val !== 0);
  17239. if (s.gzhead.hcrc && s.pending > beg) {
  17240. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17241. }
  17242. if (val === 0) {
  17243. s.status = HCRC_STATE;
  17244. }
  17245. }
  17246. else {
  17247. s.status = HCRC_STATE;
  17248. }
  17249. }
  17250. if (s.status === HCRC_STATE) {
  17251. if (s.gzhead.hcrc) {
  17252. if (s.pending + 2 > s.pending_buf_size) {
  17253. flush_pending(strm);
  17254. }
  17255. if (s.pending + 2 <= s.pending_buf_size) {
  17256. put_byte(s, strm.adler & 0xff);
  17257. put_byte(s, (strm.adler >> 8) & 0xff);
  17258. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17259. s.status = BUSY_STATE;
  17260. }
  17261. }
  17262. else {
  17263. s.status = BUSY_STATE;
  17264. }
  17265. }
  17266. //#endif
  17267. /* Flush as much pending output as possible */
  17268. if (s.pending !== 0) {
  17269. flush_pending(strm);
  17270. if (strm.avail_out === 0) {
  17271. /* Since avail_out is 0, deflate will be called again with
  17272. * more output space, but possibly with both pending and
  17273. * avail_in equal to zero. There won't be anything to do,
  17274. * but this is not an error situation so make sure we
  17275. * return OK instead of BUF_ERROR at next call of deflate:
  17276. */
  17277. s.last_flush = -1;
  17278. return Z_OK;
  17279. }
  17280. /* Make sure there is something to do and avoid duplicate consecutive
  17281. * flushes. For repeated and useless calls with Z_FINISH, we keep
  17282. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  17283. */
  17284. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  17285. flush !== Z_FINISH) {
  17286. return err(strm, Z_BUF_ERROR);
  17287. }
  17288. /* User must not provide more input after the first FINISH: */
  17289. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  17290. return err(strm, Z_BUF_ERROR);
  17291. }
  17292. /* Start a new block or continue the current one.
  17293. */
  17294. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  17295. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  17296. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  17297. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  17298. configuration_table[s.level].func(s, flush));
  17299. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  17300. s.status = FINISH_STATE;
  17301. }
  17302. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  17303. if (strm.avail_out === 0) {
  17304. s.last_flush = -1;
  17305. /* avoid BUF_ERROR next call, see above */
  17306. }
  17307. return Z_OK;
  17308. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  17309. * of deflate should use the same flush parameter to make sure
  17310. * that the flush is complete. So we don't have to output an
  17311. * empty block here, this will be done at next call. This also
  17312. * ensures that for a very small output buffer, we emit at most
  17313. * one empty block.
  17314. */
  17315. }
  17316. if (bstate === BS_BLOCK_DONE) {
  17317. if (flush === Z_PARTIAL_FLUSH) {
  17318. trees._tr_align(s);
  17319. }
  17320. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  17321. trees._tr_stored_block(s, 0, 0, false);
  17322. /* For a full flush, this empty block will be recognized
  17323. * as a special marker by inflate_sync().
  17324. */
  17325. if (flush === Z_FULL_FLUSH) {
  17326. /*** CLEAR_HASH(s); ***/ /* forget history */
  17327. zero(s.head); // Fill with NIL (= 0);
  17328. if (s.lookahead === 0) {
  17329. s.strstart = 0;
  17330. s.block_start = 0;
  17331. s.insert = 0;
  17332. }
  17333. }
  17334. }
  17335. flush_pending(strm);
  17336. if (strm.avail_out === 0) {
  17337. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17338. return Z_OK;
  17339. }
  17340. }
  17341. }
  17342. //Assert(strm->avail_out > 0, "bug2");
  17343. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17344. if (flush !== Z_FINISH) { return Z_OK; }
  17345. if (s.wrap <= 0) { return Z_STREAM_END; }
  17346. /* Write the trailer */
  17347. if (s.wrap === 2) {
  17348. put_byte(s, strm.adler & 0xff);
  17349. put_byte(s, (strm.adler >> 8) & 0xff);
  17350. put_byte(s, (strm.adler >> 16) & 0xff);
  17351. put_byte(s, (strm.adler >> 24) & 0xff);
  17352. put_byte(s, strm.total_in & 0xff);
  17353. put_byte(s, (strm.total_in >> 8) & 0xff);
  17354. put_byte(s, (strm.total_in >> 16) & 0xff);
  17355. put_byte(s, (strm.total_in >> 24) & 0xff);
  17356. }
  17357. else
  17358. {
  17359. putShortMSB(s, strm.adler >>> 16);
  17360. putShortMSB(s, strm.adler & 0xffff);
  17361. }
  17362. flush_pending(strm);
  17363. /* If avail_out is zero, the application will call deflate again
  17364. * to flush the rest.
  17365. */
  17366. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17367. /* write the trailer only once! */
  17368. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17369. }
  17370. function deflateEnd(strm) {
  17371. var status;
  17372. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17373. return Z_STREAM_ERROR;
  17374. }
  17375. status = strm.state.status;
  17376. if (status !== INIT_STATE &&
  17377. status !== EXTRA_STATE &&
  17378. status !== NAME_STATE &&
  17379. status !== COMMENT_STATE &&
  17380. status !== HCRC_STATE &&
  17381. status !== BUSY_STATE &&
  17382. status !== FINISH_STATE
  17383. ) {
  17384. return err(strm, Z_STREAM_ERROR);
  17385. }
  17386. strm.state = null;
  17387. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17388. }
  17389. /* =========================================================================
  17390. * Copy the source state to the destination state
  17391. */
  17392. //function deflateCopy(dest, source) {
  17393. //
  17394. //}
  17395. exports.deflateInit = deflateInit;
  17396. exports.deflateInit2 = deflateInit2;
  17397. exports.deflateReset = deflateReset;
  17398. exports.deflateResetKeep = deflateResetKeep;
  17399. exports.deflateSetHeader = deflateSetHeader;
  17400. exports.deflate = deflate;
  17401. exports.deflateEnd = deflateEnd;
  17402. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17403. /* Not implemented
  17404. exports.deflateBound = deflateBound;
  17405. exports.deflateCopy = deflateCopy;
  17406. exports.deflateSetDictionary = deflateSetDictionary;
  17407. exports.deflateParams = deflateParams;
  17408. exports.deflatePending = deflatePending;
  17409. exports.deflatePrime = deflatePrime;
  17410. exports.deflateTune = deflateTune;
  17411. */
  17412. },{"../utils/common":127,"./adler32":129,"./crc32":131,"./messages":137,"./trees":138}],133:[function(require,module,exports){
  17413. 'use strict';
  17414. function GZheader() {
  17415. /* true if compressed data believed to be text */
  17416. this.text = 0;
  17417. /* modification time */
  17418. this.time = 0;
  17419. /* extra flags (not used when writing a gzip file) */
  17420. this.xflags = 0;
  17421. /* operating system */
  17422. this.os = 0;
  17423. /* pointer to extra field or Z_NULL if none */
  17424. this.extra = null;
  17425. /* extra field length (valid if extra != Z_NULL) */
  17426. this.extra_len = 0; // Actually, we don't need it in JS,
  17427. // but leave for few code modifications
  17428. //
  17429. // Setup limits is not necessary because in js we should not preallocate memory
  17430. // for inflate use constant limit in 65536 bytes
  17431. //
  17432. /* space at extra (only when reading header) */
  17433. // this.extra_max = 0;
  17434. /* pointer to zero-terminated file name or Z_NULL */
  17435. this.name = '';
  17436. /* space at name (only when reading header) */
  17437. // this.name_max = 0;
  17438. /* pointer to zero-terminated comment or Z_NULL */
  17439. this.comment = '';
  17440. /* space at comment (only when reading header) */
  17441. // this.comm_max = 0;
  17442. /* true if there was or will be a header crc */
  17443. this.hcrc = 0;
  17444. /* true when done reading gzip header (not used when writing a gzip file) */
  17445. this.done = false;
  17446. }
  17447. module.exports = GZheader;
  17448. },{}],134:[function(require,module,exports){
  17449. 'use strict';
  17450. // See state defs from inflate.js
  17451. var BAD = 30; /* got a data error -- remain here until reset */
  17452. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17453. /*
  17454. Decode literal, length, and distance codes and write out the resulting
  17455. literal and match bytes until either not enough input or output is
  17456. available, an end-of-block is encountered, or a data error is encountered.
  17457. When large enough input and output buffers are supplied to inflate(), for
  17458. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17459. inflate execution time is spent in this routine.
  17460. Entry assumptions:
  17461. state.mode === LEN
  17462. strm.avail_in >= 6
  17463. strm.avail_out >= 258
  17464. start >= strm.avail_out
  17465. state.bits < 8
  17466. On return, state.mode is one of:
  17467. LEN -- ran out of enough output space or enough available input
  17468. TYPE -- reached end of block code, inflate() to interpret next block
  17469. BAD -- error in block data
  17470. Notes:
  17471. - The maximum input bits used by a length/distance pair is 15 bits for the
  17472. length code, 5 bits for the length extra, 15 bits for the distance code,
  17473. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17474. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17475. checking for available input while decoding.
  17476. - The maximum bytes that a single length/distance pair can output is 258
  17477. bytes, which is the maximum length that can be coded. inflate_fast()
  17478. requires strm.avail_out >= 258 for each loop to avoid checking for
  17479. output space.
  17480. */
  17481. module.exports = function inflate_fast(strm, start) {
  17482. var state;
  17483. var _in; /* local strm.input */
  17484. var last; /* have enough input while in < last */
  17485. var _out; /* local strm.output */
  17486. var beg; /* inflate()'s initial strm.output */
  17487. var end; /* while out < end, enough space available */
  17488. //#ifdef INFLATE_STRICT
  17489. var dmax; /* maximum distance from zlib header */
  17490. //#endif
  17491. var wsize; /* window size or zero if not using window */
  17492. var whave; /* valid bytes in the window */
  17493. var wnext; /* window write index */
  17494. var window; /* allocated sliding window, if wsize != 0 */
  17495. var hold; /* local strm.hold */
  17496. var bits; /* local strm.bits */
  17497. var lcode; /* local strm.lencode */
  17498. var dcode; /* local strm.distcode */
  17499. var lmask; /* mask for first level of length codes */
  17500. var dmask; /* mask for first level of distance codes */
  17501. var here; /* retrieved table entry */
  17502. var op; /* code bits, operation, extra bits, or */
  17503. /* window position, window bytes to copy */
  17504. var len; /* match length, unused bytes */
  17505. var dist; /* match distance */
  17506. var from; /* where to copy match from */
  17507. var from_source;
  17508. var input, output; // JS specific, because we have no pointers
  17509. /* copy state to local variables */
  17510. state = strm.state;
  17511. //here = state.here;
  17512. _in = strm.next_in;
  17513. input = strm.input;
  17514. last = _in + (strm.avail_in - 5);
  17515. _out = strm.next_out;
  17516. output = strm.output;
  17517. beg = _out - (start - strm.avail_out);
  17518. end = _out + (strm.avail_out - 257);
  17519. //#ifdef INFLATE_STRICT
  17520. dmax = state.dmax;
  17521. //#endif
  17522. wsize = state.wsize;
  17523. whave = state.whave;
  17524. wnext = state.wnext;
  17525. window = state.window;
  17526. hold = state.hold;
  17527. bits = state.bits;
  17528. lcode = state.lencode;
  17529. dcode = state.distcode;
  17530. lmask = (1 << state.lenbits) - 1;
  17531. dmask = (1 << state.distbits) - 1;
  17532. /* decode literals and length/distances until end-of-block or not enough
  17533. input data or output space */
  17534. top:
  17535. do {
  17536. if (bits < 15) {
  17537. hold += input[_in++] << bits;
  17538. bits += 8;
  17539. hold += input[_in++] << bits;
  17540. bits += 8;
  17541. }
  17542. here = lcode[hold & lmask];
  17543. dolen:
  17544. for (;;) { // Goto emulation
  17545. op = here >>> 24/*here.bits*/;
  17546. hold >>>= op;
  17547. bits -= op;
  17548. op = (here >>> 16) & 0xff/*here.op*/;
  17549. if (op === 0) { /* literal */
  17550. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17551. // "inflate: literal '%c'\n" :
  17552. // "inflate: literal 0x%02x\n", here.val));
  17553. output[_out++] = here & 0xffff/*here.val*/;
  17554. }
  17555. else if (op & 16) { /* length base */
  17556. len = here & 0xffff/*here.val*/;
  17557. op &= 15; /* number of extra bits */
  17558. if (op) {
  17559. if (bits < op) {
  17560. hold += input[_in++] << bits;
  17561. bits += 8;
  17562. }
  17563. len += hold & ((1 << op) - 1);
  17564. hold >>>= op;
  17565. bits -= op;
  17566. }
  17567. //Tracevv((stderr, "inflate: length %u\n", len));
  17568. if (bits < 15) {
  17569. hold += input[_in++] << bits;
  17570. bits += 8;
  17571. hold += input[_in++] << bits;
  17572. bits += 8;
  17573. }
  17574. here = dcode[hold & dmask];
  17575. dodist:
  17576. for (;;) { // goto emulation
  17577. op = here >>> 24/*here.bits*/;
  17578. hold >>>= op;
  17579. bits -= op;
  17580. op = (here >>> 16) & 0xff/*here.op*/;
  17581. if (op & 16) { /* distance base */
  17582. dist = here & 0xffff/*here.val*/;
  17583. op &= 15; /* number of extra bits */
  17584. if (bits < op) {
  17585. hold += input[_in++] << bits;
  17586. bits += 8;
  17587. if (bits < op) {
  17588. hold += input[_in++] << bits;
  17589. bits += 8;
  17590. }
  17591. }
  17592. dist += hold & ((1 << op) - 1);
  17593. //#ifdef INFLATE_STRICT
  17594. if (dist > dmax) {
  17595. strm.msg = 'invalid distance too far back';
  17596. state.mode = BAD;
  17597. break top;
  17598. }
  17599. //#endif
  17600. hold >>>= op;
  17601. bits -= op;
  17602. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17603. op = _out - beg; /* max distance in output */
  17604. if (dist > op) { /* see if copy from window */
  17605. op = dist - op; /* distance back in window */
  17606. if (op > whave) {
  17607. if (state.sane) {
  17608. strm.msg = 'invalid distance too far back';
  17609. state.mode = BAD;
  17610. break top;
  17611. }
  17612. // (!) This block is disabled in zlib defailts,
  17613. // don't enable it for binary compatibility
  17614. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17615. // if (len <= op - whave) {
  17616. // do {
  17617. // output[_out++] = 0;
  17618. // } while (--len);
  17619. // continue top;
  17620. // }
  17621. // len -= op - whave;
  17622. // do {
  17623. // output[_out++] = 0;
  17624. // } while (--op > whave);
  17625. // if (op === 0) {
  17626. // from = _out - dist;
  17627. // do {
  17628. // output[_out++] = output[from++];
  17629. // } while (--len);
  17630. // continue top;
  17631. // }
  17632. //#endif
  17633. }
  17634. from = 0; // window index
  17635. from_source = window;
  17636. if (wnext === 0) { /* very common case */
  17637. from += wsize - op;
  17638. if (op < len) { /* some from window */
  17639. len -= op;
  17640. do {
  17641. output[_out++] = window[from++];
  17642. } while (--op);
  17643. from = _out - dist; /* rest from output */
  17644. from_source = output;
  17645. }
  17646. }
  17647. else if (wnext < op) { /* wrap around window */
  17648. from += wsize + wnext - op;
  17649. op -= wnext;
  17650. if (op < len) { /* some from end of window */
  17651. len -= op;
  17652. do {
  17653. output[_out++] = window[from++];
  17654. } while (--op);
  17655. from = 0;
  17656. if (wnext < len) { /* some from start of window */
  17657. op = wnext;
  17658. len -= op;
  17659. do {
  17660. output[_out++] = window[from++];
  17661. } while (--op);
  17662. from = _out - dist; /* rest from output */
  17663. from_source = output;
  17664. }
  17665. }
  17666. }
  17667. else { /* contiguous in window */
  17668. from += wnext - op;
  17669. if (op < len) { /* some from window */
  17670. len -= op;
  17671. do {
  17672. output[_out++] = window[from++];
  17673. } while (--op);
  17674. from = _out - dist; /* rest from output */
  17675. from_source = output;
  17676. }
  17677. }
  17678. while (len > 2) {
  17679. output[_out++] = from_source[from++];
  17680. output[_out++] = from_source[from++];
  17681. output[_out++] = from_source[from++];
  17682. len -= 3;
  17683. }
  17684. if (len) {
  17685. output[_out++] = from_source[from++];
  17686. if (len > 1) {
  17687. output[_out++] = from_source[from++];
  17688. }
  17689. }
  17690. }
  17691. else {
  17692. from = _out - dist; /* copy direct from output */
  17693. do { /* minimum length is three */
  17694. output[_out++] = output[from++];
  17695. output[_out++] = output[from++];
  17696. output[_out++] = output[from++];
  17697. len -= 3;
  17698. } while (len > 2);
  17699. if (len) {
  17700. output[_out++] = output[from++];
  17701. if (len > 1) {
  17702. output[_out++] = output[from++];
  17703. }
  17704. }
  17705. }
  17706. }
  17707. else if ((op & 64) === 0) { /* 2nd level distance code */
  17708. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17709. continue dodist;
  17710. }
  17711. else {
  17712. strm.msg = 'invalid distance code';
  17713. state.mode = BAD;
  17714. break top;
  17715. }
  17716. break; // need to emulate goto via "continue"
  17717. }
  17718. }
  17719. else if ((op & 64) === 0) { /* 2nd level length code */
  17720. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17721. continue dolen;
  17722. }
  17723. else if (op & 32) { /* end-of-block */
  17724. //Tracevv((stderr, "inflate: end of block\n"));
  17725. state.mode = TYPE;
  17726. break top;
  17727. }
  17728. else {
  17729. strm.msg = 'invalid literal/length code';
  17730. state.mode = BAD;
  17731. break top;
  17732. }
  17733. break; // need to emulate goto via "continue"
  17734. }
  17735. } while (_in < last && _out < end);
  17736. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17737. len = bits >> 3;
  17738. _in -= len;
  17739. bits -= len << 3;
  17740. hold &= (1 << bits) - 1;
  17741. /* update state and return */
  17742. strm.next_in = _in;
  17743. strm.next_out = _out;
  17744. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17745. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17746. state.hold = hold;
  17747. state.bits = bits;
  17748. return;
  17749. };
  17750. },{}],135:[function(require,module,exports){
  17751. 'use strict';
  17752. var utils = require('../utils/common');
  17753. var adler32 = require('./adler32');
  17754. var crc32 = require('./crc32');
  17755. var inflate_fast = require('./inffast');
  17756. var inflate_table = require('./inftrees');
  17757. var CODES = 0;
  17758. var LENS = 1;
  17759. var DISTS = 2;
  17760. /* Public constants ==========================================================*/
  17761. /* ===========================================================================*/
  17762. /* Allowed flush values; see deflate() and inflate() below for details */
  17763. //var Z_NO_FLUSH = 0;
  17764. //var Z_PARTIAL_FLUSH = 1;
  17765. //var Z_SYNC_FLUSH = 2;
  17766. //var Z_FULL_FLUSH = 3;
  17767. var Z_FINISH = 4;
  17768. var Z_BLOCK = 5;
  17769. var Z_TREES = 6;
  17770. /* Return codes for the compression/decompression functions. Negative values
  17771. * are errors, positive values are used for special but normal events.
  17772. */
  17773. var Z_OK = 0;
  17774. var Z_STREAM_END = 1;
  17775. var Z_NEED_DICT = 2;
  17776. //var Z_ERRNO = -1;
  17777. var Z_STREAM_ERROR = -2;
  17778. var Z_DATA_ERROR = -3;
  17779. var Z_MEM_ERROR = -4;
  17780. var Z_BUF_ERROR = -5;
  17781. //var Z_VERSION_ERROR = -6;
  17782. /* The deflate compression method */
  17783. var Z_DEFLATED = 8;
  17784. /* STATES ====================================================================*/
  17785. /* ===========================================================================*/
  17786. var HEAD = 1; /* i: waiting for magic header */
  17787. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17788. var TIME = 3; /* i: waiting for modification time (gzip) */
  17789. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17790. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17791. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17792. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17793. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17794. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17795. var DICTID = 10; /* i: waiting for dictionary check value */
  17796. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17797. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17798. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17799. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17800. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17801. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17802. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17803. var LENLENS = 18; /* i: waiting for code length code lengths */
  17804. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17805. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17806. var LEN = 21; /* i: waiting for length/lit/eob code */
  17807. var LENEXT = 22; /* i: waiting for length extra bits */
  17808. var DIST = 23; /* i: waiting for distance code */
  17809. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17810. var MATCH = 25; /* o: waiting for output space to copy string */
  17811. var LIT = 26; /* o: waiting for output space to write literal */
  17812. var CHECK = 27; /* i: waiting for 32-bit check value */
  17813. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17814. var DONE = 29; /* finished check, done -- remain here until reset */
  17815. var BAD = 30; /* got a data error -- remain here until reset */
  17816. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17817. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17818. /* ===========================================================================*/
  17819. var ENOUGH_LENS = 852;
  17820. var ENOUGH_DISTS = 592;
  17821. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17822. var MAX_WBITS = 15;
  17823. /* 32K LZ77 window */
  17824. var DEF_WBITS = MAX_WBITS;
  17825. function ZSWAP32(q) {
  17826. return (((q >>> 24) & 0xff) +
  17827. ((q >>> 8) & 0xff00) +
  17828. ((q & 0xff00) << 8) +
  17829. ((q & 0xff) << 24));
  17830. }
  17831. function InflateState() {
  17832. this.mode = 0; /* current inflate mode */
  17833. this.last = false; /* true if processing last block */
  17834. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17835. this.havedict = false; /* true if dictionary provided */
  17836. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17837. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17838. this.check = 0; /* protected copy of check value */
  17839. this.total = 0; /* protected copy of output count */
  17840. // TODO: may be {}
  17841. this.head = null; /* where to save gzip header information */
  17842. /* sliding window */
  17843. this.wbits = 0; /* log base 2 of requested window size */
  17844. this.wsize = 0; /* window size or zero if not using window */
  17845. this.whave = 0; /* valid bytes in the window */
  17846. this.wnext = 0; /* window write index */
  17847. this.window = null; /* allocated sliding window, if needed */
  17848. /* bit accumulator */
  17849. this.hold = 0; /* input bit accumulator */
  17850. this.bits = 0; /* number of bits in "in" */
  17851. /* for string and stored block copying */
  17852. this.length = 0; /* literal or length of data to copy */
  17853. this.offset = 0; /* distance back to copy string from */
  17854. /* for table and code decoding */
  17855. this.extra = 0; /* extra bits needed */
  17856. /* fixed and dynamic code tables */
  17857. this.lencode = null; /* starting table for length/literal codes */
  17858. this.distcode = null; /* starting table for distance codes */
  17859. this.lenbits = 0; /* index bits for lencode */
  17860. this.distbits = 0; /* index bits for distcode */
  17861. /* dynamic table building */
  17862. this.ncode = 0; /* number of code length code lengths */
  17863. this.nlen = 0; /* number of length code lengths */
  17864. this.ndist = 0; /* number of distance code lengths */
  17865. this.have = 0; /* number of code lengths in lens[] */
  17866. this.next = null; /* next available space in codes[] */
  17867. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17868. this.work = new utils.Buf16(288); /* work area for code table building */
  17869. /*
  17870. because we don't have pointers in js, we use lencode and distcode directly
  17871. as buffers so we don't need codes
  17872. */
  17873. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17874. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17875. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17876. this.sane = 0; /* if false, allow invalid distance too far */
  17877. this.back = 0; /* bits back of last unprocessed length/lit */
  17878. this.was = 0; /* initial length of match */
  17879. }
  17880. function inflateResetKeep(strm) {
  17881. var state;
  17882. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17883. state = strm.state;
  17884. strm.total_in = strm.total_out = state.total = 0;
  17885. strm.msg = ''; /*Z_NULL*/
  17886. if (state.wrap) { /* to support ill-conceived Java test suite */
  17887. strm.adler = state.wrap & 1;
  17888. }
  17889. state.mode = HEAD;
  17890. state.last = 0;
  17891. state.havedict = 0;
  17892. state.dmax = 32768;
  17893. state.head = null/*Z_NULL*/;
  17894. state.hold = 0;
  17895. state.bits = 0;
  17896. //state.lencode = state.distcode = state.next = state.codes;
  17897. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17898. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17899. state.sane = 1;
  17900. state.back = -1;
  17901. //Tracev((stderr, "inflate: reset\n"));
  17902. return Z_OK;
  17903. }
  17904. function inflateReset(strm) {
  17905. var state;
  17906. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17907. state = strm.state;
  17908. state.wsize = 0;
  17909. state.whave = 0;
  17910. state.wnext = 0;
  17911. return inflateResetKeep(strm);
  17912. }
  17913. function inflateReset2(strm, windowBits) {
  17914. var wrap;
  17915. var state;
  17916. /* get the state */
  17917. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17918. state = strm.state;
  17919. /* extract wrap request from windowBits parameter */
  17920. if (windowBits < 0) {
  17921. wrap = 0;
  17922. windowBits = -windowBits;
  17923. }
  17924. else {
  17925. wrap = (windowBits >> 4) + 1;
  17926. if (windowBits < 48) {
  17927. windowBits &= 15;
  17928. }
  17929. }
  17930. /* set number of window bits, free window if different */
  17931. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17932. return Z_STREAM_ERROR;
  17933. }
  17934. if (state.window !== null && state.wbits !== windowBits) {
  17935. state.window = null;
  17936. }
  17937. /* update state and reset the rest of it */
  17938. state.wrap = wrap;
  17939. state.wbits = windowBits;
  17940. return inflateReset(strm);
  17941. }
  17942. function inflateInit2(strm, windowBits) {
  17943. var ret;
  17944. var state;
  17945. if (!strm) { return Z_STREAM_ERROR; }
  17946. //strm.msg = Z_NULL; /* in case we return an error */
  17947. state = new InflateState();
  17948. //if (state === Z_NULL) return Z_MEM_ERROR;
  17949. //Tracev((stderr, "inflate: allocated\n"));
  17950. strm.state = state;
  17951. state.window = null/*Z_NULL*/;
  17952. ret = inflateReset2(strm, windowBits);
  17953. if (ret !== Z_OK) {
  17954. strm.state = null/*Z_NULL*/;
  17955. }
  17956. return ret;
  17957. }
  17958. function inflateInit(strm) {
  17959. return inflateInit2(strm, DEF_WBITS);
  17960. }
  17961. /*
  17962. Return state with length and distance decoding tables and index sizes set to
  17963. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17964. If BUILDFIXED is defined, then instead this routine builds the tables the
  17965. first time it's called, and returns those tables the first time and
  17966. thereafter. This reduces the size of the code by about 2K bytes, in
  17967. exchange for a little execution time. However, BUILDFIXED should not be
  17968. used for threaded applications, since the rewriting of the tables and virgin
  17969. may not be thread-safe.
  17970. */
  17971. var virgin = true;
  17972. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17973. function fixedtables(state) {
  17974. /* build fixed huffman tables if first call (may not be thread safe) */
  17975. if (virgin) {
  17976. var sym;
  17977. lenfix = new utils.Buf32(512);
  17978. distfix = new utils.Buf32(32);
  17979. /* literal/length table */
  17980. sym = 0;
  17981. while (sym < 144) { state.lens[sym++] = 8; }
  17982. while (sym < 256) { state.lens[sym++] = 9; }
  17983. while (sym < 280) { state.lens[sym++] = 7; }
  17984. while (sym < 288) { state.lens[sym++] = 8; }
  17985. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17986. /* distance table */
  17987. sym = 0;
  17988. while (sym < 32) { state.lens[sym++] = 5; }
  17989. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17990. /* do this just once */
  17991. virgin = false;
  17992. }
  17993. state.lencode = lenfix;
  17994. state.lenbits = 9;
  17995. state.distcode = distfix;
  17996. state.distbits = 5;
  17997. }
  17998. /*
  17999. Update the window with the last wsize (normally 32K) bytes written before
  18000. returning. If window does not exist yet, create it. This is only called
  18001. when a window is already in use, or when output has been written during this
  18002. inflate call, but the end of the deflate stream has not been reached yet.
  18003. It is also called to create a window for dictionary data when a dictionary
  18004. is loaded.
  18005. Providing output buffers larger than 32K to inflate() should provide a speed
  18006. advantage, since only the last 32K of output is copied to the sliding window
  18007. upon return from inflate(), and since all distances after the first 32K of
  18008. output will fall in the output data, making match copies simpler and faster.
  18009. The advantage may be dependent on the size of the processor's data caches.
  18010. */
  18011. function updatewindow(strm, src, end, copy) {
  18012. var dist;
  18013. var state = strm.state;
  18014. /* if it hasn't been done already, allocate space for the window */
  18015. if (state.window === null) {
  18016. state.wsize = 1 << state.wbits;
  18017. state.wnext = 0;
  18018. state.whave = 0;
  18019. state.window = new utils.Buf8(state.wsize);
  18020. }
  18021. /* copy state->wsize or less output bytes into the circular window */
  18022. if (copy >= state.wsize) {
  18023. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  18024. state.wnext = 0;
  18025. state.whave = state.wsize;
  18026. }
  18027. else {
  18028. dist = state.wsize - state.wnext;
  18029. if (dist > copy) {
  18030. dist = copy;
  18031. }
  18032. //zmemcpy(state->window + state->wnext, end - copy, dist);
  18033. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  18034. copy -= dist;
  18035. if (copy) {
  18036. //zmemcpy(state->window, end - copy, copy);
  18037. utils.arraySet(state.window,src, end - copy, copy, 0);
  18038. state.wnext = copy;
  18039. state.whave = state.wsize;
  18040. }
  18041. else {
  18042. state.wnext += dist;
  18043. if (state.wnext === state.wsize) { state.wnext = 0; }
  18044. if (state.whave < state.wsize) { state.whave += dist; }
  18045. }
  18046. }
  18047. return 0;
  18048. }
  18049. function inflate(strm, flush) {
  18050. var state;
  18051. var input, output; // input/output buffers
  18052. var next; /* next input INDEX */
  18053. var put; /* next output INDEX */
  18054. var have, left; /* available input and output */
  18055. var hold; /* bit buffer */
  18056. var bits; /* bits in bit buffer */
  18057. var _in, _out; /* save starting available input and output */
  18058. var copy; /* number of stored or match bytes to copy */
  18059. var from; /* where to copy match bytes from */
  18060. var from_source;
  18061. var here = 0; /* current decoding table entry */
  18062. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  18063. //var last; /* parent table entry */
  18064. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  18065. var len; /* length to copy for repeats, bits to drop */
  18066. var ret; /* return code */
  18067. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  18068. var opts;
  18069. var n; // temporary var for NEED_BITS
  18070. var order = /* permutation of code lengths */
  18071. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  18072. if (!strm || !strm.state || !strm.output ||
  18073. (!strm.input && strm.avail_in !== 0)) {
  18074. return Z_STREAM_ERROR;
  18075. }
  18076. state = strm.state;
  18077. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  18078. //--- LOAD() ---
  18079. put = strm.next_out;
  18080. output = strm.output;
  18081. left = strm.avail_out;
  18082. next = strm.next_in;
  18083. input = strm.input;
  18084. have = strm.avail_in;
  18085. hold = state.hold;
  18086. bits = state.bits;
  18087. //---
  18088. _in = have;
  18089. _out = left;
  18090. ret = Z_OK;
  18091. inf_leave: // goto emulation
  18092. for (;;) {
  18093. switch (state.mode) {
  18094. case HEAD:
  18095. if (state.wrap === 0) {
  18096. state.mode = TYPEDO;
  18097. break;
  18098. }
  18099. //=== NEEDBITS(16);
  18100. while (bits < 16) {
  18101. if (have === 0) { break inf_leave; }
  18102. have--;
  18103. hold += input[next++] << bits;
  18104. bits += 8;
  18105. }
  18106. //===//
  18107. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  18108. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  18109. //=== CRC2(state.check, hold);
  18110. hbuf[0] = hold & 0xff;
  18111. hbuf[1] = (hold >>> 8) & 0xff;
  18112. state.check = crc32(state.check, hbuf, 2, 0);
  18113. //===//
  18114. //=== INITBITS();
  18115. hold = 0;
  18116. bits = 0;
  18117. //===//
  18118. state.mode = FLAGS;
  18119. break;
  18120. }
  18121. state.flags = 0; /* expect zlib header */
  18122. if (state.head) {
  18123. state.head.done = false;
  18124. }
  18125. if (!(state.wrap & 1) || /* check if zlib header allowed */
  18126. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  18127. strm.msg = 'incorrect header check';
  18128. state.mode = BAD;
  18129. break;
  18130. }
  18131. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  18132. strm.msg = 'unknown compression method';
  18133. state.mode = BAD;
  18134. break;
  18135. }
  18136. //--- DROPBITS(4) ---//
  18137. hold >>>= 4;
  18138. bits -= 4;
  18139. //---//
  18140. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  18141. if (state.wbits === 0) {
  18142. state.wbits = len;
  18143. }
  18144. else if (len > state.wbits) {
  18145. strm.msg = 'invalid window size';
  18146. state.mode = BAD;
  18147. break;
  18148. }
  18149. state.dmax = 1 << len;
  18150. //Tracev((stderr, "inflate: zlib header ok\n"));
  18151. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18152. state.mode = hold & 0x200 ? DICTID : TYPE;
  18153. //=== INITBITS();
  18154. hold = 0;
  18155. bits = 0;
  18156. //===//
  18157. break;
  18158. case FLAGS:
  18159. //=== NEEDBITS(16); */
  18160. while (bits < 16) {
  18161. if (have === 0) { break inf_leave; }
  18162. have--;
  18163. hold += input[next++] << bits;
  18164. bits += 8;
  18165. }
  18166. //===//
  18167. state.flags = hold;
  18168. if ((state.flags & 0xff) !== Z_DEFLATED) {
  18169. strm.msg = 'unknown compression method';
  18170. state.mode = BAD;
  18171. break;
  18172. }
  18173. if (state.flags & 0xe000) {
  18174. strm.msg = 'unknown header flags set';
  18175. state.mode = BAD;
  18176. break;
  18177. }
  18178. if (state.head) {
  18179. state.head.text = ((hold >> 8) & 1);
  18180. }
  18181. if (state.flags & 0x0200) {
  18182. //=== CRC2(state.check, hold);
  18183. hbuf[0] = hold & 0xff;
  18184. hbuf[1] = (hold >>> 8) & 0xff;
  18185. state.check = crc32(state.check, hbuf, 2, 0);
  18186. //===//
  18187. }
  18188. //=== INITBITS();
  18189. hold = 0;
  18190. bits = 0;
  18191. //===//
  18192. state.mode = TIME;
  18193. /* falls through */
  18194. case TIME:
  18195. //=== NEEDBITS(32); */
  18196. while (bits < 32) {
  18197. if (have === 0) { break inf_leave; }
  18198. have--;
  18199. hold += input[next++] << bits;
  18200. bits += 8;
  18201. }
  18202. //===//
  18203. if (state.head) {
  18204. state.head.time = hold;
  18205. }
  18206. if (state.flags & 0x0200) {
  18207. //=== CRC4(state.check, hold)
  18208. hbuf[0] = hold & 0xff;
  18209. hbuf[1] = (hold >>> 8) & 0xff;
  18210. hbuf[2] = (hold >>> 16) & 0xff;
  18211. hbuf[3] = (hold >>> 24) & 0xff;
  18212. state.check = crc32(state.check, hbuf, 4, 0);
  18213. //===
  18214. }
  18215. //=== INITBITS();
  18216. hold = 0;
  18217. bits = 0;
  18218. //===//
  18219. state.mode = OS;
  18220. /* falls through */
  18221. case OS:
  18222. //=== NEEDBITS(16); */
  18223. while (bits < 16) {
  18224. if (have === 0) { break inf_leave; }
  18225. have--;
  18226. hold += input[next++] << bits;
  18227. bits += 8;
  18228. }
  18229. //===//
  18230. if (state.head) {
  18231. state.head.xflags = (hold & 0xff);
  18232. state.head.os = (hold >> 8);
  18233. }
  18234. if (state.flags & 0x0200) {
  18235. //=== CRC2(state.check, hold);
  18236. hbuf[0] = hold & 0xff;
  18237. hbuf[1] = (hold >>> 8) & 0xff;
  18238. state.check = crc32(state.check, hbuf, 2, 0);
  18239. //===//
  18240. }
  18241. //=== INITBITS();
  18242. hold = 0;
  18243. bits = 0;
  18244. //===//
  18245. state.mode = EXLEN;
  18246. /* falls through */
  18247. case EXLEN:
  18248. if (state.flags & 0x0400) {
  18249. //=== NEEDBITS(16); */
  18250. while (bits < 16) {
  18251. if (have === 0) { break inf_leave; }
  18252. have--;
  18253. hold += input[next++] << bits;
  18254. bits += 8;
  18255. }
  18256. //===//
  18257. state.length = hold;
  18258. if (state.head) {
  18259. state.head.extra_len = hold;
  18260. }
  18261. if (state.flags & 0x0200) {
  18262. //=== CRC2(state.check, hold);
  18263. hbuf[0] = hold & 0xff;
  18264. hbuf[1] = (hold >>> 8) & 0xff;
  18265. state.check = crc32(state.check, hbuf, 2, 0);
  18266. //===//
  18267. }
  18268. //=== INITBITS();
  18269. hold = 0;
  18270. bits = 0;
  18271. //===//
  18272. }
  18273. else if (state.head) {
  18274. state.head.extra = null/*Z_NULL*/;
  18275. }
  18276. state.mode = EXTRA;
  18277. /* falls through */
  18278. case EXTRA:
  18279. if (state.flags & 0x0400) {
  18280. copy = state.length;
  18281. if (copy > have) { copy = have; }
  18282. if (copy) {
  18283. if (state.head) {
  18284. len = state.head.extra_len - state.length;
  18285. if (!state.head.extra) {
  18286. // Use untyped array for more conveniend processing later
  18287. state.head.extra = new Array(state.head.extra_len);
  18288. }
  18289. utils.arraySet(
  18290. state.head.extra,
  18291. input,
  18292. next,
  18293. // extra field is limited to 65536 bytes
  18294. // - no need for additional size check
  18295. copy,
  18296. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  18297. len
  18298. );
  18299. //zmemcpy(state.head.extra + len, next,
  18300. // len + copy > state.head.extra_max ?
  18301. // state.head.extra_max - len : copy);
  18302. }
  18303. if (state.flags & 0x0200) {
  18304. state.check = crc32(state.check, input, copy, next);
  18305. }
  18306. have -= copy;
  18307. next += copy;
  18308. state.length -= copy;
  18309. }
  18310. if (state.length) { break inf_leave; }
  18311. }
  18312. state.length = 0;
  18313. state.mode = NAME;
  18314. /* falls through */
  18315. case NAME:
  18316. if (state.flags & 0x0800) {
  18317. if (have === 0) { break inf_leave; }
  18318. copy = 0;
  18319. do {
  18320. // TODO: 2 or 1 bytes?
  18321. len = input[next + copy++];
  18322. /* use constant limit because in js we should not preallocate memory */
  18323. if (state.head && len &&
  18324. (state.length < 65536 /*state.head.name_max*/)) {
  18325. state.head.name += String.fromCharCode(len);
  18326. }
  18327. } while (len && copy < have);
  18328. if (state.flags & 0x0200) {
  18329. state.check = crc32(state.check, input, copy, next);
  18330. }
  18331. have -= copy;
  18332. next += copy;
  18333. if (len) { break inf_leave; }
  18334. }
  18335. else if (state.head) {
  18336. state.head.name = null;
  18337. }
  18338. state.length = 0;
  18339. state.mode = COMMENT;
  18340. /* falls through */
  18341. case COMMENT:
  18342. if (state.flags & 0x1000) {
  18343. if (have === 0) { break inf_leave; }
  18344. copy = 0;
  18345. do {
  18346. len = input[next + copy++];
  18347. /* use constant limit because in js we should not preallocate memory */
  18348. if (state.head && len &&
  18349. (state.length < 65536 /*state.head.comm_max*/)) {
  18350. state.head.comment += String.fromCharCode(len);
  18351. }
  18352. } while (len && copy < have);
  18353. if (state.flags & 0x0200) {
  18354. state.check = crc32(state.check, input, copy, next);
  18355. }
  18356. have -= copy;
  18357. next += copy;
  18358. if (len) { break inf_leave; }
  18359. }
  18360. else if (state.head) {
  18361. state.head.comment = null;
  18362. }
  18363. state.mode = HCRC;
  18364. /* falls through */
  18365. case HCRC:
  18366. if (state.flags & 0x0200) {
  18367. //=== NEEDBITS(16); */
  18368. while (bits < 16) {
  18369. if (have === 0) { break inf_leave; }
  18370. have--;
  18371. hold += input[next++] << bits;
  18372. bits += 8;
  18373. }
  18374. //===//
  18375. if (hold !== (state.check & 0xffff)) {
  18376. strm.msg = 'header crc mismatch';
  18377. state.mode = BAD;
  18378. break;
  18379. }
  18380. //=== INITBITS();
  18381. hold = 0;
  18382. bits = 0;
  18383. //===//
  18384. }
  18385. if (state.head) {
  18386. state.head.hcrc = ((state.flags >> 9) & 1);
  18387. state.head.done = true;
  18388. }
  18389. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  18390. state.mode = TYPE;
  18391. break;
  18392. case DICTID:
  18393. //=== NEEDBITS(32); */
  18394. while (bits < 32) {
  18395. if (have === 0) { break inf_leave; }
  18396. have--;
  18397. hold += input[next++] << bits;
  18398. bits += 8;
  18399. }
  18400. //===//
  18401. strm.adler = state.check = ZSWAP32(hold);
  18402. //=== INITBITS();
  18403. hold = 0;
  18404. bits = 0;
  18405. //===//
  18406. state.mode = DICT;
  18407. /* falls through */
  18408. case DICT:
  18409. if (state.havedict === 0) {
  18410. //--- RESTORE() ---
  18411. strm.next_out = put;
  18412. strm.avail_out = left;
  18413. strm.next_in = next;
  18414. strm.avail_in = have;
  18415. state.hold = hold;
  18416. state.bits = bits;
  18417. //---
  18418. return Z_NEED_DICT;
  18419. }
  18420. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18421. state.mode = TYPE;
  18422. /* falls through */
  18423. case TYPE:
  18424. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18425. /* falls through */
  18426. case TYPEDO:
  18427. if (state.last) {
  18428. //--- BYTEBITS() ---//
  18429. hold >>>= bits & 7;
  18430. bits -= bits & 7;
  18431. //---//
  18432. state.mode = CHECK;
  18433. break;
  18434. }
  18435. //=== NEEDBITS(3); */
  18436. while (bits < 3) {
  18437. if (have === 0) { break inf_leave; }
  18438. have--;
  18439. hold += input[next++] << bits;
  18440. bits += 8;
  18441. }
  18442. //===//
  18443. state.last = (hold & 0x01)/*BITS(1)*/;
  18444. //--- DROPBITS(1) ---//
  18445. hold >>>= 1;
  18446. bits -= 1;
  18447. //---//
  18448. switch ((hold & 0x03)/*BITS(2)*/) {
  18449. case 0: /* stored block */
  18450. //Tracev((stderr, "inflate: stored block%s\n",
  18451. // state.last ? " (last)" : ""));
  18452. state.mode = STORED;
  18453. break;
  18454. case 1: /* fixed block */
  18455. fixedtables(state);
  18456. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18457. // state.last ? " (last)" : ""));
  18458. state.mode = LEN_; /* decode codes */
  18459. if (flush === Z_TREES) {
  18460. //--- DROPBITS(2) ---//
  18461. hold >>>= 2;
  18462. bits -= 2;
  18463. //---//
  18464. break inf_leave;
  18465. }
  18466. break;
  18467. case 2: /* dynamic block */
  18468. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18469. // state.last ? " (last)" : ""));
  18470. state.mode = TABLE;
  18471. break;
  18472. case 3:
  18473. strm.msg = 'invalid block type';
  18474. state.mode = BAD;
  18475. }
  18476. //--- DROPBITS(2) ---//
  18477. hold >>>= 2;
  18478. bits -= 2;
  18479. //---//
  18480. break;
  18481. case STORED:
  18482. //--- BYTEBITS() ---// /* go to byte boundary */
  18483. hold >>>= bits & 7;
  18484. bits -= bits & 7;
  18485. //---//
  18486. //=== NEEDBITS(32); */
  18487. while (bits < 32) {
  18488. if (have === 0) { break inf_leave; }
  18489. have--;
  18490. hold += input[next++] << bits;
  18491. bits += 8;
  18492. }
  18493. //===//
  18494. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18495. strm.msg = 'invalid stored block lengths';
  18496. state.mode = BAD;
  18497. break;
  18498. }
  18499. state.length = hold & 0xffff;
  18500. //Tracev((stderr, "inflate: stored length %u\n",
  18501. // state.length));
  18502. //=== INITBITS();
  18503. hold = 0;
  18504. bits = 0;
  18505. //===//
  18506. state.mode = COPY_;
  18507. if (flush === Z_TREES) { break inf_leave; }
  18508. /* falls through */
  18509. case COPY_:
  18510. state.mode = COPY;
  18511. /* falls through */
  18512. case COPY:
  18513. copy = state.length;
  18514. if (copy) {
  18515. if (copy > have) { copy = have; }
  18516. if (copy > left) { copy = left; }
  18517. if (copy === 0) { break inf_leave; }
  18518. //--- zmemcpy(put, next, copy); ---
  18519. utils.arraySet(output, input, next, copy, put);
  18520. //---//
  18521. have -= copy;
  18522. next += copy;
  18523. left -= copy;
  18524. put += copy;
  18525. state.length -= copy;
  18526. break;
  18527. }
  18528. //Tracev((stderr, "inflate: stored end\n"));
  18529. state.mode = TYPE;
  18530. break;
  18531. case TABLE:
  18532. //=== NEEDBITS(14); */
  18533. while (bits < 14) {
  18534. if (have === 0) { break inf_leave; }
  18535. have--;
  18536. hold += input[next++] << bits;
  18537. bits += 8;
  18538. }
  18539. //===//
  18540. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18541. //--- DROPBITS(5) ---//
  18542. hold >>>= 5;
  18543. bits -= 5;
  18544. //---//
  18545. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18546. //--- DROPBITS(5) ---//
  18547. hold >>>= 5;
  18548. bits -= 5;
  18549. //---//
  18550. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18551. //--- DROPBITS(4) ---//
  18552. hold >>>= 4;
  18553. bits -= 4;
  18554. //---//
  18555. //#ifndef PKZIP_BUG_WORKAROUND
  18556. if (state.nlen > 286 || state.ndist > 30) {
  18557. strm.msg = 'too many length or distance symbols';
  18558. state.mode = BAD;
  18559. break;
  18560. }
  18561. //#endif
  18562. //Tracev((stderr, "inflate: table sizes ok\n"));
  18563. state.have = 0;
  18564. state.mode = LENLENS;
  18565. /* falls through */
  18566. case LENLENS:
  18567. while (state.have < state.ncode) {
  18568. //=== NEEDBITS(3);
  18569. while (bits < 3) {
  18570. if (have === 0) { break inf_leave; }
  18571. have--;
  18572. hold += input[next++] << bits;
  18573. bits += 8;
  18574. }
  18575. //===//
  18576. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18577. //--- DROPBITS(3) ---//
  18578. hold >>>= 3;
  18579. bits -= 3;
  18580. //---//
  18581. }
  18582. while (state.have < 19) {
  18583. state.lens[order[state.have++]] = 0;
  18584. }
  18585. // We have separate tables & no pointers. 2 commented lines below not needed.
  18586. //state.next = state.codes;
  18587. //state.lencode = state.next;
  18588. // Switch to use dynamic table
  18589. state.lencode = state.lendyn;
  18590. state.lenbits = 7;
  18591. opts = {bits: state.lenbits};
  18592. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18593. state.lenbits = opts.bits;
  18594. if (ret) {
  18595. strm.msg = 'invalid code lengths set';
  18596. state.mode = BAD;
  18597. break;
  18598. }
  18599. //Tracev((stderr, "inflate: code lengths ok\n"));
  18600. state.have = 0;
  18601. state.mode = CODELENS;
  18602. /* falls through */
  18603. case CODELENS:
  18604. while (state.have < state.nlen + state.ndist) {
  18605. for (;;) {
  18606. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18607. here_bits = here >>> 24;
  18608. here_op = (here >>> 16) & 0xff;
  18609. here_val = here & 0xffff;
  18610. if ((here_bits) <= bits) { break; }
  18611. //--- PULLBYTE() ---//
  18612. if (have === 0) { break inf_leave; }
  18613. have--;
  18614. hold += input[next++] << bits;
  18615. bits += 8;
  18616. //---//
  18617. }
  18618. if (here_val < 16) {
  18619. //--- DROPBITS(here.bits) ---//
  18620. hold >>>= here_bits;
  18621. bits -= here_bits;
  18622. //---//
  18623. state.lens[state.have++] = here_val;
  18624. }
  18625. else {
  18626. if (here_val === 16) {
  18627. //=== NEEDBITS(here.bits + 2);
  18628. n = here_bits + 2;
  18629. while (bits < n) {
  18630. if (have === 0) { break inf_leave; }
  18631. have--;
  18632. hold += input[next++] << bits;
  18633. bits += 8;
  18634. }
  18635. //===//
  18636. //--- DROPBITS(here.bits) ---//
  18637. hold >>>= here_bits;
  18638. bits -= here_bits;
  18639. //---//
  18640. if (state.have === 0) {
  18641. strm.msg = 'invalid bit length repeat';
  18642. state.mode = BAD;
  18643. break;
  18644. }
  18645. len = state.lens[state.have - 1];
  18646. copy = 3 + (hold & 0x03);//BITS(2);
  18647. //--- DROPBITS(2) ---//
  18648. hold >>>= 2;
  18649. bits -= 2;
  18650. //---//
  18651. }
  18652. else if (here_val === 17) {
  18653. //=== NEEDBITS(here.bits + 3);
  18654. n = here_bits + 3;
  18655. while (bits < n) {
  18656. if (have === 0) { break inf_leave; }
  18657. have--;
  18658. hold += input[next++] << bits;
  18659. bits += 8;
  18660. }
  18661. //===//
  18662. //--- DROPBITS(here.bits) ---//
  18663. hold >>>= here_bits;
  18664. bits -= here_bits;
  18665. //---//
  18666. len = 0;
  18667. copy = 3 + (hold & 0x07);//BITS(3);
  18668. //--- DROPBITS(3) ---//
  18669. hold >>>= 3;
  18670. bits -= 3;
  18671. //---//
  18672. }
  18673. else {
  18674. //=== NEEDBITS(here.bits + 7);
  18675. n = here_bits + 7;
  18676. while (bits < n) {
  18677. if (have === 0) { break inf_leave; }
  18678. have--;
  18679. hold += input[next++] << bits;
  18680. bits += 8;
  18681. }
  18682. //===//
  18683. //--- DROPBITS(here.bits) ---//
  18684. hold >>>= here_bits;
  18685. bits -= here_bits;
  18686. //---//
  18687. len = 0;
  18688. copy = 11 + (hold & 0x7f);//BITS(7);
  18689. //--- DROPBITS(7) ---//
  18690. hold >>>= 7;
  18691. bits -= 7;
  18692. //---//
  18693. }
  18694. if (state.have + copy > state.nlen + state.ndist) {
  18695. strm.msg = 'invalid bit length repeat';
  18696. state.mode = BAD;
  18697. break;
  18698. }
  18699. while (copy--) {
  18700. state.lens[state.have++] = len;
  18701. }
  18702. }
  18703. }
  18704. /* handle error breaks in while */
  18705. if (state.mode === BAD) { break; }
  18706. /* check for end-of-block code (better have one) */
  18707. if (state.lens[256] === 0) {
  18708. strm.msg = 'invalid code -- missing end-of-block';
  18709. state.mode = BAD;
  18710. break;
  18711. }
  18712. /* build code tables -- note: do not change the lenbits or distbits
  18713. values here (9 and 6) without reading the comments in inftrees.h
  18714. concerning the ENOUGH constants, which depend on those values */
  18715. state.lenbits = 9;
  18716. opts = {bits: state.lenbits};
  18717. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18718. // We have separate tables & no pointers. 2 commented lines below not needed.
  18719. // state.next_index = opts.table_index;
  18720. state.lenbits = opts.bits;
  18721. // state.lencode = state.next;
  18722. if (ret) {
  18723. strm.msg = 'invalid literal/lengths set';
  18724. state.mode = BAD;
  18725. break;
  18726. }
  18727. state.distbits = 6;
  18728. //state.distcode.copy(state.codes);
  18729. // Switch to use dynamic table
  18730. state.distcode = state.distdyn;
  18731. opts = {bits: state.distbits};
  18732. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18733. // We have separate tables & no pointers. 2 commented lines below not needed.
  18734. // state.next_index = opts.table_index;
  18735. state.distbits = opts.bits;
  18736. // state.distcode = state.next;
  18737. if (ret) {
  18738. strm.msg = 'invalid distances set';
  18739. state.mode = BAD;
  18740. break;
  18741. }
  18742. //Tracev((stderr, 'inflate: codes ok\n'));
  18743. state.mode = LEN_;
  18744. if (flush === Z_TREES) { break inf_leave; }
  18745. /* falls through */
  18746. case LEN_:
  18747. state.mode = LEN;
  18748. /* falls through */
  18749. case LEN:
  18750. if (have >= 6 && left >= 258) {
  18751. //--- RESTORE() ---
  18752. strm.next_out = put;
  18753. strm.avail_out = left;
  18754. strm.next_in = next;
  18755. strm.avail_in = have;
  18756. state.hold = hold;
  18757. state.bits = bits;
  18758. //---
  18759. inflate_fast(strm, _out);
  18760. //--- LOAD() ---
  18761. put = strm.next_out;
  18762. output = strm.output;
  18763. left = strm.avail_out;
  18764. next = strm.next_in;
  18765. input = strm.input;
  18766. have = strm.avail_in;
  18767. hold = state.hold;
  18768. bits = state.bits;
  18769. //---
  18770. if (state.mode === TYPE) {
  18771. state.back = -1;
  18772. }
  18773. break;
  18774. }
  18775. state.back = 0;
  18776. for (;;) {
  18777. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18778. here_bits = here >>> 24;
  18779. here_op = (here >>> 16) & 0xff;
  18780. here_val = here & 0xffff;
  18781. if (here_bits <= bits) { break; }
  18782. //--- PULLBYTE() ---//
  18783. if (have === 0) { break inf_leave; }
  18784. have--;
  18785. hold += input[next++] << bits;
  18786. bits += 8;
  18787. //---//
  18788. }
  18789. if (here_op && (here_op & 0xf0) === 0) {
  18790. last_bits = here_bits;
  18791. last_op = here_op;
  18792. last_val = here_val;
  18793. for (;;) {
  18794. here = state.lencode[last_val +
  18795. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18796. here_bits = here >>> 24;
  18797. here_op = (here >>> 16) & 0xff;
  18798. here_val = here & 0xffff;
  18799. if ((last_bits + here_bits) <= bits) { break; }
  18800. //--- PULLBYTE() ---//
  18801. if (have === 0) { break inf_leave; }
  18802. have--;
  18803. hold += input[next++] << bits;
  18804. bits += 8;
  18805. //---//
  18806. }
  18807. //--- DROPBITS(last.bits) ---//
  18808. hold >>>= last_bits;
  18809. bits -= last_bits;
  18810. //---//
  18811. state.back += last_bits;
  18812. }
  18813. //--- DROPBITS(here.bits) ---//
  18814. hold >>>= here_bits;
  18815. bits -= here_bits;
  18816. //---//
  18817. state.back += here_bits;
  18818. state.length = here_val;
  18819. if (here_op === 0) {
  18820. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18821. // "inflate: literal '%c'\n" :
  18822. // "inflate: literal 0x%02x\n", here.val));
  18823. state.mode = LIT;
  18824. break;
  18825. }
  18826. if (here_op & 32) {
  18827. //Tracevv((stderr, "inflate: end of block\n"));
  18828. state.back = -1;
  18829. state.mode = TYPE;
  18830. break;
  18831. }
  18832. if (here_op & 64) {
  18833. strm.msg = 'invalid literal/length code';
  18834. state.mode = BAD;
  18835. break;
  18836. }
  18837. state.extra = here_op & 15;
  18838. state.mode = LENEXT;
  18839. /* falls through */
  18840. case LENEXT:
  18841. if (state.extra) {
  18842. //=== NEEDBITS(state.extra);
  18843. n = state.extra;
  18844. while (bits < n) {
  18845. if (have === 0) { break inf_leave; }
  18846. have--;
  18847. hold += input[next++] << bits;
  18848. bits += 8;
  18849. }
  18850. //===//
  18851. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18852. //--- DROPBITS(state.extra) ---//
  18853. hold >>>= state.extra;
  18854. bits -= state.extra;
  18855. //---//
  18856. state.back += state.extra;
  18857. }
  18858. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18859. state.was = state.length;
  18860. state.mode = DIST;
  18861. /* falls through */
  18862. case DIST:
  18863. for (;;) {
  18864. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18865. here_bits = here >>> 24;
  18866. here_op = (here >>> 16) & 0xff;
  18867. here_val = here & 0xffff;
  18868. if ((here_bits) <= bits) { break; }
  18869. //--- PULLBYTE() ---//
  18870. if (have === 0) { break inf_leave; }
  18871. have--;
  18872. hold += input[next++] << bits;
  18873. bits += 8;
  18874. //---//
  18875. }
  18876. if ((here_op & 0xf0) === 0) {
  18877. last_bits = here_bits;
  18878. last_op = here_op;
  18879. last_val = here_val;
  18880. for (;;) {
  18881. here = state.distcode[last_val +
  18882. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18883. here_bits = here >>> 24;
  18884. here_op = (here >>> 16) & 0xff;
  18885. here_val = here & 0xffff;
  18886. if ((last_bits + here_bits) <= bits) { break; }
  18887. //--- PULLBYTE() ---//
  18888. if (have === 0) { break inf_leave; }
  18889. have--;
  18890. hold += input[next++] << bits;
  18891. bits += 8;
  18892. //---//
  18893. }
  18894. //--- DROPBITS(last.bits) ---//
  18895. hold >>>= last_bits;
  18896. bits -= last_bits;
  18897. //---//
  18898. state.back += last_bits;
  18899. }
  18900. //--- DROPBITS(here.bits) ---//
  18901. hold >>>= here_bits;
  18902. bits -= here_bits;
  18903. //---//
  18904. state.back += here_bits;
  18905. if (here_op & 64) {
  18906. strm.msg = 'invalid distance code';
  18907. state.mode = BAD;
  18908. break;
  18909. }
  18910. state.offset = here_val;
  18911. state.extra = (here_op) & 15;
  18912. state.mode = DISTEXT;
  18913. /* falls through */
  18914. case DISTEXT:
  18915. if (state.extra) {
  18916. //=== NEEDBITS(state.extra);
  18917. n = state.extra;
  18918. while (bits < n) {
  18919. if (have === 0) { break inf_leave; }
  18920. have--;
  18921. hold += input[next++] << bits;
  18922. bits += 8;
  18923. }
  18924. //===//
  18925. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18926. //--- DROPBITS(state.extra) ---//
  18927. hold >>>= state.extra;
  18928. bits -= state.extra;
  18929. //---//
  18930. state.back += state.extra;
  18931. }
  18932. //#ifdef INFLATE_STRICT
  18933. if (state.offset > state.dmax) {
  18934. strm.msg = 'invalid distance too far back';
  18935. state.mode = BAD;
  18936. break;
  18937. }
  18938. //#endif
  18939. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18940. state.mode = MATCH;
  18941. /* falls through */
  18942. case MATCH:
  18943. if (left === 0) { break inf_leave; }
  18944. copy = _out - left;
  18945. if (state.offset > copy) { /* copy from window */
  18946. copy = state.offset - copy;
  18947. if (copy > state.whave) {
  18948. if (state.sane) {
  18949. strm.msg = 'invalid distance too far back';
  18950. state.mode = BAD;
  18951. break;
  18952. }
  18953. // (!) This block is disabled in zlib defailts,
  18954. // don't enable it for binary compatibility
  18955. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18956. // Trace((stderr, "inflate.c too far\n"));
  18957. // copy -= state.whave;
  18958. // if (copy > state.length) { copy = state.length; }
  18959. // if (copy > left) { copy = left; }
  18960. // left -= copy;
  18961. // state.length -= copy;
  18962. // do {
  18963. // output[put++] = 0;
  18964. // } while (--copy);
  18965. // if (state.length === 0) { state.mode = LEN; }
  18966. // break;
  18967. //#endif
  18968. }
  18969. if (copy > state.wnext) {
  18970. copy -= state.wnext;
  18971. from = state.wsize - copy;
  18972. }
  18973. else {
  18974. from = state.wnext - copy;
  18975. }
  18976. if (copy > state.length) { copy = state.length; }
  18977. from_source = state.window;
  18978. }
  18979. else { /* copy from output */
  18980. from_source = output;
  18981. from = put - state.offset;
  18982. copy = state.length;
  18983. }
  18984. if (copy > left) { copy = left; }
  18985. left -= copy;
  18986. state.length -= copy;
  18987. do {
  18988. output[put++] = from_source[from++];
  18989. } while (--copy);
  18990. if (state.length === 0) { state.mode = LEN; }
  18991. break;
  18992. case LIT:
  18993. if (left === 0) { break inf_leave; }
  18994. output[put++] = state.length;
  18995. left--;
  18996. state.mode = LEN;
  18997. break;
  18998. case CHECK:
  18999. if (state.wrap) {
  19000. //=== NEEDBITS(32);
  19001. while (bits < 32) {
  19002. if (have === 0) { break inf_leave; }
  19003. have--;
  19004. // Use '|' insdead of '+' to make sure that result is signed
  19005. hold |= input[next++] << bits;
  19006. bits += 8;
  19007. }
  19008. //===//
  19009. _out -= left;
  19010. strm.total_out += _out;
  19011. state.total += _out;
  19012. if (_out) {
  19013. strm.adler = state.check =
  19014. /*UPDATE(state.check, put - _out, _out);*/
  19015. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  19016. }
  19017. _out = left;
  19018. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  19019. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  19020. strm.msg = 'incorrect data check';
  19021. state.mode = BAD;
  19022. break;
  19023. }
  19024. //=== INITBITS();
  19025. hold = 0;
  19026. bits = 0;
  19027. //===//
  19028. //Tracev((stderr, "inflate: check matches trailer\n"));
  19029. }
  19030. state.mode = LENGTH;
  19031. /* falls through */
  19032. case LENGTH:
  19033. if (state.wrap && state.flags) {
  19034. //=== NEEDBITS(32);
  19035. while (bits < 32) {
  19036. if (have === 0) { break inf_leave; }
  19037. have--;
  19038. hold += input[next++] << bits;
  19039. bits += 8;
  19040. }
  19041. //===//
  19042. if (hold !== (state.total & 0xffffffff)) {
  19043. strm.msg = 'incorrect length check';
  19044. state.mode = BAD;
  19045. break;
  19046. }
  19047. //=== INITBITS();
  19048. hold = 0;
  19049. bits = 0;
  19050. //===//
  19051. //Tracev((stderr, "inflate: length matches trailer\n"));
  19052. }
  19053. state.mode = DONE;
  19054. /* falls through */
  19055. case DONE:
  19056. ret = Z_STREAM_END;
  19057. break inf_leave;
  19058. case BAD:
  19059. ret = Z_DATA_ERROR;
  19060. break inf_leave;
  19061. case MEM:
  19062. return Z_MEM_ERROR;
  19063. case SYNC:
  19064. /* falls through */
  19065. default:
  19066. return Z_STREAM_ERROR;
  19067. }
  19068. }
  19069. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  19070. /*
  19071. Return from inflate(), updating the total counts and the check value.
  19072. If there was no progress during the inflate() call, return a buffer
  19073. error. Call updatewindow() to create and/or update the window state.
  19074. Note: a memory error from inflate() is non-recoverable.
  19075. */
  19076. //--- RESTORE() ---
  19077. strm.next_out = put;
  19078. strm.avail_out = left;
  19079. strm.next_in = next;
  19080. strm.avail_in = have;
  19081. state.hold = hold;
  19082. state.bits = bits;
  19083. //---
  19084. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  19085. (state.mode < CHECK || flush !== Z_FINISH))) {
  19086. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  19087. state.mode = MEM;
  19088. return Z_MEM_ERROR;
  19089. }
  19090. }
  19091. _in -= strm.avail_in;
  19092. _out -= strm.avail_out;
  19093. strm.total_in += _in;
  19094. strm.total_out += _out;
  19095. state.total += _out;
  19096. if (state.wrap && _out) {
  19097. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  19098. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  19099. }
  19100. strm.data_type = state.bits + (state.last ? 64 : 0) +
  19101. (state.mode === TYPE ? 128 : 0) +
  19102. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  19103. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  19104. ret = Z_BUF_ERROR;
  19105. }
  19106. return ret;
  19107. }
  19108. function inflateEnd(strm) {
  19109. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  19110. return Z_STREAM_ERROR;
  19111. }
  19112. var state = strm.state;
  19113. if (state.window) {
  19114. state.window = null;
  19115. }
  19116. strm.state = null;
  19117. return Z_OK;
  19118. }
  19119. function inflateGetHeader(strm, head) {
  19120. var state;
  19121. /* check state */
  19122. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19123. state = strm.state;
  19124. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  19125. /* save header structure */
  19126. state.head = head;
  19127. head.done = false;
  19128. return Z_OK;
  19129. }
  19130. exports.inflateReset = inflateReset;
  19131. exports.inflateReset2 = inflateReset2;
  19132. exports.inflateResetKeep = inflateResetKeep;
  19133. exports.inflateInit = inflateInit;
  19134. exports.inflateInit2 = inflateInit2;
  19135. exports.inflate = inflate;
  19136. exports.inflateEnd = inflateEnd;
  19137. exports.inflateGetHeader = inflateGetHeader;
  19138. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  19139. /* Not implemented
  19140. exports.inflateCopy = inflateCopy;
  19141. exports.inflateGetDictionary = inflateGetDictionary;
  19142. exports.inflateMark = inflateMark;
  19143. exports.inflatePrime = inflatePrime;
  19144. exports.inflateSetDictionary = inflateSetDictionary;
  19145. exports.inflateSync = inflateSync;
  19146. exports.inflateSyncPoint = inflateSyncPoint;
  19147. exports.inflateUndermine = inflateUndermine;
  19148. */
  19149. },{"../utils/common":127,"./adler32":129,"./crc32":131,"./inffast":134,"./inftrees":136}],136:[function(require,module,exports){
  19150. 'use strict';
  19151. var utils = require('../utils/common');
  19152. var MAXBITS = 15;
  19153. var ENOUGH_LENS = 852;
  19154. var ENOUGH_DISTS = 592;
  19155. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19156. var CODES = 0;
  19157. var LENS = 1;
  19158. var DISTS = 2;
  19159. var lbase = [ /* Length codes 257..285 base */
  19160. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  19161. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  19162. ];
  19163. var lext = [ /* Length codes 257..285 extra */
  19164. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  19165. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  19166. ];
  19167. var dbase = [ /* Distance codes 0..29 base */
  19168. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  19169. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  19170. 8193, 12289, 16385, 24577, 0, 0
  19171. ];
  19172. var dext = [ /* Distance codes 0..29 extra */
  19173. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  19174. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  19175. 28, 28, 29, 29, 64, 64
  19176. ];
  19177. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  19178. {
  19179. var bits = opts.bits;
  19180. //here = opts.here; /* table entry for duplication */
  19181. var len = 0; /* a code's length in bits */
  19182. var sym = 0; /* index of code symbols */
  19183. var min = 0, max = 0; /* minimum and maximum code lengths */
  19184. var root = 0; /* number of index bits for root table */
  19185. var curr = 0; /* number of index bits for current table */
  19186. var drop = 0; /* code bits to drop for sub-table */
  19187. var left = 0; /* number of prefix codes available */
  19188. var used = 0; /* code entries in table used */
  19189. var huff = 0; /* Huffman code */
  19190. var incr; /* for incrementing code, index */
  19191. var fill; /* index for replicating entries */
  19192. var low; /* low bits for current root entry */
  19193. var mask; /* mask for low root bits */
  19194. var next; /* next available space in table */
  19195. var base = null; /* base value table to use */
  19196. var base_index = 0;
  19197. // var shoextra; /* extra bits table to use */
  19198. var end; /* use base and extra for symbol > end */
  19199. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  19200. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  19201. var extra = null;
  19202. var extra_index = 0;
  19203. var here_bits, here_op, here_val;
  19204. /*
  19205. Process a set of code lengths to create a canonical Huffman code. The
  19206. code lengths are lens[0..codes-1]. Each length corresponds to the
  19207. symbols 0..codes-1. The Huffman code is generated by first sorting the
  19208. symbols by length from short to long, and retaining the symbol order
  19209. for codes with equal lengths. Then the code starts with all zero bits
  19210. for the first code of the shortest length, and the codes are integer
  19211. increments for the same length, and zeros are appended as the length
  19212. increases. For the deflate format, these bits are stored backwards
  19213. from their more natural integer increment ordering, and so when the
  19214. decoding tables are built in the large loop below, the integer codes
  19215. are incremented backwards.
  19216. This routine assumes, but does not check, that all of the entries in
  19217. lens[] are in the range 0..MAXBITS. The caller must assure this.
  19218. 1..MAXBITS is interpreted as that code length. zero means that that
  19219. symbol does not occur in this code.
  19220. The codes are sorted by computing a count of codes for each length,
  19221. creating from that a table of starting indices for each length in the
  19222. sorted table, and then entering the symbols in order in the sorted
  19223. table. The sorted table is work[], with that space being provided by
  19224. the caller.
  19225. The length counts are used for other purposes as well, i.e. finding
  19226. the minimum and maximum length codes, determining if there are any
  19227. codes at all, checking for a valid set of lengths, and looking ahead
  19228. at length counts to determine sub-table sizes when building the
  19229. decoding tables.
  19230. */
  19231. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  19232. for (len = 0; len <= MAXBITS; len++) {
  19233. count[len] = 0;
  19234. }
  19235. for (sym = 0; sym < codes; sym++) {
  19236. count[lens[lens_index + sym]]++;
  19237. }
  19238. /* bound code lengths, force root to be within code lengths */
  19239. root = bits;
  19240. for (max = MAXBITS; max >= 1; max--) {
  19241. if (count[max] !== 0) { break; }
  19242. }
  19243. if (root > max) {
  19244. root = max;
  19245. }
  19246. if (max === 0) { /* no symbols to code at all */
  19247. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  19248. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  19249. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  19250. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19251. //table.op[opts.table_index] = 64;
  19252. //table.bits[opts.table_index] = 1;
  19253. //table.val[opts.table_index++] = 0;
  19254. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19255. opts.bits = 1;
  19256. return 0; /* no symbols, but wait for decoding to report error */
  19257. }
  19258. for (min = 1; min < max; min++) {
  19259. if (count[min] !== 0) { break; }
  19260. }
  19261. if (root < min) {
  19262. root = min;
  19263. }
  19264. /* check for an over-subscribed or incomplete set of lengths */
  19265. left = 1;
  19266. for (len = 1; len <= MAXBITS; len++) {
  19267. left <<= 1;
  19268. left -= count[len];
  19269. if (left < 0) {
  19270. return -1;
  19271. } /* over-subscribed */
  19272. }
  19273. if (left > 0 && (type === CODES || max !== 1)) {
  19274. return -1; /* incomplete set */
  19275. }
  19276. /* generate offsets into symbol table for each length for sorting */
  19277. offs[1] = 0;
  19278. for (len = 1; len < MAXBITS; len++) {
  19279. offs[len + 1] = offs[len] + count[len];
  19280. }
  19281. /* sort symbols by length, by symbol order within each length */
  19282. for (sym = 0; sym < codes; sym++) {
  19283. if (lens[lens_index + sym] !== 0) {
  19284. work[offs[lens[lens_index + sym]]++] = sym;
  19285. }
  19286. }
  19287. /*
  19288. Create and fill in decoding tables. In this loop, the table being
  19289. filled is at next and has curr index bits. The code being used is huff
  19290. with length len. That code is converted to an index by dropping drop
  19291. bits off of the bottom. For codes where len is less than drop + curr,
  19292. those top drop + curr - len bits are incremented through all values to
  19293. fill the table with replicated entries.
  19294. root is the number of index bits for the root table. When len exceeds
  19295. root, sub-tables are created pointed to by the root entry with an index
  19296. of the low root bits of huff. This is saved in low to check for when a
  19297. new sub-table should be started. drop is zero when the root table is
  19298. being filled, and drop is root when sub-tables are being filled.
  19299. When a new sub-table is needed, it is necessary to look ahead in the
  19300. code lengths to determine what size sub-table is needed. The length
  19301. counts are used for this, and so count[] is decremented as codes are
  19302. entered in the tables.
  19303. used keeps track of how many table entries have been allocated from the
  19304. provided *table space. It is checked for LENS and DIST tables against
  19305. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  19306. the initial root table size constants. See the comments in inftrees.h
  19307. for more information.
  19308. sym increments through all symbols, and the loop terminates when
  19309. all codes of length max, i.e. all codes, have been processed. This
  19310. routine permits incomplete codes, so another loop after this one fills
  19311. in the rest of the decoding tables with invalid code markers.
  19312. */
  19313. /* set up for code type */
  19314. // poor man optimization - use if-else instead of switch,
  19315. // to avoid deopts in old v8
  19316. if (type === CODES) {
  19317. base = extra = work; /* dummy value--not used */
  19318. end = 19;
  19319. } else if (type === LENS) {
  19320. base = lbase;
  19321. base_index -= 257;
  19322. extra = lext;
  19323. extra_index -= 257;
  19324. end = 256;
  19325. } else { /* DISTS */
  19326. base = dbase;
  19327. extra = dext;
  19328. end = -1;
  19329. }
  19330. /* initialize opts for loop */
  19331. huff = 0; /* starting code */
  19332. sym = 0; /* starting code symbol */
  19333. len = min; /* starting code length */
  19334. next = table_index; /* current table to fill in */
  19335. curr = root; /* current table index bits */
  19336. drop = 0; /* current bits to drop from code for index */
  19337. low = -1; /* trigger new sub-table when len > root */
  19338. used = 1 << root; /* use root table entries */
  19339. mask = used - 1; /* mask for comparing low */
  19340. /* check available table space */
  19341. if ((type === LENS && used > ENOUGH_LENS) ||
  19342. (type === DISTS && used > ENOUGH_DISTS)) {
  19343. return 1;
  19344. }
  19345. var i=0;
  19346. /* process all codes and make table entries */
  19347. for (;;) {
  19348. i++;
  19349. /* create table entry */
  19350. here_bits = len - drop;
  19351. if (work[sym] < end) {
  19352. here_op = 0;
  19353. here_val = work[sym];
  19354. }
  19355. else if (work[sym] > end) {
  19356. here_op = extra[extra_index + work[sym]];
  19357. here_val = base[base_index + work[sym]];
  19358. }
  19359. else {
  19360. here_op = 32 + 64; /* end of block */
  19361. here_val = 0;
  19362. }
  19363. /* replicate for those indices with low len bits equal to huff */
  19364. incr = 1 << (len - drop);
  19365. fill = 1 << curr;
  19366. min = fill; /* save offset to next table */
  19367. do {
  19368. fill -= incr;
  19369. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19370. } while (fill !== 0);
  19371. /* backwards increment the len-bit code huff */
  19372. incr = 1 << (len - 1);
  19373. while (huff & incr) {
  19374. incr >>= 1;
  19375. }
  19376. if (incr !== 0) {
  19377. huff &= incr - 1;
  19378. huff += incr;
  19379. } else {
  19380. huff = 0;
  19381. }
  19382. /* go to next symbol, update count, len */
  19383. sym++;
  19384. if (--count[len] === 0) {
  19385. if (len === max) { break; }
  19386. len = lens[lens_index + work[sym]];
  19387. }
  19388. /* create new sub-table if needed */
  19389. if (len > root && (huff & mask) !== low) {
  19390. /* if first time, transition to sub-tables */
  19391. if (drop === 0) {
  19392. drop = root;
  19393. }
  19394. /* increment past last table */
  19395. next += min; /* here min is 1 << curr */
  19396. /* determine length of next table */
  19397. curr = len - drop;
  19398. left = 1 << curr;
  19399. while (curr + drop < max) {
  19400. left -= count[curr + drop];
  19401. if (left <= 0) { break; }
  19402. curr++;
  19403. left <<= 1;
  19404. }
  19405. /* check for enough space */
  19406. used += 1 << curr;
  19407. if ((type === LENS && used > ENOUGH_LENS) ||
  19408. (type === DISTS && used > ENOUGH_DISTS)) {
  19409. return 1;
  19410. }
  19411. /* point entry in root table to sub-table */
  19412. low = huff & mask;
  19413. /*table.op[low] = curr;
  19414. table.bits[low] = root;
  19415. table.val[low] = next - opts.table_index;*/
  19416. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19417. }
  19418. }
  19419. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19420. at most one remaining entry, since if the code is incomplete, the
  19421. maximum code length that was allowed to get this far is one bit) */
  19422. if (huff !== 0) {
  19423. //table.op[next + huff] = 64; /* invalid code marker */
  19424. //table.bits[next + huff] = len - drop;
  19425. //table.val[next + huff] = 0;
  19426. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19427. }
  19428. /* set return parameters */
  19429. //opts.table_index += used;
  19430. opts.bits = root;
  19431. return 0;
  19432. };
  19433. },{"../utils/common":127}],137:[function(require,module,exports){
  19434. 'use strict';
  19435. module.exports = {
  19436. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  19437. '1': 'stream end', /* Z_STREAM_END 1 */
  19438. '0': '', /* Z_OK 0 */
  19439. '-1': 'file error', /* Z_ERRNO (-1) */
  19440. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19441. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19442. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19443. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19444. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19445. };
  19446. },{}],138:[function(require,module,exports){
  19447. 'use strict';
  19448. var utils = require('../utils/common');
  19449. /* Public constants ==========================================================*/
  19450. /* ===========================================================================*/
  19451. //var Z_FILTERED = 1;
  19452. //var Z_HUFFMAN_ONLY = 2;
  19453. //var Z_RLE = 3;
  19454. var Z_FIXED = 4;
  19455. //var Z_DEFAULT_STRATEGY = 0;
  19456. /* Possible values of the data_type field (though see inflate()) */
  19457. var Z_BINARY = 0;
  19458. var Z_TEXT = 1;
  19459. //var Z_ASCII = 1; // = Z_TEXT
  19460. var Z_UNKNOWN = 2;
  19461. /*============================================================================*/
  19462. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19463. // From zutil.h
  19464. var STORED_BLOCK = 0;
  19465. var STATIC_TREES = 1;
  19466. var DYN_TREES = 2;
  19467. /* The three kinds of block type */
  19468. var MIN_MATCH = 3;
  19469. var MAX_MATCH = 258;
  19470. /* The minimum and maximum match lengths */
  19471. // From deflate.h
  19472. /* ===========================================================================
  19473. * Internal compression state.
  19474. */
  19475. var LENGTH_CODES = 29;
  19476. /* number of length codes, not counting the special END_BLOCK code */
  19477. var LITERALS = 256;
  19478. /* number of literal bytes 0..255 */
  19479. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19480. /* number of Literal or Length codes, including the END_BLOCK code */
  19481. var D_CODES = 30;
  19482. /* number of distance codes */
  19483. var BL_CODES = 19;
  19484. /* number of codes used to transfer the bit lengths */
  19485. var HEAP_SIZE = 2*L_CODES + 1;
  19486. /* maximum heap size */
  19487. var MAX_BITS = 15;
  19488. /* All codes must not exceed MAX_BITS bits */
  19489. var Buf_size = 16;
  19490. /* size of bit buffer in bi_buf */
  19491. /* ===========================================================================
  19492. * Constants
  19493. */
  19494. var MAX_BL_BITS = 7;
  19495. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19496. var END_BLOCK = 256;
  19497. /* end of block literal code */
  19498. var REP_3_6 = 16;
  19499. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19500. var REPZ_3_10 = 17;
  19501. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19502. var REPZ_11_138 = 18;
  19503. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19504. var extra_lbits = /* extra bits for each length code */
  19505. [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];
  19506. var extra_dbits = /* extra bits for each distance code */
  19507. [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];
  19508. var extra_blbits = /* extra bits for each bit length code */
  19509. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19510. var bl_order =
  19511. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19512. /* The lengths of the bit length codes are sent in order of decreasing
  19513. * probability, to avoid transmitting the lengths for unused bit length codes.
  19514. */
  19515. /* ===========================================================================
  19516. * Local data. These are initialized only once.
  19517. */
  19518. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19519. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19520. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19521. var static_ltree = new Array((L_CODES+2) * 2);
  19522. zero(static_ltree);
  19523. /* The static literal tree. Since the bit lengths are imposed, there is no
  19524. * need for the L_CODES extra codes used during heap construction. However
  19525. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19526. * below).
  19527. */
  19528. var static_dtree = new Array(D_CODES * 2);
  19529. zero(static_dtree);
  19530. /* The static distance tree. (Actually a trivial tree since all codes use
  19531. * 5 bits.)
  19532. */
  19533. var _dist_code = new Array(DIST_CODE_LEN);
  19534. zero(_dist_code);
  19535. /* Distance codes. The first 256 values correspond to the distances
  19536. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19537. * the 15 bit distances.
  19538. */
  19539. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19540. zero(_length_code);
  19541. /* length code for each normalized match length (0 == MIN_MATCH) */
  19542. var base_length = new Array(LENGTH_CODES);
  19543. zero(base_length);
  19544. /* First normalized length for each code (0 = MIN_MATCH) */
  19545. var base_dist = new Array(D_CODES);
  19546. zero(base_dist);
  19547. /* First normalized distance for each code (0 = distance of 1) */
  19548. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19549. this.static_tree = static_tree; /* static tree or NULL */
  19550. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19551. this.extra_base = extra_base; /* base index for extra_bits */
  19552. this.elems = elems; /* max number of elements in the tree */
  19553. this.max_length = max_length; /* max bit length for the codes */
  19554. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19555. this.has_stree = static_tree && static_tree.length;
  19556. };
  19557. var static_l_desc;
  19558. var static_d_desc;
  19559. var static_bl_desc;
  19560. var TreeDesc = function(dyn_tree, stat_desc) {
  19561. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19562. this.max_code = 0; /* largest code with non zero frequency */
  19563. this.stat_desc = stat_desc; /* the corresponding static tree */
  19564. };
  19565. function d_code(dist) {
  19566. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19567. }
  19568. /* ===========================================================================
  19569. * Output a short LSB first on the stream.
  19570. * IN assertion: there is enough room in pendingBuf.
  19571. */
  19572. function put_short (s, w) {
  19573. // put_byte(s, (uch)((w) & 0xff));
  19574. // put_byte(s, (uch)((ush)(w) >> 8));
  19575. s.pending_buf[s.pending++] = (w) & 0xff;
  19576. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19577. }
  19578. /* ===========================================================================
  19579. * Send a value on a given number of bits.
  19580. * IN assertion: length <= 16 and value fits in length bits.
  19581. */
  19582. function send_bits(s, value, length) {
  19583. if (s.bi_valid > (Buf_size - length)) {
  19584. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19585. put_short(s, s.bi_buf);
  19586. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19587. s.bi_valid += length - Buf_size;
  19588. } else {
  19589. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19590. s.bi_valid += length;
  19591. }
  19592. }
  19593. function send_code(s, c, tree) {
  19594. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19595. }
  19596. /* ===========================================================================
  19597. * Reverse the first len bits of a code, using straightforward code (a faster
  19598. * method would use a table)
  19599. * IN assertion: 1 <= len <= 15
  19600. */
  19601. function bi_reverse(code, len) {
  19602. var res = 0;
  19603. do {
  19604. res |= code & 1;
  19605. code >>>= 1;
  19606. res <<= 1;
  19607. } while (--len > 0);
  19608. return res >>> 1;
  19609. }
  19610. /* ===========================================================================
  19611. * Flush the bit buffer, keeping at most 7 bits in it.
  19612. */
  19613. function bi_flush(s) {
  19614. if (s.bi_valid === 16) {
  19615. put_short(s, s.bi_buf);
  19616. s.bi_buf = 0;
  19617. s.bi_valid = 0;
  19618. } else if (s.bi_valid >= 8) {
  19619. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19620. s.bi_buf >>= 8;
  19621. s.bi_valid -= 8;
  19622. }
  19623. }
  19624. /* ===========================================================================
  19625. * Compute the optimal bit lengths for a tree and update the total bit length
  19626. * for the current block.
  19627. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19628. * above are the tree nodes sorted by increasing frequency.
  19629. * OUT assertions: the field len is set to the optimal bit length, the
  19630. * array bl_count contains the frequencies for each bit length.
  19631. * The length opt_len is updated; static_len is also updated if stree is
  19632. * not null.
  19633. */
  19634. function gen_bitlen(s, desc)
  19635. // deflate_state *s;
  19636. // tree_desc *desc; /* the tree descriptor */
  19637. {
  19638. var tree = desc.dyn_tree;
  19639. var max_code = desc.max_code;
  19640. var stree = desc.stat_desc.static_tree;
  19641. var has_stree = desc.stat_desc.has_stree;
  19642. var extra = desc.stat_desc.extra_bits;
  19643. var base = desc.stat_desc.extra_base;
  19644. var max_length = desc.stat_desc.max_length;
  19645. var h; /* heap index */
  19646. var n, m; /* iterate over the tree elements */
  19647. var bits; /* bit length */
  19648. var xbits; /* extra bits */
  19649. var f; /* frequency */
  19650. var overflow = 0; /* number of elements with bit length too large */
  19651. for (bits = 0; bits <= MAX_BITS; bits++) {
  19652. s.bl_count[bits] = 0;
  19653. }
  19654. /* In a first pass, compute the optimal bit lengths (which may
  19655. * overflow in the case of the bit length tree).
  19656. */
  19657. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19658. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19659. n = s.heap[h];
  19660. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19661. if (bits > max_length) {
  19662. bits = max_length;
  19663. overflow++;
  19664. }
  19665. tree[n*2 + 1]/*.Len*/ = bits;
  19666. /* We overwrite tree[n].Dad which is no longer needed */
  19667. if (n > max_code) { continue; } /* not a leaf node */
  19668. s.bl_count[bits]++;
  19669. xbits = 0;
  19670. if (n >= base) {
  19671. xbits = extra[n-base];
  19672. }
  19673. f = tree[n * 2]/*.Freq*/;
  19674. s.opt_len += f * (bits + xbits);
  19675. if (has_stree) {
  19676. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19677. }
  19678. }
  19679. if (overflow === 0) { return; }
  19680. // Trace((stderr,"\nbit length overflow\n"));
  19681. /* This happens for example on obj2 and pic of the Calgary corpus */
  19682. /* Find the first bit length which could increase: */
  19683. do {
  19684. bits = max_length-1;
  19685. while (s.bl_count[bits] === 0) { bits--; }
  19686. s.bl_count[bits]--; /* move one leaf down the tree */
  19687. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19688. s.bl_count[max_length]--;
  19689. /* The brother of the overflow item also moves one step up,
  19690. * but this does not affect bl_count[max_length]
  19691. */
  19692. overflow -= 2;
  19693. } while (overflow > 0);
  19694. /* Now recompute all bit lengths, scanning in increasing frequency.
  19695. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19696. * lengths instead of fixing only the wrong ones. This idea is taken
  19697. * from 'ar' written by Haruhiko Okumura.)
  19698. */
  19699. for (bits = max_length; bits !== 0; bits--) {
  19700. n = s.bl_count[bits];
  19701. while (n !== 0) {
  19702. m = s.heap[--h];
  19703. if (m > max_code) { continue; }
  19704. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19705. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19706. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19707. tree[m*2 + 1]/*.Len*/ = bits;
  19708. }
  19709. n--;
  19710. }
  19711. }
  19712. }
  19713. /* ===========================================================================
  19714. * Generate the codes for a given tree and bit counts (which need not be
  19715. * optimal).
  19716. * IN assertion: the array bl_count contains the bit length statistics for
  19717. * the given tree and the field len is set for all tree elements.
  19718. * OUT assertion: the field code is set for all tree elements of non
  19719. * zero code length.
  19720. */
  19721. function gen_codes(tree, max_code, bl_count)
  19722. // ct_data *tree; /* the tree to decorate */
  19723. // int max_code; /* largest code with non zero frequency */
  19724. // ushf *bl_count; /* number of codes at each bit length */
  19725. {
  19726. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19727. var code = 0; /* running code value */
  19728. var bits; /* bit index */
  19729. var n; /* code index */
  19730. /* The distribution counts are first used to generate the code values
  19731. * without bit reversal.
  19732. */
  19733. for (bits = 1; bits <= MAX_BITS; bits++) {
  19734. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19735. }
  19736. /* Check that the bit counts in bl_count are consistent. The last code
  19737. * must be all ones.
  19738. */
  19739. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19740. // "inconsistent bit counts");
  19741. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19742. for (n = 0; n <= max_code; n++) {
  19743. var len = tree[n*2 + 1]/*.Len*/;
  19744. if (len === 0) { continue; }
  19745. /* Now reverse the bits */
  19746. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19747. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19748. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19749. }
  19750. }
  19751. /* ===========================================================================
  19752. * Initialize the various 'constant' tables.
  19753. */
  19754. function tr_static_init() {
  19755. var n; /* iterates over tree elements */
  19756. var bits; /* bit counter */
  19757. var length; /* length value */
  19758. var code; /* code value */
  19759. var dist; /* distance index */
  19760. var bl_count = new Array(MAX_BITS+1);
  19761. /* number of codes at each bit length for an optimal tree */
  19762. // do check in _tr_init()
  19763. //if (static_init_done) return;
  19764. /* For some embedded targets, global variables are not initialized: */
  19765. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19766. static_l_desc.static_tree = static_ltree;
  19767. static_l_desc.extra_bits = extra_lbits;
  19768. static_d_desc.static_tree = static_dtree;
  19769. static_d_desc.extra_bits = extra_dbits;
  19770. static_bl_desc.extra_bits = extra_blbits;
  19771. #endif*/
  19772. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19773. length = 0;
  19774. for (code = 0; code < LENGTH_CODES-1; code++) {
  19775. base_length[code] = length;
  19776. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19777. _length_code[length++] = code;
  19778. }
  19779. }
  19780. //Assert (length == 256, "tr_static_init: length != 256");
  19781. /* Note that the length 255 (match length 258) can be represented
  19782. * in two different ways: code 284 + 5 bits or code 285, so we
  19783. * overwrite length_code[255] to use the best encoding:
  19784. */
  19785. _length_code[length-1] = code;
  19786. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19787. dist = 0;
  19788. for (code = 0 ; code < 16; code++) {
  19789. base_dist[code] = dist;
  19790. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19791. _dist_code[dist++] = code;
  19792. }
  19793. }
  19794. //Assert (dist == 256, "tr_static_init: dist != 256");
  19795. dist >>= 7; /* from now on, all distances are divided by 128 */
  19796. for (; code < D_CODES; code++) {
  19797. base_dist[code] = dist << 7;
  19798. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19799. _dist_code[256 + dist++] = code;
  19800. }
  19801. }
  19802. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19803. /* Construct the codes of the static literal tree */
  19804. for (bits = 0; bits <= MAX_BITS; bits++) {
  19805. bl_count[bits] = 0;
  19806. }
  19807. n = 0;
  19808. while (n <= 143) {
  19809. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19810. n++;
  19811. bl_count[8]++;
  19812. }
  19813. while (n <= 255) {
  19814. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19815. n++;
  19816. bl_count[9]++;
  19817. }
  19818. while (n <= 279) {
  19819. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19820. n++;
  19821. bl_count[7]++;
  19822. }
  19823. while (n <= 287) {
  19824. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19825. n++;
  19826. bl_count[8]++;
  19827. }
  19828. /* Codes 286 and 287 do not exist, but we must include them in the
  19829. * tree construction to get a canonical Huffman tree (longest code
  19830. * all ones)
  19831. */
  19832. gen_codes(static_ltree, L_CODES+1, bl_count);
  19833. /* The static distance tree is trivial: */
  19834. for (n = 0; n < D_CODES; n++) {
  19835. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19836. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19837. }
  19838. // Now data ready and we can init static trees
  19839. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19840. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19841. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19842. //static_init_done = true;
  19843. }
  19844. /* ===========================================================================
  19845. * Initialize a new block.
  19846. */
  19847. function init_block(s) {
  19848. var n; /* iterates over tree elements */
  19849. /* Initialize the trees. */
  19850. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19851. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19852. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19853. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19854. s.opt_len = s.static_len = 0;
  19855. s.last_lit = s.matches = 0;
  19856. }
  19857. /* ===========================================================================
  19858. * Flush the bit buffer and align the output on a byte boundary
  19859. */
  19860. function bi_windup(s)
  19861. {
  19862. if (s.bi_valid > 8) {
  19863. put_short(s, s.bi_buf);
  19864. } else if (s.bi_valid > 0) {
  19865. //put_byte(s, (Byte)s->bi_buf);
  19866. s.pending_buf[s.pending++] = s.bi_buf;
  19867. }
  19868. s.bi_buf = 0;
  19869. s.bi_valid = 0;
  19870. }
  19871. /* ===========================================================================
  19872. * Copy a stored block, storing first the length and its
  19873. * one's complement if requested.
  19874. */
  19875. function copy_block(s, buf, len, header)
  19876. //DeflateState *s;
  19877. //charf *buf; /* the input data */
  19878. //unsigned len; /* its length */
  19879. //int header; /* true if block header must be written */
  19880. {
  19881. bi_windup(s); /* align on byte boundary */
  19882. if (header) {
  19883. put_short(s, len);
  19884. put_short(s, ~len);
  19885. }
  19886. // while (len--) {
  19887. // put_byte(s, *buf++);
  19888. // }
  19889. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19890. s.pending += len;
  19891. }
  19892. /* ===========================================================================
  19893. * Compares to subtrees, using the tree depth as tie breaker when
  19894. * the subtrees have equal frequency. This minimizes the worst case length.
  19895. */
  19896. function smaller(tree, n, m, depth) {
  19897. var _n2 = n*2;
  19898. var _m2 = m*2;
  19899. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19900. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19901. }
  19902. /* ===========================================================================
  19903. * Restore the heap property by moving down the tree starting at node k,
  19904. * exchanging a node with the smallest of its two sons if necessary, stopping
  19905. * when the heap property is re-established (each father smaller than its
  19906. * two sons).
  19907. */
  19908. function pqdownheap(s, tree, k)
  19909. // deflate_state *s;
  19910. // ct_data *tree; /* the tree to restore */
  19911. // int k; /* node to move down */
  19912. {
  19913. var v = s.heap[k];
  19914. var j = k << 1; /* left son of k */
  19915. while (j <= s.heap_len) {
  19916. /* Set j to the smallest of the two sons: */
  19917. if (j < s.heap_len &&
  19918. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19919. j++;
  19920. }
  19921. /* Exit if v is smaller than both sons */
  19922. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19923. /* Exchange v with the smallest son */
  19924. s.heap[k] = s.heap[j];
  19925. k = j;
  19926. /* And continue down the tree, setting j to the left son of k */
  19927. j <<= 1;
  19928. }
  19929. s.heap[k] = v;
  19930. }
  19931. // inlined manually
  19932. // var SMALLEST = 1;
  19933. /* ===========================================================================
  19934. * Send the block data compressed using the given Huffman trees
  19935. */
  19936. function compress_block(s, ltree, dtree)
  19937. // deflate_state *s;
  19938. // const ct_data *ltree; /* literal tree */
  19939. // const ct_data *dtree; /* distance tree */
  19940. {
  19941. var dist; /* distance of matched string */
  19942. var lc; /* match length or unmatched char (if dist == 0) */
  19943. var lx = 0; /* running index in l_buf */
  19944. var code; /* the code to send */
  19945. var extra; /* number of extra bits to send */
  19946. if (s.last_lit !== 0) {
  19947. do {
  19948. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19949. lc = s.pending_buf[s.l_buf + lx];
  19950. lx++;
  19951. if (dist === 0) {
  19952. send_code(s, lc, ltree); /* send a literal byte */
  19953. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19954. } else {
  19955. /* Here, lc is the match length - MIN_MATCH */
  19956. code = _length_code[lc];
  19957. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19958. extra = extra_lbits[code];
  19959. if (extra !== 0) {
  19960. lc -= base_length[code];
  19961. send_bits(s, lc, extra); /* send the extra length bits */
  19962. }
  19963. dist--; /* dist is now the match distance - 1 */
  19964. code = d_code(dist);
  19965. //Assert (code < D_CODES, "bad d_code");
  19966. send_code(s, code, dtree); /* send the distance code */
  19967. extra = extra_dbits[code];
  19968. if (extra !== 0) {
  19969. dist -= base_dist[code];
  19970. send_bits(s, dist, extra); /* send the extra distance bits */
  19971. }
  19972. } /* literal or match pair ? */
  19973. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19974. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19975. // "pendingBuf overflow");
  19976. } while (lx < s.last_lit);
  19977. }
  19978. send_code(s, END_BLOCK, ltree);
  19979. }
  19980. /* ===========================================================================
  19981. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19982. * Update the total bit length for the current block.
  19983. * IN assertion: the field freq is set for all tree elements.
  19984. * OUT assertions: the fields len and code are set to the optimal bit length
  19985. * and corresponding code. The length opt_len is updated; static_len is
  19986. * also updated if stree is not null. The field max_code is set.
  19987. */
  19988. function build_tree(s, desc)
  19989. // deflate_state *s;
  19990. // tree_desc *desc; /* the tree descriptor */
  19991. {
  19992. var tree = desc.dyn_tree;
  19993. var stree = desc.stat_desc.static_tree;
  19994. var has_stree = desc.stat_desc.has_stree;
  19995. var elems = desc.stat_desc.elems;
  19996. var n, m; /* iterate over heap elements */
  19997. var max_code = -1; /* largest code with non zero frequency */
  19998. var node; /* new node being created */
  19999. /* Construct the initial heap, with least frequent element in
  20000. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  20001. * heap[0] is not used.
  20002. */
  20003. s.heap_len = 0;
  20004. s.heap_max = HEAP_SIZE;
  20005. for (n = 0; n < elems; n++) {
  20006. if (tree[n * 2]/*.Freq*/ !== 0) {
  20007. s.heap[++s.heap_len] = max_code = n;
  20008. s.depth[n] = 0;
  20009. } else {
  20010. tree[n*2 + 1]/*.Len*/ = 0;
  20011. }
  20012. }
  20013. /* The pkzip format requires that at least one distance code exists,
  20014. * and that at least one bit should be sent even if there is only one
  20015. * possible code. So to avoid special checks later on we force at least
  20016. * two codes of non zero frequency.
  20017. */
  20018. while (s.heap_len < 2) {
  20019. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  20020. tree[node * 2]/*.Freq*/ = 1;
  20021. s.depth[node] = 0;
  20022. s.opt_len--;
  20023. if (has_stree) {
  20024. s.static_len -= stree[node*2 + 1]/*.Len*/;
  20025. }
  20026. /* node is 0 or 1 so it does not have extra bits */
  20027. }
  20028. desc.max_code = max_code;
  20029. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  20030. * establish sub-heaps of increasing lengths:
  20031. */
  20032. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  20033. /* Construct the Huffman tree by repeatedly combining the least two
  20034. * frequent nodes.
  20035. */
  20036. node = elems; /* next internal node of the tree */
  20037. do {
  20038. //pqremove(s, tree, n); /* n = node of least frequency */
  20039. /*** pqremove ***/
  20040. n = s.heap[1/*SMALLEST*/];
  20041. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  20042. pqdownheap(s, tree, 1/*SMALLEST*/);
  20043. /***/
  20044. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  20045. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  20046. s.heap[--s.heap_max] = m;
  20047. /* Create a new node father of n and m */
  20048. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  20049. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  20050. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  20051. /* and insert the new node in the heap */
  20052. s.heap[1/*SMALLEST*/] = node++;
  20053. pqdownheap(s, tree, 1/*SMALLEST*/);
  20054. } while (s.heap_len >= 2);
  20055. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  20056. /* At this point, the fields freq and dad are set. We can now
  20057. * generate the bit lengths.
  20058. */
  20059. gen_bitlen(s, desc);
  20060. /* The field len is now set, we can generate the bit codes */
  20061. gen_codes(tree, max_code, s.bl_count);
  20062. }
  20063. /* ===========================================================================
  20064. * Scan a literal or distance tree to determine the frequencies of the codes
  20065. * in the bit length tree.
  20066. */
  20067. function scan_tree(s, tree, max_code)
  20068. // deflate_state *s;
  20069. // ct_data *tree; /* the tree to be scanned */
  20070. // int max_code; /* and its largest code of non zero frequency */
  20071. {
  20072. var n; /* iterates over all tree elements */
  20073. var prevlen = -1; /* last emitted length */
  20074. var curlen; /* length of current code */
  20075. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  20076. var count = 0; /* repeat count of the current code */
  20077. var max_count = 7; /* max repeat count */
  20078. var min_count = 4; /* min repeat count */
  20079. if (nextlen === 0) {
  20080. max_count = 138;
  20081. min_count = 3;
  20082. }
  20083. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  20084. for (n = 0; n <= max_code; n++) {
  20085. curlen = nextlen;
  20086. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  20087. if (++count < max_count && curlen === nextlen) {
  20088. continue;
  20089. } else if (count < min_count) {
  20090. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  20091. } else if (curlen !== 0) {
  20092. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  20093. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  20094. } else if (count <= 10) {
  20095. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  20096. } else {
  20097. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  20098. }
  20099. count = 0;
  20100. prevlen = curlen;
  20101. if (nextlen === 0) {
  20102. max_count = 138;
  20103. min_count = 3;
  20104. } else if (curlen === nextlen) {
  20105. max_count = 6;
  20106. min_count = 3;
  20107. } else {
  20108. max_count = 7;
  20109. min_count = 4;
  20110. }
  20111. }
  20112. }
  20113. /* ===========================================================================
  20114. * Send a literal or distance tree in compressed form, using the codes in
  20115. * bl_tree.
  20116. */
  20117. function send_tree(s, tree, max_code)
  20118. // deflate_state *s;
  20119. // ct_data *tree; /* the tree to be scanned */
  20120. // int max_code; /* and its largest code of non zero frequency */
  20121. {
  20122. var n; /* iterates over all tree elements */
  20123. var prevlen = -1; /* last emitted length */
  20124. var curlen; /* length of current code */
  20125. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  20126. var count = 0; /* repeat count of the current code */
  20127. var max_count = 7; /* max repeat count */
  20128. var min_count = 4; /* min repeat count */
  20129. /* tree[max_code+1].Len = -1; */ /* guard already set */
  20130. if (nextlen === 0) {
  20131. max_count = 138;
  20132. min_count = 3;
  20133. }
  20134. for (n = 0; n <= max_code; n++) {
  20135. curlen = nextlen;
  20136. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  20137. if (++count < max_count && curlen === nextlen) {
  20138. continue;
  20139. } else if (count < min_count) {
  20140. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  20141. } else if (curlen !== 0) {
  20142. if (curlen !== prevlen) {
  20143. send_code(s, curlen, s.bl_tree);
  20144. count--;
  20145. }
  20146. //Assert(count >= 3 && count <= 6, " 3_6?");
  20147. send_code(s, REP_3_6, s.bl_tree);
  20148. send_bits(s, count-3, 2);
  20149. } else if (count <= 10) {
  20150. send_code(s, REPZ_3_10, s.bl_tree);
  20151. send_bits(s, count-3, 3);
  20152. } else {
  20153. send_code(s, REPZ_11_138, s.bl_tree);
  20154. send_bits(s, count-11, 7);
  20155. }
  20156. count = 0;
  20157. prevlen = curlen;
  20158. if (nextlen === 0) {
  20159. max_count = 138;
  20160. min_count = 3;
  20161. } else if (curlen === nextlen) {
  20162. max_count = 6;
  20163. min_count = 3;
  20164. } else {
  20165. max_count = 7;
  20166. min_count = 4;
  20167. }
  20168. }
  20169. }
  20170. /* ===========================================================================
  20171. * Construct the Huffman tree for the bit lengths and return the index in
  20172. * bl_order of the last bit length code to send.
  20173. */
  20174. function build_bl_tree(s) {
  20175. var max_blindex; /* index of last bit length code of non zero freq */
  20176. /* Determine the bit length frequencies for literal and distance trees */
  20177. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  20178. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  20179. /* Build the bit length tree: */
  20180. build_tree(s, s.bl_desc);
  20181. /* opt_len now includes the length of the tree representations, except
  20182. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  20183. */
  20184. /* Determine the number of bit length codes to send. The pkzip format
  20185. * requires that at least 4 bit length codes be sent. (appnote.txt says
  20186. * 3 but the actual value used is 4.)
  20187. */
  20188. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  20189. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  20190. break;
  20191. }
  20192. }
  20193. /* Update opt_len to include the bit length tree and counts */
  20194. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  20195. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  20196. // s->opt_len, s->static_len));
  20197. return max_blindex;
  20198. }
  20199. /* ===========================================================================
  20200. * Send the header for a block using dynamic Huffman trees: the counts, the
  20201. * lengths of the bit length codes, the literal tree and the distance tree.
  20202. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  20203. */
  20204. function send_all_trees(s, lcodes, dcodes, blcodes)
  20205. // deflate_state *s;
  20206. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  20207. {
  20208. var rank; /* index in bl_order */
  20209. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  20210. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  20211. // "too many codes");
  20212. //Tracev((stderr, "\nbl counts: "));
  20213. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  20214. send_bits(s, dcodes-1, 5);
  20215. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  20216. for (rank = 0; rank < blcodes; rank++) {
  20217. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  20218. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  20219. }
  20220. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  20221. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  20222. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  20223. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  20224. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  20225. }
  20226. /* ===========================================================================
  20227. * Check if the data type is TEXT or BINARY, using the following algorithm:
  20228. * - TEXT if the two conditions below are satisfied:
  20229. * a) There are no non-portable control characters belonging to the
  20230. * "black list" (0..6, 14..25, 28..31).
  20231. * b) There is at least one printable character belonging to the
  20232. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  20233. * - BINARY otherwise.
  20234. * - The following partially-portable control characters form a
  20235. * "gray list" that is ignored in this detection algorithm:
  20236. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  20237. * IN assertion: the fields Freq of dyn_ltree are set.
  20238. */
  20239. function detect_data_type(s) {
  20240. /* black_mask is the bit mask of black-listed bytes
  20241. * set bits 0..6, 14..25, and 28..31
  20242. * 0xf3ffc07f = binary 11110011111111111100000001111111
  20243. */
  20244. var black_mask = 0xf3ffc07f;
  20245. var n;
  20246. /* Check for non-textual ("black-listed") bytes. */
  20247. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  20248. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  20249. return Z_BINARY;
  20250. }
  20251. }
  20252. /* Check for textual ("white-listed") bytes. */
  20253. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  20254. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  20255. return Z_TEXT;
  20256. }
  20257. for (n = 32; n < LITERALS; n++) {
  20258. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  20259. return Z_TEXT;
  20260. }
  20261. }
  20262. /* There are no "black-listed" or "white-listed" bytes:
  20263. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  20264. */
  20265. return Z_BINARY;
  20266. }
  20267. var static_init_done = false;
  20268. /* ===========================================================================
  20269. * Initialize the tree data structures for a new zlib stream.
  20270. */
  20271. function _tr_init(s)
  20272. {
  20273. if (!static_init_done) {
  20274. tr_static_init();
  20275. static_init_done = true;
  20276. }
  20277. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  20278. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  20279. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  20280. s.bi_buf = 0;
  20281. s.bi_valid = 0;
  20282. /* Initialize the first block of the first file: */
  20283. init_block(s);
  20284. }
  20285. /* ===========================================================================
  20286. * Send a stored block
  20287. */
  20288. function _tr_stored_block(s, buf, stored_len, last)
  20289. //DeflateState *s;
  20290. //charf *buf; /* input block */
  20291. //ulg stored_len; /* length of input block */
  20292. //int last; /* one if this is the last block for a file */
  20293. {
  20294. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  20295. copy_block(s, buf, stored_len, true); /* with header */
  20296. }
  20297. /* ===========================================================================
  20298. * Send one empty static block to give enough lookahead for inflate.
  20299. * This takes 10 bits, of which 7 may remain in the bit buffer.
  20300. */
  20301. function _tr_align(s) {
  20302. send_bits(s, STATIC_TREES<<1, 3);
  20303. send_code(s, END_BLOCK, static_ltree);
  20304. bi_flush(s);
  20305. }
  20306. /* ===========================================================================
  20307. * Determine the best encoding for the current block: dynamic trees, static
  20308. * trees or store, and output the encoded block to the zip file.
  20309. */
  20310. function _tr_flush_block(s, buf, stored_len, last)
  20311. //DeflateState *s;
  20312. //charf *buf; /* input block, or NULL if too old */
  20313. //ulg stored_len; /* length of input block */
  20314. //int last; /* one if this is the last block for a file */
  20315. {
  20316. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  20317. var max_blindex = 0; /* index of last bit length code of non zero freq */
  20318. /* Build the Huffman trees unless a stored block is forced */
  20319. if (s.level > 0) {
  20320. /* Check if the file is binary or text */
  20321. if (s.strm.data_type === Z_UNKNOWN) {
  20322. s.strm.data_type = detect_data_type(s);
  20323. }
  20324. /* Construct the literal and distance trees */
  20325. build_tree(s, s.l_desc);
  20326. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  20327. // s->static_len));
  20328. build_tree(s, s.d_desc);
  20329. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20330. // s->static_len));
  20331. /* At this point, opt_len and static_len are the total bit lengths of
  20332. * the compressed block data, excluding the tree representations.
  20333. */
  20334. /* Build the bit length tree for the above two trees, and get the index
  20335. * in bl_order of the last bit length code to send.
  20336. */
  20337. max_blindex = build_bl_tree(s);
  20338. /* Determine the best encoding. Compute the block lengths in bytes. */
  20339. opt_lenb = (s.opt_len+3+7) >>> 3;
  20340. static_lenb = (s.static_len+3+7) >>> 3;
  20341. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20342. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20343. // s->last_lit));
  20344. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20345. } else {
  20346. // Assert(buf != (char*)0, "lost buf");
  20347. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20348. }
  20349. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  20350. /* 4: two words for the lengths */
  20351. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20352. * Otherwise we can't have processed more than WSIZE input bytes since
  20353. * the last block flush, because compression would have been
  20354. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20355. * transform a block into a stored block.
  20356. */
  20357. _tr_stored_block(s, buf, stored_len, last);
  20358. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20359. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  20360. compress_block(s, static_ltree, static_dtree);
  20361. } else {
  20362. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  20363. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  20364. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20365. }
  20366. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20367. /* The above check is made mod 2^32, for files larger than 512 MB
  20368. * and uLong implemented on 32 bits.
  20369. */
  20370. init_block(s);
  20371. if (last) {
  20372. bi_windup(s);
  20373. }
  20374. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20375. // s->compressed_len-7*last));
  20376. }
  20377. /* ===========================================================================
  20378. * Save the match info and tally the frequency counts. Return true if
  20379. * the current block must be flushed.
  20380. */
  20381. function _tr_tally(s, dist, lc)
  20382. // deflate_state *s;
  20383. // unsigned dist; /* distance of matched string */
  20384. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20385. {
  20386. //var out_length, in_length, dcode;
  20387. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20388. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20389. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20390. s.last_lit++;
  20391. if (dist === 0) {
  20392. /* lc is the unmatched char */
  20393. s.dyn_ltree[lc*2]/*.Freq*/++;
  20394. } else {
  20395. s.matches++;
  20396. /* Here, lc is the match length - MIN_MATCH */
  20397. dist--; /* dist = match distance - 1 */
  20398. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20399. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20400. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20401. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  20402. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20403. }
  20404. // (!) This block is disabled in zlib defailts,
  20405. // don't enable it for binary compatibility
  20406. //#ifdef TRUNCATE_BLOCK
  20407. // /* Try to guess if it is profitable to stop the current block here */
  20408. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20409. // /* Compute an upper bound for the compressed length */
  20410. // out_length = s.last_lit*8;
  20411. // in_length = s.strstart - s.block_start;
  20412. //
  20413. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20414. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20415. // }
  20416. // out_length >>>= 3;
  20417. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20418. // // s->last_lit, in_length, out_length,
  20419. // // 100L - out_length*100L/in_length));
  20420. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20421. // return true;
  20422. // }
  20423. // }
  20424. //#endif
  20425. return (s.last_lit === s.lit_bufsize-1);
  20426. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20427. * on 16 bit machines and because stored blocks are restricted to
  20428. * 64K-1 bytes.
  20429. */
  20430. }
  20431. exports._tr_init = _tr_init;
  20432. exports._tr_stored_block = _tr_stored_block;
  20433. exports._tr_flush_block = _tr_flush_block;
  20434. exports._tr_tally = _tr_tally;
  20435. exports._tr_align = _tr_align;
  20436. },{"../utils/common":127}],139:[function(require,module,exports){
  20437. 'use strict';
  20438. function ZStream() {
  20439. /* next input byte */
  20440. this.input = null; // JS specific, because we have no pointers
  20441. this.next_in = 0;
  20442. /* number of bytes available at input */
  20443. this.avail_in = 0;
  20444. /* total number of input bytes read so far */
  20445. this.total_in = 0;
  20446. /* next output byte should be put there */
  20447. this.output = null; // JS specific, because we have no pointers
  20448. this.next_out = 0;
  20449. /* remaining free space at output */
  20450. this.avail_out = 0;
  20451. /* total number of bytes output so far */
  20452. this.total_out = 0;
  20453. /* last error message, NULL if no error */
  20454. this.msg = ''/*Z_NULL*/;
  20455. /* not visible by applications */
  20456. this.state = null;
  20457. /* best guess about the data type: binary or text */
  20458. this.data_type = 2/*Z_UNKNOWN*/;
  20459. /* adler32 value of the uncompressed data */
  20460. this.adler = 0;
  20461. }
  20462. module.exports = ZStream;
  20463. },{}],140:[function(require,module,exports){
  20464. exports.Parser = require("./lib/parser").Parser;
  20465. exports.rules = require("./lib/rules");
  20466. exports.errors = require("./lib/errors");
  20467. exports.results = require("./lib/parsing-results");
  20468. exports.StringSource = require("./lib/StringSource");
  20469. exports.Token = require("./lib/Token");
  20470. exports.bottomUp = require("./lib/bottom-up");
  20471. exports.RegexTokeniser = require("./lib/regex-tokeniser").RegexTokeniser;
  20472. exports.rule = function(ruleBuilder) {
  20473. var rule;
  20474. return function(input) {
  20475. if (!rule) {
  20476. rule = ruleBuilder();
  20477. }
  20478. return rule(input);
  20479. };
  20480. };
  20481. },{"./lib/StringSource":141,"./lib/Token":142,"./lib/bottom-up":144,"./lib/errors":145,"./lib/parser":147,"./lib/parsing-results":148,"./lib/regex-tokeniser":149,"./lib/rules":150}],141:[function(require,module,exports){
  20482. var util = require("util");
  20483. var StringSource = module.exports = function(string, description) {
  20484. var self = {
  20485. asString: function() {
  20486. return string;
  20487. },
  20488. range: function(startIndex, endIndex) {
  20489. return new StringSourceRange(string, description, startIndex, endIndex);
  20490. }
  20491. };
  20492. return self;
  20493. };
  20494. var StringSourceRange = function(string, description, startIndex, endIndex) {
  20495. this._string = string;
  20496. this._description = description;
  20497. this._startIndex = startIndex;
  20498. this._endIndex = endIndex;
  20499. };
  20500. StringSourceRange.prototype.to = function(otherRange) {
  20501. // TODO: Assert that tokens are the same across both iterators
  20502. return new StringSourceRange(this._string, this._description, this._startIndex, otherRange._endIndex);
  20503. };
  20504. StringSourceRange.prototype.describe = function() {
  20505. var position = this._position();
  20506. var description = this._description ? this._description + "\n" : "";
  20507. return util.format("%sLine number: %s\nCharacter number: %s",
  20508. description, position.lineNumber, position.characterNumber);
  20509. };
  20510. StringSourceRange.prototype.lineNumber = function() {
  20511. return this._position().lineNumber;
  20512. };
  20513. StringSourceRange.prototype.characterNumber = function() {
  20514. return this._position().characterNumber;
  20515. };
  20516. StringSourceRange.prototype._position = function() {
  20517. var self = this;
  20518. var index = 0;
  20519. var nextNewLine = function() {
  20520. return self._string.indexOf("\n", index);
  20521. };
  20522. var lineNumber = 1;
  20523. while (nextNewLine() !== -1 && nextNewLine() < this._startIndex) {
  20524. index = nextNewLine() + 1;
  20525. lineNumber += 1;
  20526. }
  20527. var characterNumber = this._startIndex - index + 1;
  20528. return {lineNumber: lineNumber, characterNumber: characterNumber};
  20529. };
  20530. },{"util":100}],142:[function(require,module,exports){
  20531. module.exports = function(name, value, source) {
  20532. this.name = name;
  20533. this.value = value;
  20534. if (source) {
  20535. this.source = source;
  20536. }
  20537. };
  20538. },{}],143:[function(require,module,exports){
  20539. var TokenIterator = module.exports = function(tokens, startIndex) {
  20540. this._tokens = tokens;
  20541. this._startIndex = startIndex || 0;
  20542. };
  20543. TokenIterator.prototype.head = function() {
  20544. return this._tokens[this._startIndex];
  20545. };
  20546. TokenIterator.prototype.tail = function(startIndex) {
  20547. return new TokenIterator(this._tokens, this._startIndex + 1);
  20548. };
  20549. TokenIterator.prototype.toArray = function() {
  20550. return this._tokens.slice(this._startIndex);
  20551. };
  20552. TokenIterator.prototype.end = function() {
  20553. return this._tokens[this._tokens.length - 1];
  20554. };
  20555. // TODO: doesn't need to be a method, can be a separate function,
  20556. // which simplifies implementation of the TokenIterator interface
  20557. TokenIterator.prototype.to = function(end) {
  20558. var start = this.head().source;
  20559. var endToken = end.head() || end.end();
  20560. return start.to(endToken.source);
  20561. };
  20562. },{}],144:[function(require,module,exports){
  20563. var rules = require("./rules");
  20564. var results = require("./parsing-results");
  20565. exports.parser = function(name, prefixRules, infixRuleBuilders) {
  20566. var self = {
  20567. rule: rule,
  20568. leftAssociative: leftAssociative,
  20569. rightAssociative: rightAssociative
  20570. };
  20571. var infixRules = new InfixRules(infixRuleBuilders.map(createInfixRule));
  20572. var prefixRule = rules.firstOf(name, prefixRules);
  20573. function createInfixRule(infixRuleBuilder) {
  20574. return {
  20575. name: infixRuleBuilder.name,
  20576. rule: lazyRule(infixRuleBuilder.ruleBuilder.bind(null, self))
  20577. };
  20578. }
  20579. function rule() {
  20580. return createRule(infixRules);
  20581. }
  20582. function leftAssociative(name) {
  20583. return createRule(infixRules.untilExclusive(name));
  20584. }
  20585. function rightAssociative(name) {
  20586. return createRule(infixRules.untilInclusive(name));
  20587. }
  20588. function createRule(infixRules) {
  20589. return apply.bind(null, infixRules);
  20590. }
  20591. function apply(infixRules, tokens) {
  20592. var leftResult = prefixRule(tokens);
  20593. if (leftResult.isSuccess()) {
  20594. return infixRules.apply(leftResult);
  20595. } else {
  20596. return leftResult;
  20597. }
  20598. }
  20599. return self;
  20600. };
  20601. function InfixRules(infixRules) {
  20602. function untilExclusive(name) {
  20603. return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name)));
  20604. }
  20605. function untilInclusive(name) {
  20606. return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name) + 1));
  20607. }
  20608. function ruleNames() {
  20609. return infixRules.map(function(rule) {
  20610. return rule.name;
  20611. });
  20612. }
  20613. function apply(leftResult) {
  20614. var currentResult;
  20615. var source;
  20616. while (true) {
  20617. currentResult = applyToTokens(leftResult.remaining());
  20618. if (currentResult.isSuccess()) {
  20619. source = leftResult.source().to(currentResult.source());
  20620. leftResult = results.success(
  20621. currentResult.value()(leftResult.value(), source),
  20622. currentResult.remaining(),
  20623. source
  20624. )
  20625. } else if (currentResult.isFailure()) {
  20626. return leftResult;
  20627. } else {
  20628. return currentResult;
  20629. }
  20630. }
  20631. }
  20632. function applyToTokens(tokens) {
  20633. return rules.firstOf("infix", infixRules.map(function(infix) {
  20634. return infix.rule;
  20635. }))(tokens);
  20636. }
  20637. return {
  20638. apply: apply,
  20639. untilExclusive: untilExclusive,
  20640. untilInclusive: untilInclusive
  20641. }
  20642. }
  20643. exports.infix = function(name, ruleBuilder) {
  20644. function map(func) {
  20645. return exports.infix(name, function(parser) {
  20646. var rule = ruleBuilder(parser);
  20647. return function(tokens) {
  20648. var result = rule(tokens);
  20649. return result.map(function(right) {
  20650. return function(left, source) {
  20651. return func(left, right, source);
  20652. };
  20653. });
  20654. };
  20655. });
  20656. }
  20657. return {
  20658. name: name,
  20659. ruleBuilder: ruleBuilder,
  20660. map: map
  20661. };
  20662. }
  20663. // TODO: move into a sensible place and remove duplication
  20664. var lazyRule = function(ruleBuilder) {
  20665. var rule;
  20666. return function(input) {
  20667. if (!rule) {
  20668. rule = ruleBuilder();
  20669. }
  20670. return rule(input);
  20671. };
  20672. };
  20673. },{"./parsing-results":148,"./rules":150}],145:[function(require,module,exports){
  20674. exports.error = function(options) {
  20675. return new Error(options);
  20676. };
  20677. var Error = function(options) {
  20678. this.expected = options.expected;
  20679. this.actual = options.actual;
  20680. this._location = options.location;
  20681. };
  20682. Error.prototype.describe = function() {
  20683. var locationDescription = this._location ? this._location.describe() + ":\n" : "";
  20684. return locationDescription + "Expected " + this.expected + "\nbut got " + this.actual;
  20685. };
  20686. Error.prototype.lineNumber = function() {
  20687. return this._location.lineNumber();
  20688. };
  20689. Error.prototype.characterNumber = function() {
  20690. return this._location.characterNumber();
  20691. };
  20692. },{}],146:[function(require,module,exports){
  20693. var fromArray = exports.fromArray = function(array) {
  20694. var index = 0;
  20695. var hasNext = function() {
  20696. return index < array.length;
  20697. };
  20698. return new LazyIterator({
  20699. hasNext: hasNext,
  20700. next: function() {
  20701. if (!hasNext()) {
  20702. throw new Error("No more elements");
  20703. } else {
  20704. return array[index++];
  20705. }
  20706. }
  20707. });
  20708. };
  20709. var LazyIterator = function(iterator) {
  20710. this._iterator = iterator;
  20711. };
  20712. LazyIterator.prototype.map = function(func) {
  20713. var iterator = this._iterator;
  20714. return new LazyIterator({
  20715. hasNext: function() {
  20716. return iterator.hasNext();
  20717. },
  20718. next: function() {
  20719. return func(iterator.next());
  20720. }
  20721. });
  20722. };
  20723. LazyIterator.prototype.filter = function(condition) {
  20724. var iterator = this._iterator;
  20725. var moved = false;
  20726. var hasNext = false;
  20727. var next;
  20728. var moveIfNecessary = function() {
  20729. if (moved) {
  20730. return;
  20731. }
  20732. moved = true;
  20733. hasNext = false;
  20734. while (iterator.hasNext() && !hasNext) {
  20735. next = iterator.next();
  20736. hasNext = condition(next);
  20737. }
  20738. };
  20739. return new LazyIterator({
  20740. hasNext: function() {
  20741. moveIfNecessary();
  20742. return hasNext;
  20743. },
  20744. next: function() {
  20745. moveIfNecessary();
  20746. var toReturn = next;
  20747. moved = false;
  20748. return toReturn;
  20749. }
  20750. });
  20751. };
  20752. LazyIterator.prototype.first = function() {
  20753. var iterator = this._iterator;
  20754. if (this._iterator.hasNext()) {
  20755. return iterator.next();
  20756. } else {
  20757. return null;
  20758. }
  20759. };
  20760. LazyIterator.prototype.toArray = function() {
  20761. var result = [];
  20762. while (this._iterator.hasNext()) {
  20763. result.push(this._iterator.next());
  20764. }
  20765. return result;
  20766. };
  20767. },{}],147:[function(require,module,exports){
  20768. var TokenIterator = require("./TokenIterator");
  20769. exports.Parser = function(options) {
  20770. var parseTokens = function(parser, tokens) {
  20771. return parser(new TokenIterator(tokens));
  20772. };
  20773. return {
  20774. parseTokens: parseTokens
  20775. };
  20776. };
  20777. },{"./TokenIterator":143}],148:[function(require,module,exports){
  20778. module.exports = {
  20779. failure: function(errors, remaining) {
  20780. if (errors.length < 1) {
  20781. throw new Error("Failure must have errors");
  20782. }
  20783. return new Result({
  20784. status: "failure",
  20785. remaining: remaining,
  20786. errors: errors
  20787. });
  20788. },
  20789. error: function(errors, remaining) {
  20790. if (errors.length < 1) {
  20791. throw new Error("Failure must have errors");
  20792. }
  20793. return new Result({
  20794. status: "error",
  20795. remaining: remaining,
  20796. errors: errors
  20797. });
  20798. },
  20799. success: function(value, remaining, source) {
  20800. return new Result({
  20801. status: "success",
  20802. value: value,
  20803. source: source,
  20804. remaining: remaining,
  20805. errors: []
  20806. });
  20807. },
  20808. cut: function(remaining) {
  20809. return new Result({
  20810. status: "cut",
  20811. remaining: remaining,
  20812. errors: []
  20813. });
  20814. }
  20815. };
  20816. var Result = function(options) {
  20817. this._value = options.value;
  20818. this._status = options.status;
  20819. this._hasValue = options.value !== undefined;
  20820. this._remaining = options.remaining;
  20821. this._source = options.source;
  20822. this._errors = options.errors;
  20823. };
  20824. Result.prototype.map = function(func) {
  20825. if (this._hasValue) {
  20826. return new Result({
  20827. value: func(this._value, this._source),
  20828. status: this._status,
  20829. remaining: this._remaining,
  20830. source: this._source,
  20831. errors: this._errors
  20832. });
  20833. } else {
  20834. return this;
  20835. }
  20836. };
  20837. Result.prototype.changeRemaining = function(remaining) {
  20838. return new Result({
  20839. value: this._value,
  20840. status: this._status,
  20841. remaining: remaining,
  20842. source: this._source,
  20843. errors: this._errors
  20844. });
  20845. };
  20846. Result.prototype.isSuccess = function() {
  20847. return this._status === "success" || this._status === "cut";
  20848. };
  20849. Result.prototype.isFailure = function() {
  20850. return this._status === "failure";
  20851. };
  20852. Result.prototype.isError = function() {
  20853. return this._status === "error";
  20854. };
  20855. Result.prototype.isCut = function() {
  20856. return this._status === "cut";
  20857. };
  20858. Result.prototype.value = function() {
  20859. return this._value;
  20860. };
  20861. Result.prototype.remaining = function() {
  20862. return this._remaining;
  20863. };
  20864. Result.prototype.source = function() {
  20865. return this._source;
  20866. };
  20867. Result.prototype.errors = function() {
  20868. return this._errors;
  20869. };
  20870. },{}],149:[function(require,module,exports){
  20871. var Token = require("./Token");
  20872. var StringSource = require("./StringSource");
  20873. exports.RegexTokeniser = RegexTokeniser;
  20874. function RegexTokeniser(rules) {
  20875. rules = rules.map(function(rule) {
  20876. return {
  20877. name: rule.name,
  20878. regex: new RegExp(rule.regex.source, "g")
  20879. };
  20880. });
  20881. function tokenise(input, description) {
  20882. var source = new StringSource(input, description);
  20883. var index = 0;
  20884. var tokens = [];
  20885. while (index < input.length) {
  20886. var result = readNextToken(input, index, source);
  20887. index = result.endIndex;
  20888. tokens.push(result.token);
  20889. }
  20890. tokens.push(endToken(input, source));
  20891. return tokens;
  20892. }
  20893. function readNextToken(string, startIndex, source) {
  20894. for (var i = 0; i < rules.length; i++) {
  20895. var regex = rules[i].regex;
  20896. regex.lastIndex = startIndex;
  20897. var result = regex.exec(string);
  20898. if (result) {
  20899. var endIndex = startIndex + result[0].length;
  20900. if (result.index === startIndex && endIndex > startIndex) {
  20901. var value = result[1];
  20902. var token = new Token(
  20903. rules[i].name,
  20904. value,
  20905. source.range(startIndex, endIndex)
  20906. );
  20907. return {token: token, endIndex: endIndex};
  20908. }
  20909. }
  20910. }
  20911. var endIndex = startIndex + 1;
  20912. var token = new Token(
  20913. "unrecognisedCharacter",
  20914. string.substring(startIndex, endIndex),
  20915. source.range(startIndex, endIndex)
  20916. );
  20917. return {token: token, endIndex: endIndex};
  20918. }
  20919. function endToken(input, source) {
  20920. return new Token(
  20921. "end",
  20922. null,
  20923. source.range(input.length, input.length)
  20924. );
  20925. }
  20926. return {
  20927. tokenise: tokenise
  20928. }
  20929. }
  20930. },{"./StringSource":141,"./Token":142}],150:[function(require,module,exports){
  20931. var _ = require("underscore");
  20932. var options = require("option");
  20933. var results = require("./parsing-results");
  20934. var errors = require("./errors");
  20935. var lazyIterators = require("./lazy-iterators");
  20936. exports.token = function(tokenType, value) {
  20937. var matchValue = value !== undefined;
  20938. return function(input) {
  20939. var token = input.head();
  20940. if (token && token.name === tokenType && (!matchValue || token.value === value)) {
  20941. return results.success(token.value, input.tail(), token.source);
  20942. } else {
  20943. var expected = describeToken({name: tokenType, value: value});
  20944. return describeTokenMismatch(input, expected);
  20945. }
  20946. };
  20947. };
  20948. exports.tokenOfType = function(tokenType) {
  20949. return exports.token(tokenType);
  20950. };
  20951. exports.firstOf = function(name, parsers) {
  20952. if (!_.isArray(parsers)) {
  20953. parsers = Array.prototype.slice.call(arguments, 1);
  20954. }
  20955. return function(input) {
  20956. return lazyIterators
  20957. .fromArray(parsers)
  20958. .map(function(parser) {
  20959. return parser(input);
  20960. })
  20961. .filter(function(result) {
  20962. return result.isSuccess() || result.isError();
  20963. })
  20964. .first() || describeTokenMismatch(input, name);
  20965. };
  20966. };
  20967. exports.then = function(parser, func) {
  20968. return function(input) {
  20969. var result = parser(input);
  20970. if (!result.map) {
  20971. console.log(result);
  20972. }
  20973. return result.map(func);
  20974. };
  20975. };
  20976. exports.sequence = function() {
  20977. var parsers = Array.prototype.slice.call(arguments, 0);
  20978. var rule = function(input) {
  20979. var result = _.foldl(parsers, function(memo, parser) {
  20980. var result = memo.result;
  20981. var hasCut = memo.hasCut;
  20982. if (!result.isSuccess()) {
  20983. return {result: result, hasCut: hasCut};
  20984. }
  20985. var subResult = parser(result.remaining());
  20986. if (subResult.isCut()) {
  20987. return {result: result, hasCut: true};
  20988. } else if (subResult.isSuccess()) {
  20989. var values;
  20990. if (parser.isCaptured) {
  20991. values = result.value().withValue(parser, subResult.value());
  20992. } else {
  20993. values = result.value();
  20994. }
  20995. var remaining = subResult.remaining();
  20996. var source = input.to(remaining);
  20997. return {
  20998. result: results.success(values, remaining, source),
  20999. hasCut: hasCut
  21000. };
  21001. } else if (hasCut) {
  21002. return {result: results.error(subResult.errors(), subResult.remaining()), hasCut: hasCut};
  21003. } else {
  21004. return {result: subResult, hasCut: hasCut};
  21005. }
  21006. }, {result: results.success(new SequenceValues(), input), hasCut: false}).result;
  21007. var source = input.to(result.remaining());
  21008. return result.map(function(values) {
  21009. return values.withValue(exports.sequence.source, source);
  21010. });
  21011. };
  21012. rule.head = function() {
  21013. var firstCapture = _.find(parsers, isCapturedRule);
  21014. return exports.then(
  21015. rule,
  21016. exports.sequence.extract(firstCapture)
  21017. );
  21018. };
  21019. rule.map = function(func) {
  21020. return exports.then(
  21021. rule,
  21022. function(result) {
  21023. return func.apply(this, result.toArray());
  21024. }
  21025. );
  21026. };
  21027. function isCapturedRule(subRule) {
  21028. return subRule.isCaptured;
  21029. }
  21030. return rule;
  21031. };
  21032. var SequenceValues = function(values, valuesArray) {
  21033. this._values = values || {};
  21034. this._valuesArray = valuesArray || [];
  21035. };
  21036. SequenceValues.prototype.withValue = function(rule, value) {
  21037. if (rule.captureName && rule.captureName in this._values) {
  21038. throw new Error("Cannot add second value for capture \"" + rule.captureName + "\"");
  21039. } else {
  21040. var newValues = _.clone(this._values);
  21041. newValues[rule.captureName] = value;
  21042. var newValuesArray = this._valuesArray.concat([value]);
  21043. return new SequenceValues(newValues, newValuesArray);
  21044. }
  21045. };
  21046. SequenceValues.prototype.get = function(rule) {
  21047. if (rule.captureName in this._values) {
  21048. return this._values[rule.captureName];
  21049. } else {
  21050. throw new Error("No value for capture \"" + rule.captureName + "\"");
  21051. }
  21052. };
  21053. SequenceValues.prototype.toArray = function() {
  21054. return this._valuesArray;
  21055. };
  21056. exports.sequence.capture = function(rule, name) {
  21057. var captureRule = function() {
  21058. return rule.apply(this, arguments);
  21059. };
  21060. captureRule.captureName = name;
  21061. captureRule.isCaptured = true;
  21062. return captureRule;
  21063. };
  21064. exports.sequence.extract = function(rule) {
  21065. return function(result) {
  21066. return result.get(rule);
  21067. };
  21068. };
  21069. exports.sequence.applyValues = function(func) {
  21070. // TODO: check captureName doesn't conflict with source or other captures
  21071. var rules = Array.prototype.slice.call(arguments, 1);
  21072. return function(result) {
  21073. var values = rules.map(function(rule) {
  21074. return result.get(rule);
  21075. });
  21076. return func.apply(this, values);
  21077. };
  21078. };
  21079. exports.sequence.source = {
  21080. captureName: "☃source☃"
  21081. };
  21082. exports.sequence.cut = function() {
  21083. return function(input) {
  21084. return results.cut(input);
  21085. };
  21086. };
  21087. exports.optional = function(rule) {
  21088. return function(input) {
  21089. var result = rule(input);
  21090. if (result.isSuccess()) {
  21091. return result.map(options.some);
  21092. } else if (result.isFailure()) {
  21093. return results.success(options.none, input);
  21094. } else {
  21095. return result;
  21096. }
  21097. };
  21098. };
  21099. exports.zeroOrMoreWithSeparator = function(rule, separator) {
  21100. return repeatedWithSeparator(rule, separator, false);
  21101. };
  21102. exports.oneOrMoreWithSeparator = function(rule, separator) {
  21103. return repeatedWithSeparator(rule, separator, true);
  21104. };
  21105. var zeroOrMore = exports.zeroOrMore = function(rule) {
  21106. return function(input) {
  21107. var values = [];
  21108. var result;
  21109. while ((result = rule(input)) && result.isSuccess()) {
  21110. input = result.remaining();
  21111. values.push(result.value());
  21112. }
  21113. if (result.isError()) {
  21114. return result;
  21115. } else {
  21116. return results.success(values, input);
  21117. }
  21118. };
  21119. };
  21120. exports.oneOrMore = function(rule) {
  21121. return exports.oneOrMoreWithSeparator(rule, noOpRule);
  21122. };
  21123. function noOpRule(input) {
  21124. return results.success(null, input);
  21125. }
  21126. var repeatedWithSeparator = function(rule, separator, isOneOrMore) {
  21127. return function(input) {
  21128. var result = rule(input);
  21129. if (result.isSuccess()) {
  21130. var mainRule = exports.sequence.capture(rule, "main");
  21131. var remainingRule = zeroOrMore(exports.then(
  21132. exports.sequence(separator, mainRule),
  21133. exports.sequence.extract(mainRule)
  21134. ));
  21135. var remainingResult = remainingRule(result.remaining());
  21136. return results.success([result.value()].concat(remainingResult.value()), remainingResult.remaining());
  21137. } else if (isOneOrMore || result.isError()) {
  21138. return result;
  21139. } else {
  21140. return results.success([], input);
  21141. }
  21142. };
  21143. };
  21144. exports.leftAssociative = function(leftRule, rightRule, func) {
  21145. var rights;
  21146. if (func) {
  21147. rights = [{func: func, rule: rightRule}];
  21148. } else {
  21149. rights = rightRule;
  21150. }
  21151. rights = rights.map(function(right) {
  21152. return exports.then(right.rule, function(rightValue) {
  21153. return function(leftValue, source) {
  21154. return right.func(leftValue, rightValue, source);
  21155. };
  21156. });
  21157. });
  21158. var repeatedRule = exports.firstOf.apply(null, ["rules"].concat(rights));
  21159. return function(input) {
  21160. var start = input;
  21161. var leftResult = leftRule(input);
  21162. if (!leftResult.isSuccess()) {
  21163. return leftResult;
  21164. }
  21165. var repeatedResult = repeatedRule(leftResult.remaining());
  21166. while (repeatedResult.isSuccess()) {
  21167. var remaining = repeatedResult.remaining();
  21168. var source = start.to(repeatedResult.remaining());
  21169. var right = repeatedResult.value();
  21170. leftResult = results.success(
  21171. right(leftResult.value(), source),
  21172. remaining,
  21173. source
  21174. );
  21175. repeatedResult = repeatedRule(leftResult.remaining());
  21176. }
  21177. if (repeatedResult.isError()) {
  21178. return repeatedResult;
  21179. }
  21180. return leftResult;
  21181. };
  21182. };
  21183. exports.leftAssociative.firstOf = function() {
  21184. return Array.prototype.slice.call(arguments, 0);
  21185. };
  21186. exports.nonConsuming = function(rule) {
  21187. return function(input) {
  21188. return rule(input).changeRemaining(input);
  21189. };
  21190. };
  21191. var describeToken = function(token) {
  21192. if (token.value) {
  21193. return token.name + " \"" + token.value + "\"";
  21194. } else {
  21195. return token.name;
  21196. }
  21197. };
  21198. function describeTokenMismatch(input, expected) {
  21199. var error;
  21200. var token = input.head();
  21201. if (token) {
  21202. error = errors.error({
  21203. expected: expected,
  21204. actual: describeToken(token),
  21205. location: token.source
  21206. });
  21207. } else {
  21208. error = errors.error({
  21209. expected: expected,
  21210. actual: "end of tokens"
  21211. });
  21212. }
  21213. return results.failure([error], input);
  21214. }
  21215. },{"./errors":145,"./lazy-iterators":146,"./parsing-results":148,"option":151,"underscore":152}],151:[function(require,module,exports){
  21216. exports.none = Object.create({
  21217. value: function() {
  21218. throw new Error('Called value on none');
  21219. },
  21220. isNone: function() {
  21221. return true;
  21222. },
  21223. isSome: function() {
  21224. return false;
  21225. },
  21226. map: function() {
  21227. return exports.none;
  21228. },
  21229. flatMap: function() {
  21230. return exports.none;
  21231. },
  21232. toArray: function() {
  21233. return [];
  21234. },
  21235. orElse: callOrReturn,
  21236. valueOrElse: callOrReturn
  21237. });
  21238. function callOrReturn(value) {
  21239. if (typeof(value) == "function") {
  21240. return value();
  21241. } else {
  21242. return value;
  21243. }
  21244. }
  21245. exports.some = function(value) {
  21246. return new Some(value);
  21247. };
  21248. var Some = function(value) {
  21249. this._value = value;
  21250. };
  21251. Some.prototype.value = function() {
  21252. return this._value;
  21253. };
  21254. Some.prototype.isNone = function() {
  21255. return false;
  21256. };
  21257. Some.prototype.isSome = function() {
  21258. return true;
  21259. };
  21260. Some.prototype.map = function(func) {
  21261. return new Some(func(this._value));
  21262. };
  21263. Some.prototype.flatMap = function(func) {
  21264. return func(this._value);
  21265. };
  21266. Some.prototype.toArray = function() {
  21267. return [this._value];
  21268. };
  21269. Some.prototype.orElse = function(value) {
  21270. return this;
  21271. };
  21272. Some.prototype.valueOrElse = function(value) {
  21273. return this._value;
  21274. };
  21275. exports.isOption = function(value) {
  21276. return value === exports.none || value instanceof Some;
  21277. };
  21278. exports.fromNullable = function(value) {
  21279. if (value == null) {
  21280. return exports.none;
  21281. }
  21282. return new Some(value);
  21283. }
  21284. },{}],152:[function(require,module,exports){
  21285. // Underscore.js 1.4.4
  21286. // http://underscorejs.org
  21287. // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
  21288. // Underscore may be freely distributed under the MIT license.
  21289. (function() {
  21290. // Baseline setup
  21291. // --------------
  21292. // Establish the root object, `window` in the browser, or `global` on the server.
  21293. var root = this;
  21294. // Save the previous value of the `_` variable.
  21295. var previousUnderscore = root._;
  21296. // Establish the object that gets returned to break out of a loop iteration.
  21297. var breaker = {};
  21298. // Save bytes in the minified (but not gzipped) version:
  21299. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  21300. // Create quick reference variables for speed access to core prototypes.
  21301. var push = ArrayProto.push,
  21302. slice = ArrayProto.slice,
  21303. concat = ArrayProto.concat,
  21304. toString = ObjProto.toString,
  21305. hasOwnProperty = ObjProto.hasOwnProperty;
  21306. // All **ECMAScript 5** native function implementations that we hope to use
  21307. // are declared here.
  21308. var
  21309. nativeForEach = ArrayProto.forEach,
  21310. nativeMap = ArrayProto.map,
  21311. nativeReduce = ArrayProto.reduce,
  21312. nativeReduceRight = ArrayProto.reduceRight,
  21313. nativeFilter = ArrayProto.filter,
  21314. nativeEvery = ArrayProto.every,
  21315. nativeSome = ArrayProto.some,
  21316. nativeIndexOf = ArrayProto.indexOf,
  21317. nativeLastIndexOf = ArrayProto.lastIndexOf,
  21318. nativeIsArray = Array.isArray,
  21319. nativeKeys = Object.keys,
  21320. nativeBind = FuncProto.bind;
  21321. // Create a safe reference to the Underscore object for use below.
  21322. var _ = function(obj) {
  21323. if (obj instanceof _) return obj;
  21324. if (!(this instanceof _)) return new _(obj);
  21325. this._wrapped = obj;
  21326. };
  21327. // Export the Underscore object for **Node.js**, with
  21328. // backwards-compatibility for the old `require()` API. If we're in
  21329. // the browser, add `_` as a global object via a string identifier,
  21330. // for Closure Compiler "advanced" mode.
  21331. if (typeof exports !== 'undefined') {
  21332. if (typeof module !== 'undefined' && module.exports) {
  21333. exports = module.exports = _;
  21334. }
  21335. exports._ = _;
  21336. } else {
  21337. root._ = _;
  21338. }
  21339. // Current version.
  21340. _.VERSION = '1.4.4';
  21341. // Collection Functions
  21342. // --------------------
  21343. // The cornerstone, an `each` implementation, aka `forEach`.
  21344. // Handles objects with the built-in `forEach`, arrays, and raw objects.
  21345. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  21346. var each = _.each = _.forEach = function(obj, iterator, context) {
  21347. if (obj == null) return;
  21348. if (nativeForEach && obj.forEach === nativeForEach) {
  21349. obj.forEach(iterator, context);
  21350. } else if (obj.length === +obj.length) {
  21351. for (var i = 0, l = obj.length; i < l; i++) {
  21352. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  21353. }
  21354. } else {
  21355. for (var key in obj) {
  21356. if (_.has(obj, key)) {
  21357. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  21358. }
  21359. }
  21360. }
  21361. };
  21362. // Return the results of applying the iterator to each element.
  21363. // Delegates to **ECMAScript 5**'s native `map` if available.
  21364. _.map = _.collect = function(obj, iterator, context) {
  21365. var results = [];
  21366. if (obj == null) return results;
  21367. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  21368. each(obj, function(value, index, list) {
  21369. results[results.length] = iterator.call(context, value, index, list);
  21370. });
  21371. return results;
  21372. };
  21373. var reduceError = 'Reduce of empty array with no initial value';
  21374. // **Reduce** builds up a single result from a list of values, aka `inject`,
  21375. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  21376. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  21377. var initial = arguments.length > 2;
  21378. if (obj == null) obj = [];
  21379. if (nativeReduce && obj.reduce === nativeReduce) {
  21380. if (context) iterator = _.bind(iterator, context);
  21381. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  21382. }
  21383. each(obj, function(value, index, list) {
  21384. if (!initial) {
  21385. memo = value;
  21386. initial = true;
  21387. } else {
  21388. memo = iterator.call(context, memo, value, index, list);
  21389. }
  21390. });
  21391. if (!initial) throw new TypeError(reduceError);
  21392. return memo;
  21393. };
  21394. // The right-associative version of reduce, also known as `foldr`.
  21395. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  21396. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  21397. var initial = arguments.length > 2;
  21398. if (obj == null) obj = [];
  21399. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  21400. if (context) iterator = _.bind(iterator, context);
  21401. return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  21402. }
  21403. var length = obj.length;
  21404. if (length !== +length) {
  21405. var keys = _.keys(obj);
  21406. length = keys.length;
  21407. }
  21408. each(obj, function(value, index, list) {
  21409. index = keys ? keys[--length] : --length;
  21410. if (!initial) {
  21411. memo = obj[index];
  21412. initial = true;
  21413. } else {
  21414. memo = iterator.call(context, memo, obj[index], index, list);
  21415. }
  21416. });
  21417. if (!initial) throw new TypeError(reduceError);
  21418. return memo;
  21419. };
  21420. // Return the first value which passes a truth test. Aliased as `detect`.
  21421. _.find = _.detect = function(obj, iterator, context) {
  21422. var result;
  21423. any(obj, function(value, index, list) {
  21424. if (iterator.call(context, value, index, list)) {
  21425. result = value;
  21426. return true;
  21427. }
  21428. });
  21429. return result;
  21430. };
  21431. // Return all the elements that pass a truth test.
  21432. // Delegates to **ECMAScript 5**'s native `filter` if available.
  21433. // Aliased as `select`.
  21434. _.filter = _.select = function(obj, iterator, context) {
  21435. var results = [];
  21436. if (obj == null) return results;
  21437. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  21438. each(obj, function(value, index, list) {
  21439. if (iterator.call(context, value, index, list)) results[results.length] = value;
  21440. });
  21441. return results;
  21442. };
  21443. // Return all the elements for which a truth test fails.
  21444. _.reject = function(obj, iterator, context) {
  21445. return _.filter(obj, function(value, index, list) {
  21446. return !iterator.call(context, value, index, list);
  21447. }, context);
  21448. };
  21449. // Determine whether all of the elements match a truth test.
  21450. // Delegates to **ECMAScript 5**'s native `every` if available.
  21451. // Aliased as `all`.
  21452. _.every = _.all = function(obj, iterator, context) {
  21453. iterator || (iterator = _.identity);
  21454. var result = true;
  21455. if (obj == null) return result;
  21456. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  21457. each(obj, function(value, index, list) {
  21458. if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  21459. });
  21460. return !!result;
  21461. };
  21462. // Determine if at least one element in the object matches a truth test.
  21463. // Delegates to **ECMAScript 5**'s native `some` if available.
  21464. // Aliased as `any`.
  21465. var any = _.some = _.any = function(obj, iterator, context) {
  21466. iterator || (iterator = _.identity);
  21467. var result = false;
  21468. if (obj == null) return result;
  21469. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  21470. each(obj, function(value, index, list) {
  21471. if (result || (result = iterator.call(context, value, index, list))) return breaker;
  21472. });
  21473. return !!result;
  21474. };
  21475. // Determine if the array or object contains a given value (using `===`).
  21476. // Aliased as `include`.
  21477. _.contains = _.include = function(obj, target) {
  21478. if (obj == null) return false;
  21479. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  21480. return any(obj, function(value) {
  21481. return value === target;
  21482. });
  21483. };
  21484. // Invoke a method (with arguments) on every item in a collection.
  21485. _.invoke = function(obj, method) {
  21486. var args = slice.call(arguments, 2);
  21487. var isFunc = _.isFunction(method);
  21488. return _.map(obj, function(value) {
  21489. return (isFunc ? method : value[method]).apply(value, args);
  21490. });
  21491. };
  21492. // Convenience version of a common use case of `map`: fetching a property.
  21493. _.pluck = function(obj, key) {
  21494. return _.map(obj, function(value){ return value[key]; });
  21495. };
  21496. // Convenience version of a common use case of `filter`: selecting only objects
  21497. // containing specific `key:value` pairs.
  21498. _.where = function(obj, attrs, first) {
  21499. if (_.isEmpty(attrs)) return first ? null : [];
  21500. return _[first ? 'find' : 'filter'](obj, function(value) {
  21501. for (var key in attrs) {
  21502. if (attrs[key] !== value[key]) return false;
  21503. }
  21504. return true;
  21505. });
  21506. };
  21507. // Convenience version of a common use case of `find`: getting the first object
  21508. // containing specific `key:value` pairs.
  21509. _.findWhere = function(obj, attrs) {
  21510. return _.where(obj, attrs, true);
  21511. };
  21512. // Return the maximum element or (element-based computation).
  21513. // Can't optimize arrays of integers longer than 65,535 elements.
  21514. // See: https://bugs.webkit.org/show_bug.cgi?id=80797
  21515. _.max = function(obj, iterator, context) {
  21516. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  21517. return Math.max.apply(Math, obj);
  21518. }
  21519. if (!iterator && _.isEmpty(obj)) return -Infinity;
  21520. var result = {computed : -Infinity, value: -Infinity};
  21521. each(obj, function(value, index, list) {
  21522. var computed = iterator ? iterator.call(context, value, index, list) : value;
  21523. computed >= result.computed && (result = {value : value, computed : computed});
  21524. });
  21525. return result.value;
  21526. };
  21527. // Return the minimum element (or element-based computation).
  21528. _.min = function(obj, iterator, context) {
  21529. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  21530. return Math.min.apply(Math, obj);
  21531. }
  21532. if (!iterator && _.isEmpty(obj)) return Infinity;
  21533. var result = {computed : Infinity, value: Infinity};
  21534. each(obj, function(value, index, list) {
  21535. var computed = iterator ? iterator.call(context, value, index, list) : value;
  21536. computed < result.computed && (result = {value : value, computed : computed});
  21537. });
  21538. return result.value;
  21539. };
  21540. // Shuffle an array.
  21541. _.shuffle = function(obj) {
  21542. var rand;
  21543. var index = 0;
  21544. var shuffled = [];
  21545. each(obj, function(value) {
  21546. rand = _.random(index++);
  21547. shuffled[index - 1] = shuffled[rand];
  21548. shuffled[rand] = value;
  21549. });
  21550. return shuffled;
  21551. };
  21552. // An internal function to generate lookup iterators.
  21553. var lookupIterator = function(value) {
  21554. return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  21555. };
  21556. // Sort the object's values by a criterion produced by an iterator.
  21557. _.sortBy = function(obj, value, context) {
  21558. var iterator = lookupIterator(value);
  21559. return _.pluck(_.map(obj, function(value, index, list) {
  21560. return {
  21561. value : value,
  21562. index : index,
  21563. criteria : iterator.call(context, value, index, list)
  21564. };
  21565. }).sort(function(left, right) {
  21566. var a = left.criteria;
  21567. var b = right.criteria;
  21568. if (a !== b) {
  21569. if (a > b || a === void 0) return 1;
  21570. if (a < b || b === void 0) return -1;
  21571. }
  21572. return left.index < right.index ? -1 : 1;
  21573. }), 'value');
  21574. };
  21575. // An internal function used for aggregate "group by" operations.
  21576. var group = function(obj, value, context, behavior) {
  21577. var result = {};
  21578. var iterator = lookupIterator(value || _.identity);
  21579. each(obj, function(value, index) {
  21580. var key = iterator.call(context, value, index, obj);
  21581. behavior(result, key, value);
  21582. });
  21583. return result;
  21584. };
  21585. // Groups the object's values by a criterion. Pass either a string attribute
  21586. // to group by, or a function that returns the criterion.
  21587. _.groupBy = function(obj, value, context) {
  21588. return group(obj, value, context, function(result, key, value) {
  21589. (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
  21590. });
  21591. };
  21592. // Counts instances of an object that group by a certain criterion. Pass
  21593. // either a string attribute to count by, or a function that returns the
  21594. // criterion.
  21595. _.countBy = function(obj, value, context) {
  21596. return group(obj, value, context, function(result, key) {
  21597. if (!_.has(result, key)) result[key] = 0;
  21598. result[key]++;
  21599. });
  21600. };
  21601. // Use a comparator function to figure out the smallest index at which
  21602. // an object should be inserted so as to maintain order. Uses binary search.
  21603. _.sortedIndex = function(array, obj, iterator, context) {
  21604. iterator = iterator == null ? _.identity : lookupIterator(iterator);
  21605. var value = iterator.call(context, obj);
  21606. var low = 0, high = array.length;
  21607. while (low < high) {
  21608. var mid = (low + high) >>> 1;
  21609. iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
  21610. }
  21611. return low;
  21612. };
  21613. // Safely convert anything iterable into a real, live array.
  21614. _.toArray = function(obj) {
  21615. if (!obj) return [];
  21616. if (_.isArray(obj)) return slice.call(obj);
  21617. if (obj.length === +obj.length) return _.map(obj, _.identity);
  21618. return _.values(obj);
  21619. };
  21620. // Return the number of elements in an object.
  21621. _.size = function(obj) {
  21622. if (obj == null) return 0;
  21623. return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  21624. };
  21625. // Array Functions
  21626. // ---------------
  21627. // Get the first element of an array. Passing **n** will return the first N
  21628. // values in the array. Aliased as `head` and `take`. The **guard** check
  21629. // allows it to work with `_.map`.
  21630. _.first = _.head = _.take = function(array, n, guard) {
  21631. if (array == null) return void 0;
  21632. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  21633. };
  21634. // Returns everything but the last entry of the array. Especially useful on
  21635. // the arguments object. Passing **n** will return all the values in
  21636. // the array, excluding the last N. The **guard** check allows it to work with
  21637. // `_.map`.
  21638. _.initial = function(array, n, guard) {
  21639. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  21640. };
  21641. // Get the last element of an array. Passing **n** will return the last N
  21642. // values in the array. The **guard** check allows it to work with `_.map`.
  21643. _.last = function(array, n, guard) {
  21644. if (array == null) return void 0;
  21645. if ((n != null) && !guard) {
  21646. return slice.call(array, Math.max(array.length - n, 0));
  21647. } else {
  21648. return array[array.length - 1];
  21649. }
  21650. };
  21651. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  21652. // Especially useful on the arguments object. Passing an **n** will return
  21653. // the rest N values in the array. The **guard**
  21654. // check allows it to work with `_.map`.
  21655. _.rest = _.tail = _.drop = function(array, n, guard) {
  21656. return slice.call(array, (n == null) || guard ? 1 : n);
  21657. };
  21658. // Trim out all falsy values from an array.
  21659. _.compact = function(array) {
  21660. return _.filter(array, _.identity);
  21661. };
  21662. // Internal implementation of a recursive `flatten` function.
  21663. var flatten = function(input, shallow, output) {
  21664. each(input, function(value) {
  21665. if (_.isArray(value)) {
  21666. shallow ? push.apply(output, value) : flatten(value, shallow, output);
  21667. } else {
  21668. output.push(value);
  21669. }
  21670. });
  21671. return output;
  21672. };
  21673. // Return a completely flattened version of an array.
  21674. _.flatten = function(array, shallow) {
  21675. return flatten(array, shallow, []);
  21676. };
  21677. // Return a version of the array that does not contain the specified value(s).
  21678. _.without = function(array) {
  21679. return _.difference(array, slice.call(arguments, 1));
  21680. };
  21681. // Produce a duplicate-free version of the array. If the array has already
  21682. // been sorted, you have the option of using a faster algorithm.
  21683. // Aliased as `unique`.
  21684. _.uniq = _.unique = function(array, isSorted, iterator, context) {
  21685. if (_.isFunction(isSorted)) {
  21686. context = iterator;
  21687. iterator = isSorted;
  21688. isSorted = false;
  21689. }
  21690. var initial = iterator ? _.map(array, iterator, context) : array;
  21691. var results = [];
  21692. var seen = [];
  21693. each(initial, function(value, index) {
  21694. if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
  21695. seen.push(value);
  21696. results.push(array[index]);
  21697. }
  21698. });
  21699. return results;
  21700. };
  21701. // Produce an array that contains the union: each distinct element from all of
  21702. // the passed-in arrays.
  21703. _.union = function() {
  21704. return _.uniq(concat.apply(ArrayProto, arguments));
  21705. };
  21706. // Produce an array that contains every item shared between all the
  21707. // passed-in arrays.
  21708. _.intersection = function(array) {
  21709. var rest = slice.call(arguments, 1);
  21710. return _.filter(_.uniq(array), function(item) {
  21711. return _.every(rest, function(other) {
  21712. return _.indexOf(other, item) >= 0;
  21713. });
  21714. });
  21715. };
  21716. // Take the difference between one array and a number of other arrays.
  21717. // Only the elements present in just the first array will remain.
  21718. _.difference = function(array) {
  21719. var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
  21720. return _.filter(array, function(value){ return !_.contains(rest, value); });
  21721. };
  21722. // Zip together multiple lists into a single array -- elements that share
  21723. // an index go together.
  21724. _.zip = function() {
  21725. var args = slice.call(arguments);
  21726. var length = _.max(_.pluck(args, 'length'));
  21727. var results = new Array(length);
  21728. for (var i = 0; i < length; i++) {
  21729. results[i] = _.pluck(args, "" + i);
  21730. }
  21731. return results;
  21732. };
  21733. // Converts lists into objects. Pass either a single array of `[key, value]`
  21734. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  21735. // the corresponding values.
  21736. _.object = function(list, values) {
  21737. if (list == null) return {};
  21738. var result = {};
  21739. for (var i = 0, l = list.length; i < l; i++) {
  21740. if (values) {
  21741. result[list[i]] = values[i];
  21742. } else {
  21743. result[list[i][0]] = list[i][1];
  21744. }
  21745. }
  21746. return result;
  21747. };
  21748. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  21749. // we need this function. Return the position of the first occurrence of an
  21750. // item in an array, or -1 if the item is not included in the array.
  21751. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  21752. // If the array is large and already in sort order, pass `true`
  21753. // for **isSorted** to use binary search.
  21754. _.indexOf = function(array, item, isSorted) {
  21755. if (array == null) return -1;
  21756. var i = 0, l = array.length;
  21757. if (isSorted) {
  21758. if (typeof isSorted == 'number') {
  21759. i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
  21760. } else {
  21761. i = _.sortedIndex(array, item);
  21762. return array[i] === item ? i : -1;
  21763. }
  21764. }
  21765. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
  21766. for (; i < l; i++) if (array[i] === item) return i;
  21767. return -1;
  21768. };
  21769. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  21770. _.lastIndexOf = function(array, item, from) {
  21771. if (array == null) return -1;
  21772. var hasIndex = from != null;
  21773. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
  21774. return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
  21775. }
  21776. var i = (hasIndex ? from : array.length);
  21777. while (i--) if (array[i] === item) return i;
  21778. return -1;
  21779. };
  21780. // Generate an integer Array containing an arithmetic progression. A port of
  21781. // the native Python `range()` function. See
  21782. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  21783. _.range = function(start, stop, step) {
  21784. if (arguments.length <= 1) {
  21785. stop = start || 0;
  21786. start = 0;
  21787. }
  21788. step = arguments[2] || 1;
  21789. var len = Math.max(Math.ceil((stop - start) / step), 0);
  21790. var idx = 0;
  21791. var range = new Array(len);
  21792. while(idx < len) {
  21793. range[idx++] = start;
  21794. start += step;
  21795. }
  21796. return range;
  21797. };
  21798. // Function (ahem) Functions
  21799. // ------------------
  21800. // Create a function bound to a given object (assigning `this`, and arguments,
  21801. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  21802. // available.
  21803. _.bind = function(func, context) {
  21804. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  21805. var args = slice.call(arguments, 2);
  21806. return function() {
  21807. return func.apply(context, args.concat(slice.call(arguments)));
  21808. };
  21809. };
  21810. // Partially apply a function by creating a version that has had some of its
  21811. // arguments pre-filled, without changing its dynamic `this` context.
  21812. _.partial = function(func) {
  21813. var args = slice.call(arguments, 1);
  21814. return function() {
  21815. return func.apply(this, args.concat(slice.call(arguments)));
  21816. };
  21817. };
  21818. // Bind all of an object's methods to that object. Useful for ensuring that
  21819. // all callbacks defined on an object belong to it.
  21820. _.bindAll = function(obj) {
  21821. var funcs = slice.call(arguments, 1);
  21822. if (funcs.length === 0) funcs = _.functions(obj);
  21823. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  21824. return obj;
  21825. };
  21826. // Memoize an expensive function by storing its results.
  21827. _.memoize = function(func, hasher) {
  21828. var memo = {};
  21829. hasher || (hasher = _.identity);
  21830. return function() {
  21831. var key = hasher.apply(this, arguments);
  21832. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  21833. };
  21834. };
  21835. // Delays a function for the given number of milliseconds, and then calls
  21836. // it with the arguments supplied.
  21837. _.delay = function(func, wait) {
  21838. var args = slice.call(arguments, 2);
  21839. return setTimeout(function(){ return func.apply(null, args); }, wait);
  21840. };
  21841. // Defers a function, scheduling it to run after the current call stack has
  21842. // cleared.
  21843. _.defer = function(func) {
  21844. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  21845. };
  21846. // Returns a function, that, when invoked, will only be triggered at most once
  21847. // during a given window of time.
  21848. _.throttle = function(func, wait) {
  21849. var context, args, timeout, result;
  21850. var previous = 0;
  21851. var later = function() {
  21852. previous = new Date;
  21853. timeout = null;
  21854. result = func.apply(context, args);
  21855. };
  21856. return function() {
  21857. var now = new Date;
  21858. var remaining = wait - (now - previous);
  21859. context = this;
  21860. args = arguments;
  21861. if (remaining <= 0) {
  21862. clearTimeout(timeout);
  21863. timeout = null;
  21864. previous = now;
  21865. result = func.apply(context, args);
  21866. } else if (!timeout) {
  21867. timeout = setTimeout(later, remaining);
  21868. }
  21869. return result;
  21870. };
  21871. };
  21872. // Returns a function, that, as long as it continues to be invoked, will not
  21873. // be triggered. The function will be called after it stops being called for
  21874. // N milliseconds. If `immediate` is passed, trigger the function on the
  21875. // leading edge, instead of the trailing.
  21876. _.debounce = function(func, wait, immediate) {
  21877. var timeout, result;
  21878. return function() {
  21879. var context = this, args = arguments;
  21880. var later = function() {
  21881. timeout = null;
  21882. if (!immediate) result = func.apply(context, args);
  21883. };
  21884. var callNow = immediate && !timeout;
  21885. clearTimeout(timeout);
  21886. timeout = setTimeout(later, wait);
  21887. if (callNow) result = func.apply(context, args);
  21888. return result;
  21889. };
  21890. };
  21891. // Returns a function that will be executed at most one time, no matter how
  21892. // often you call it. Useful for lazy initialization.
  21893. _.once = function(func) {
  21894. var ran = false, memo;
  21895. return function() {
  21896. if (ran) return memo;
  21897. ran = true;
  21898. memo = func.apply(this, arguments);
  21899. func = null;
  21900. return memo;
  21901. };
  21902. };
  21903. // Returns the first function passed as an argument to the second,
  21904. // allowing you to adjust arguments, run code before and after, and
  21905. // conditionally execute the original function.
  21906. _.wrap = function(func, wrapper) {
  21907. return function() {
  21908. var args = [func];
  21909. push.apply(args, arguments);
  21910. return wrapper.apply(this, args);
  21911. };
  21912. };
  21913. // Returns a function that is the composition of a list of functions, each
  21914. // consuming the return value of the function that follows.
  21915. _.compose = function() {
  21916. var funcs = arguments;
  21917. return function() {
  21918. var args = arguments;
  21919. for (var i = funcs.length - 1; i >= 0; i--) {
  21920. args = [funcs[i].apply(this, args)];
  21921. }
  21922. return args[0];
  21923. };
  21924. };
  21925. // Returns a function that will only be executed after being called N times.
  21926. _.after = function(times, func) {
  21927. if (times <= 0) return func();
  21928. return function() {
  21929. if (--times < 1) {
  21930. return func.apply(this, arguments);
  21931. }
  21932. };
  21933. };
  21934. // Object Functions
  21935. // ----------------
  21936. // Retrieve the names of an object's properties.
  21937. // Delegates to **ECMAScript 5**'s native `Object.keys`
  21938. _.keys = nativeKeys || function(obj) {
  21939. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  21940. var keys = [];
  21941. for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
  21942. return keys;
  21943. };
  21944. // Retrieve the values of an object's properties.
  21945. _.values = function(obj) {
  21946. var values = [];
  21947. for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
  21948. return values;
  21949. };
  21950. // Convert an object into a list of `[key, value]` pairs.
  21951. _.pairs = function(obj) {
  21952. var pairs = [];
  21953. for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
  21954. return pairs;
  21955. };
  21956. // Invert the keys and values of an object. The values must be serializable.
  21957. _.invert = function(obj) {
  21958. var result = {};
  21959. for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
  21960. return result;
  21961. };
  21962. // Return a sorted list of the function names available on the object.
  21963. // Aliased as `methods`
  21964. _.functions = _.methods = function(obj) {
  21965. var names = [];
  21966. for (var key in obj) {
  21967. if (_.isFunction(obj[key])) names.push(key);
  21968. }
  21969. return names.sort();
  21970. };
  21971. // Extend a given object with all the properties in passed-in object(s).
  21972. _.extend = function(obj) {
  21973. each(slice.call(arguments, 1), function(source) {
  21974. if (source) {
  21975. for (var prop in source) {
  21976. obj[prop] = source[prop];
  21977. }
  21978. }
  21979. });
  21980. return obj;
  21981. };
  21982. // Return a copy of the object only containing the whitelisted properties.
  21983. _.pick = function(obj) {
  21984. var copy = {};
  21985. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  21986. each(keys, function(key) {
  21987. if (key in obj) copy[key] = obj[key];
  21988. });
  21989. return copy;
  21990. };
  21991. // Return a copy of the object without the blacklisted properties.
  21992. _.omit = function(obj) {
  21993. var copy = {};
  21994. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  21995. for (var key in obj) {
  21996. if (!_.contains(keys, key)) copy[key] = obj[key];
  21997. }
  21998. return copy;
  21999. };
  22000. // Fill in a given object with default properties.
  22001. _.defaults = function(obj) {
  22002. each(slice.call(arguments, 1), function(source) {
  22003. if (source) {
  22004. for (var prop in source) {
  22005. if (obj[prop] == null) obj[prop] = source[prop];
  22006. }
  22007. }
  22008. });
  22009. return obj;
  22010. };
  22011. // Create a (shallow-cloned) duplicate of an object.
  22012. _.clone = function(obj) {
  22013. if (!_.isObject(obj)) return obj;
  22014. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  22015. };
  22016. // Invokes interceptor with the obj, and then returns obj.
  22017. // The primary purpose of this method is to "tap into" a method chain, in
  22018. // order to perform operations on intermediate results within the chain.
  22019. _.tap = function(obj, interceptor) {
  22020. interceptor(obj);
  22021. return obj;
  22022. };
  22023. // Internal recursive comparison function for `isEqual`.
  22024. var eq = function(a, b, aStack, bStack) {
  22025. // Identical objects are equal. `0 === -0`, but they aren't identical.
  22026. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  22027. if (a === b) return a !== 0 || 1 / a == 1 / b;
  22028. // A strict comparison is necessary because `null == undefined`.
  22029. if (a == null || b == null) return a === b;
  22030. // Unwrap any wrapped objects.
  22031. if (a instanceof _) a = a._wrapped;
  22032. if (b instanceof _) b = b._wrapped;
  22033. // Compare `[[Class]]` names.
  22034. var className = toString.call(a);
  22035. if (className != toString.call(b)) return false;
  22036. switch (className) {
  22037. // Strings, numbers, dates, and booleans are compared by value.
  22038. case '[object String]':
  22039. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  22040. // equivalent to `new String("5")`.
  22041. return a == String(b);
  22042. case '[object Number]':
  22043. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  22044. // other numeric values.
  22045. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  22046. case '[object Date]':
  22047. case '[object Boolean]':
  22048. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  22049. // millisecond representations. Note that invalid dates with millisecond representations
  22050. // of `NaN` are not equivalent.
  22051. return +a == +b;
  22052. // RegExps are compared by their source patterns and flags.
  22053. case '[object RegExp]':
  22054. return a.source == b.source &&
  22055. a.global == b.global &&
  22056. a.multiline == b.multiline &&
  22057. a.ignoreCase == b.ignoreCase;
  22058. }
  22059. if (typeof a != 'object' || typeof b != 'object') return false;
  22060. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  22061. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  22062. var length = aStack.length;
  22063. while (length--) {
  22064. // Linear search. Performance is inversely proportional to the number of
  22065. // unique nested structures.
  22066. if (aStack[length] == a) return bStack[length] == b;
  22067. }
  22068. // Add the first object to the stack of traversed objects.
  22069. aStack.push(a);
  22070. bStack.push(b);
  22071. var size = 0, result = true;
  22072. // Recursively compare objects and arrays.
  22073. if (className == '[object Array]') {
  22074. // Compare array lengths to determine if a deep comparison is necessary.
  22075. size = a.length;
  22076. result = size == b.length;
  22077. if (result) {
  22078. // Deep compare the contents, ignoring non-numeric properties.
  22079. while (size--) {
  22080. if (!(result = eq(a[size], b[size], aStack, bStack))) break;
  22081. }
  22082. }
  22083. } else {
  22084. // Objects with different constructors are not equivalent, but `Object`s
  22085. // from different frames are.
  22086. var aCtor = a.constructor, bCtor = b.constructor;
  22087. if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
  22088. _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
  22089. return false;
  22090. }
  22091. // Deep compare objects.
  22092. for (var key in a) {
  22093. if (_.has(a, key)) {
  22094. // Count the expected number of properties.
  22095. size++;
  22096. // Deep compare each member.
  22097. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
  22098. }
  22099. }
  22100. // Ensure that both objects contain the same number of properties.
  22101. if (result) {
  22102. for (key in b) {
  22103. if (_.has(b, key) && !(size--)) break;
  22104. }
  22105. result = !size;
  22106. }
  22107. }
  22108. // Remove the first object from the stack of traversed objects.
  22109. aStack.pop();
  22110. bStack.pop();
  22111. return result;
  22112. };
  22113. // Perform a deep comparison to check if two objects are equal.
  22114. _.isEqual = function(a, b) {
  22115. return eq(a, b, [], []);
  22116. };
  22117. // Is a given array, string, or object empty?
  22118. // An "empty" object has no enumerable own-properties.
  22119. _.isEmpty = function(obj) {
  22120. if (obj == null) return true;
  22121. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  22122. for (var key in obj) if (_.has(obj, key)) return false;
  22123. return true;
  22124. };
  22125. // Is a given value a DOM element?
  22126. _.isElement = function(obj) {
  22127. return !!(obj && obj.nodeType === 1);
  22128. };
  22129. // Is a given value an array?
  22130. // Delegates to ECMA5's native Array.isArray
  22131. _.isArray = nativeIsArray || function(obj) {
  22132. return toString.call(obj) == '[object Array]';
  22133. };
  22134. // Is a given variable an object?
  22135. _.isObject = function(obj) {
  22136. return obj === Object(obj);
  22137. };
  22138. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  22139. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
  22140. _['is' + name] = function(obj) {
  22141. return toString.call(obj) == '[object ' + name + ']';
  22142. };
  22143. });
  22144. // Define a fallback version of the method in browsers (ahem, IE), where
  22145. // there isn't any inspectable "Arguments" type.
  22146. if (!_.isArguments(arguments)) {
  22147. _.isArguments = function(obj) {
  22148. return !!(obj && _.has(obj, 'callee'));
  22149. };
  22150. }
  22151. // Optimize `isFunction` if appropriate.
  22152. if (typeof (/./) !== 'function') {
  22153. _.isFunction = function(obj) {
  22154. return typeof obj === 'function';
  22155. };
  22156. }
  22157. // Is a given object a finite number?
  22158. _.isFinite = function(obj) {
  22159. return isFinite(obj) && !isNaN(parseFloat(obj));
  22160. };
  22161. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  22162. _.isNaN = function(obj) {
  22163. return _.isNumber(obj) && obj != +obj;
  22164. };
  22165. // Is a given value a boolean?
  22166. _.isBoolean = function(obj) {
  22167. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  22168. };
  22169. // Is a given value equal to null?
  22170. _.isNull = function(obj) {
  22171. return obj === null;
  22172. };
  22173. // Is a given variable undefined?
  22174. _.isUndefined = function(obj) {
  22175. return obj === void 0;
  22176. };
  22177. // Shortcut function for checking if an object has a given property directly
  22178. // on itself (in other words, not on a prototype).
  22179. _.has = function(obj, key) {
  22180. return hasOwnProperty.call(obj, key);
  22181. };
  22182. // Utility Functions
  22183. // -----------------
  22184. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  22185. // previous owner. Returns a reference to the Underscore object.
  22186. _.noConflict = function() {
  22187. root._ = previousUnderscore;
  22188. return this;
  22189. };
  22190. // Keep the identity function around for default iterators.
  22191. _.identity = function(value) {
  22192. return value;
  22193. };
  22194. // Run a function **n** times.
  22195. _.times = function(n, iterator, context) {
  22196. var accum = Array(n);
  22197. for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
  22198. return accum;
  22199. };
  22200. // Return a random integer between min and max (inclusive).
  22201. _.random = function(min, max) {
  22202. if (max == null) {
  22203. max = min;
  22204. min = 0;
  22205. }
  22206. return min + Math.floor(Math.random() * (max - min + 1));
  22207. };
  22208. // List of HTML entities for escaping.
  22209. var entityMap = {
  22210. escape: {
  22211. '&': '&amp;',
  22212. '<': '&lt;',
  22213. '>': '&gt;',
  22214. '"': '&quot;',
  22215. "'": '&#x27;',
  22216. '/': '&#x2F;'
  22217. }
  22218. };
  22219. entityMap.unescape = _.invert(entityMap.escape);
  22220. // Regexes containing the keys and values listed immediately above.
  22221. var entityRegexes = {
  22222. escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  22223. unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  22224. };
  22225. // Functions for escaping and unescaping strings to/from HTML interpolation.
  22226. _.each(['escape', 'unescape'], function(method) {
  22227. _[method] = function(string) {
  22228. if (string == null) return '';
  22229. return ('' + string).replace(entityRegexes[method], function(match) {
  22230. return entityMap[method][match];
  22231. });
  22232. };
  22233. });
  22234. // If the value of the named property is a function then invoke it;
  22235. // otherwise, return it.
  22236. _.result = function(object, property) {
  22237. if (object == null) return null;
  22238. var value = object[property];
  22239. return _.isFunction(value) ? value.call(object) : value;
  22240. };
  22241. // Add your own custom functions to the Underscore object.
  22242. _.mixin = function(obj) {
  22243. each(_.functions(obj), function(name){
  22244. var func = _[name] = obj[name];
  22245. _.prototype[name] = function() {
  22246. var args = [this._wrapped];
  22247. push.apply(args, arguments);
  22248. return result.call(this, func.apply(_, args));
  22249. };
  22250. });
  22251. };
  22252. // Generate a unique integer id (unique within the entire client session).
  22253. // Useful for temporary DOM ids.
  22254. var idCounter = 0;
  22255. _.uniqueId = function(prefix) {
  22256. var id = ++idCounter + '';
  22257. return prefix ? prefix + id : id;
  22258. };
  22259. // By default, Underscore uses ERB-style template delimiters, change the
  22260. // following template settings to use alternative delimiters.
  22261. _.templateSettings = {
  22262. evaluate : /<%([\s\S]+?)%>/g,
  22263. interpolate : /<%=([\s\S]+?)%>/g,
  22264. escape : /<%-([\s\S]+?)%>/g
  22265. };
  22266. // When customizing `templateSettings`, if you don't want to define an
  22267. // interpolation, evaluation or escaping regex, we need one that is
  22268. // guaranteed not to match.
  22269. var noMatch = /(.)^/;
  22270. // Certain characters need to be escaped so that they can be put into a
  22271. // string literal.
  22272. var escapes = {
  22273. "'": "'",
  22274. '\\': '\\',
  22275. '\r': 'r',
  22276. '\n': 'n',
  22277. '\t': 't',
  22278. '\u2028': 'u2028',
  22279. '\u2029': 'u2029'
  22280. };
  22281. var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  22282. // JavaScript micro-templating, similar to John Resig's implementation.
  22283. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  22284. // and correctly escapes quotes within interpolated code.
  22285. _.template = function(text, data, settings) {
  22286. var render;
  22287. settings = _.defaults({}, settings, _.templateSettings);
  22288. // Combine delimiters into one regular expression via alternation.
  22289. var matcher = new RegExp([
  22290. (settings.escape || noMatch).source,
  22291. (settings.interpolate || noMatch).source,
  22292. (settings.evaluate || noMatch).source
  22293. ].join('|') + '|$', 'g');
  22294. // Compile the template source, escaping string literals appropriately.
  22295. var index = 0;
  22296. var source = "__p+='";
  22297. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  22298. source += text.slice(index, offset)
  22299. .replace(escaper, function(match) { return '\\' + escapes[match]; });
  22300. if (escape) {
  22301. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  22302. }
  22303. if (interpolate) {
  22304. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  22305. }
  22306. if (evaluate) {
  22307. source += "';\n" + evaluate + "\n__p+='";
  22308. }
  22309. index = offset + match.length;
  22310. return match;
  22311. });
  22312. source += "';\n";
  22313. // If a variable is not specified, place data values in local scope.
  22314. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  22315. source = "var __t,__p='',__j=Array.prototype.join," +
  22316. "print=function(){__p+=__j.call(arguments,'');};\n" +
  22317. source + "return __p;\n";
  22318. try {
  22319. render = new Function(settings.variable || 'obj', '_', source);
  22320. } catch (e) {
  22321. e.source = source;
  22322. throw e;
  22323. }
  22324. if (data) return render(data, _);
  22325. var template = function(data) {
  22326. return render.call(this, data, _);
  22327. };
  22328. // Provide the compiled function source as a convenience for precompilation.
  22329. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
  22330. return template;
  22331. };
  22332. // Add a "chain" function, which will delegate to the wrapper.
  22333. _.chain = function(obj) {
  22334. return _(obj).chain();
  22335. };
  22336. // OOP
  22337. // ---------------
  22338. // If Underscore is called as a function, it returns a wrapped object that
  22339. // can be used OO-style. This wrapper holds altered versions of all the
  22340. // underscore functions. Wrapped objects may be chained.
  22341. // Helper function to continue chaining intermediate results.
  22342. var result = function(obj) {
  22343. return this._chain ? _(obj).chain() : obj;
  22344. };
  22345. // Add all of the Underscore functions to the wrapper object.
  22346. _.mixin(_);
  22347. // Add all mutator Array functions to the wrapper.
  22348. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  22349. var method = ArrayProto[name];
  22350. _.prototype[name] = function() {
  22351. var obj = this._wrapped;
  22352. method.apply(obj, arguments);
  22353. if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
  22354. return result.call(this, obj);
  22355. };
  22356. });
  22357. // Add all accessor Array functions to the wrapper.
  22358. each(['concat', 'join', 'slice'], function(name) {
  22359. var method = ArrayProto[name];
  22360. _.prototype[name] = function() {
  22361. return result.call(this, method.apply(this._wrapped, arguments));
  22362. };
  22363. });
  22364. _.extend(_.prototype, {
  22365. // Start chaining a wrapped Underscore object.
  22366. chain: function() {
  22367. this._chain = true;
  22368. return this;
  22369. },
  22370. // Extracts the result from a wrapped and chained object.
  22371. value: function() {
  22372. return this._wrapped;
  22373. }
  22374. });
  22375. }).call(this);
  22376. },{}],153:[function(require,module,exports){
  22377. (function (Buffer){
  22378. ;(function (sax) { // wrapper for non-node envs
  22379. sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
  22380. sax.SAXParser = SAXParser
  22381. sax.SAXStream = SAXStream
  22382. sax.createStream = createStream
  22383. // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
  22384. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
  22385. // since that's the earliest that a buffer overrun could occur. This way, checks are
  22386. // as rare as required, but as often as necessary to ensure never crossing this bound.
  22387. // Furthermore, buffers are only tested at most once per write(), so passing a very
  22388. // large string into write() might have undesirable effects, but this is manageable by
  22389. // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
  22390. // edge case, result in creating at most one complete copy of the string passed in.
  22391. // Set to Infinity to have unlimited buffers.
  22392. sax.MAX_BUFFER_LENGTH = 64 * 1024
  22393. var buffers = [
  22394. 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
  22395. 'procInstName', 'procInstBody', 'entity', 'attribName',
  22396. 'attribValue', 'cdata', 'script'
  22397. ]
  22398. sax.EVENTS = [
  22399. 'text',
  22400. 'processinginstruction',
  22401. 'sgmldeclaration',
  22402. 'doctype',
  22403. 'comment',
  22404. 'attribute',
  22405. 'opentag',
  22406. 'closetag',
  22407. 'opencdata',
  22408. 'cdata',
  22409. 'closecdata',
  22410. 'error',
  22411. 'end',
  22412. 'ready',
  22413. 'script',
  22414. 'opennamespace',
  22415. 'closenamespace'
  22416. ]
  22417. function SAXParser (strict, opt) {
  22418. if (!(this instanceof SAXParser)) {
  22419. return new SAXParser(strict, opt)
  22420. }
  22421. var parser = this
  22422. clearBuffers(parser)
  22423. parser.q = parser.c = ''
  22424. parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
  22425. parser.opt = opt || {}
  22426. parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
  22427. parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
  22428. parser.tags = []
  22429. parser.closed = parser.closedRoot = parser.sawRoot = false
  22430. parser.tag = parser.error = null
  22431. parser.strict = !!strict
  22432. parser.noscript = !!(strict || parser.opt.noscript)
  22433. parser.state = S.BEGIN
  22434. parser.strictEntities = parser.opt.strictEntities
  22435. parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
  22436. parser.attribList = []
  22437. // namespaces form a prototype chain.
  22438. // it always points at the current tag,
  22439. // which protos to its parent tag.
  22440. if (parser.opt.xmlns) {
  22441. parser.ns = Object.create(rootNS)
  22442. }
  22443. // mostly just for error reporting
  22444. parser.trackPosition = parser.opt.position !== false
  22445. if (parser.trackPosition) {
  22446. parser.position = parser.line = parser.column = 0
  22447. }
  22448. emit(parser, 'onready')
  22449. }
  22450. if (!Object.create) {
  22451. Object.create = function (o) {
  22452. function F () {}
  22453. F.prototype = o
  22454. var newf = new F()
  22455. return newf
  22456. }
  22457. }
  22458. if (!Object.keys) {
  22459. Object.keys = function (o) {
  22460. var a = []
  22461. for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
  22462. return a
  22463. }
  22464. }
  22465. function checkBufferLength (parser) {
  22466. var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
  22467. var maxActual = 0
  22468. for (var i = 0, l = buffers.length; i < l; i++) {
  22469. var len = parser[buffers[i]].length
  22470. if (len > maxAllowed) {
  22471. // Text/cdata nodes can get big, and since they're buffered,
  22472. // we can get here under normal conditions.
  22473. // Avoid issues by emitting the text node now,
  22474. // so at least it won't get any bigger.
  22475. switch (buffers[i]) {
  22476. case 'textNode':
  22477. closeText(parser)
  22478. break
  22479. case 'cdata':
  22480. emitNode(parser, 'oncdata', parser.cdata)
  22481. parser.cdata = ''
  22482. break
  22483. case 'script':
  22484. emitNode(parser, 'onscript', parser.script)
  22485. parser.script = ''
  22486. break
  22487. default:
  22488. error(parser, 'Max buffer length exceeded: ' + buffers[i])
  22489. }
  22490. }
  22491. maxActual = Math.max(maxActual, len)
  22492. }
  22493. // schedule the next check for the earliest possible buffer overrun.
  22494. var m = sax.MAX_BUFFER_LENGTH - maxActual
  22495. parser.bufferCheckPosition = m + parser.position
  22496. }
  22497. function clearBuffers (parser) {
  22498. for (var i = 0, l = buffers.length; i < l; i++) {
  22499. parser[buffers[i]] = ''
  22500. }
  22501. }
  22502. function flushBuffers (parser) {
  22503. closeText(parser)
  22504. if (parser.cdata !== '') {
  22505. emitNode(parser, 'oncdata', parser.cdata)
  22506. parser.cdata = ''
  22507. }
  22508. if (parser.script !== '') {
  22509. emitNode(parser, 'onscript', parser.script)
  22510. parser.script = ''
  22511. }
  22512. }
  22513. SAXParser.prototype = {
  22514. end: function () { end(this) },
  22515. write: write,
  22516. resume: function () { this.error = null; return this },
  22517. close: function () { return this.write(null) },
  22518. flush: function () { flushBuffers(this) }
  22519. }
  22520. var Stream
  22521. try {
  22522. Stream = require('stream').Stream
  22523. } catch (ex) {
  22524. Stream = function () {}
  22525. }
  22526. var streamWraps = sax.EVENTS.filter(function (ev) {
  22527. return ev !== 'error' && ev !== 'end'
  22528. })
  22529. function createStream (strict, opt) {
  22530. return new SAXStream(strict, opt)
  22531. }
  22532. function SAXStream (strict, opt) {
  22533. if (!(this instanceof SAXStream)) {
  22534. return new SAXStream(strict, opt)
  22535. }
  22536. Stream.apply(this)
  22537. this._parser = new SAXParser(strict, opt)
  22538. this.writable = true
  22539. this.readable = true
  22540. var me = this
  22541. this._parser.onend = function () {
  22542. me.emit('end')
  22543. }
  22544. this._parser.onerror = function (er) {
  22545. me.emit('error', er)
  22546. // if didn't throw, then means error was handled.
  22547. // go ahead and clear error, so we can write again.
  22548. me._parser.error = null
  22549. }
  22550. this._decoder = null
  22551. streamWraps.forEach(function (ev) {
  22552. Object.defineProperty(me, 'on' + ev, {
  22553. get: function () {
  22554. return me._parser['on' + ev]
  22555. },
  22556. set: function (h) {
  22557. if (!h) {
  22558. me.removeAllListeners(ev)
  22559. me._parser['on' + ev] = h
  22560. return h
  22561. }
  22562. me.on(ev, h)
  22563. },
  22564. enumerable: true,
  22565. configurable: false
  22566. })
  22567. })
  22568. }
  22569. SAXStream.prototype = Object.create(Stream.prototype, {
  22570. constructor: {
  22571. value: SAXStream
  22572. }
  22573. })
  22574. SAXStream.prototype.write = function (data) {
  22575. if (typeof Buffer === 'function' &&
  22576. typeof Buffer.isBuffer === 'function' &&
  22577. Buffer.isBuffer(data)) {
  22578. if (!this._decoder) {
  22579. var SD = require('string_decoder').StringDecoder
  22580. this._decoder = new SD('utf8')
  22581. }
  22582. data = this._decoder.write(data)
  22583. }
  22584. this._parser.write(data.toString())
  22585. this.emit('data', data)
  22586. return true
  22587. }
  22588. SAXStream.prototype.end = function (chunk) {
  22589. if (chunk && chunk.length) {
  22590. this.write(chunk)
  22591. }
  22592. this._parser.end()
  22593. return true
  22594. }
  22595. SAXStream.prototype.on = function (ev, handler) {
  22596. var me = this
  22597. if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
  22598. me._parser['on' + ev] = function () {
  22599. var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
  22600. args.splice(0, 0, ev)
  22601. me.emit.apply(me, args)
  22602. }
  22603. }
  22604. return Stream.prototype.on.call(me, ev, handler)
  22605. }
  22606. // character classes and tokens
  22607. var whitespace = '\r\n\t '
  22608. // this really needs to be replaced with character classes.
  22609. // XML allows all manner of ridiculous numbers and digits.
  22610. var number = '0124356789'
  22611. var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  22612. // (Letter | "_" | ":")
  22613. var quote = '\'"'
  22614. var attribEnd = whitespace + '>'
  22615. var CDATA = '[CDATA['
  22616. var DOCTYPE = 'DOCTYPE'
  22617. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
  22618. var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
  22619. var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
  22620. // turn all the string character sets into character class objects.
  22621. whitespace = charClass(whitespace)
  22622. number = charClass(number)
  22623. letter = charClass(letter)
  22624. // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
  22625. // This implementation works on strings, a single character at a time
  22626. // as such, it cannot ever support astral-plane characters (10000-EFFFF)
  22627. // without a significant breaking change to either this parser, or the
  22628. // JavaScript language. Implementation of an emoji-capable xml parser
  22629. // is left as an exercise for the reader.
  22630. var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
  22631. var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
  22632. var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
  22633. var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
  22634. quote = charClass(quote)
  22635. attribEnd = charClass(attribEnd)
  22636. function charClass (str) {
  22637. return str.split('').reduce(function (s, c) {
  22638. s[c] = true
  22639. return s
  22640. }, {})
  22641. }
  22642. function isRegExp (c) {
  22643. return Object.prototype.toString.call(c) === '[object RegExp]'
  22644. }
  22645. function is (charclass, c) {
  22646. return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
  22647. }
  22648. function not (charclass, c) {
  22649. return !is(charclass, c)
  22650. }
  22651. var S = 0
  22652. sax.STATE = {
  22653. BEGIN: S++, // leading byte order mark or whitespace
  22654. BEGIN_WHITESPACE: S++, // leading whitespace
  22655. TEXT: S++, // general stuff
  22656. TEXT_ENTITY: S++, // &amp and such.
  22657. OPEN_WAKA: S++, // <
  22658. SGML_DECL: S++, // <!BLARG
  22659. SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
  22660. DOCTYPE: S++, // <!DOCTYPE
  22661. DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
  22662. DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
  22663. DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
  22664. COMMENT_STARTING: S++, // <!-
  22665. COMMENT: S++, // <!--
  22666. COMMENT_ENDING: S++, // <!-- blah -
  22667. COMMENT_ENDED: S++, // <!-- blah --
  22668. CDATA: S++, // <![CDATA[ something
  22669. CDATA_ENDING: S++, // ]
  22670. CDATA_ENDING_2: S++, // ]]
  22671. PROC_INST: S++, // <?hi
  22672. PROC_INST_BODY: S++, // <?hi there
  22673. PROC_INST_ENDING: S++, // <?hi "there" ?
  22674. OPEN_TAG: S++, // <strong
  22675. OPEN_TAG_SLASH: S++, // <strong /
  22676. ATTRIB: S++, // <a
  22677. ATTRIB_NAME: S++, // <a foo
  22678. ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
  22679. ATTRIB_VALUE: S++, // <a foo=
  22680. ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
  22681. ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
  22682. ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
  22683. ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="&quot;"
  22684. ATTRIB_VALUE_ENTITY_U: S++, // <foo bar=&quot
  22685. CLOSE_TAG: S++, // </a
  22686. CLOSE_TAG_SAW_WHITE: S++, // </a >
  22687. SCRIPT: S++, // <script> ...
  22688. SCRIPT_ENDING: S++ // <script> ... <
  22689. }
  22690. sax.XML_ENTITIES = {
  22691. 'amp': '&',
  22692. 'gt': '>',
  22693. 'lt': '<',
  22694. 'quot': '"',
  22695. 'apos': "'"
  22696. }
  22697. sax.ENTITIES = {
  22698. 'amp': '&',
  22699. 'gt': '>',
  22700. 'lt': '<',
  22701. 'quot': '"',
  22702. 'apos': "'",
  22703. 'AElig': 198,
  22704. 'Aacute': 193,
  22705. 'Acirc': 194,
  22706. 'Agrave': 192,
  22707. 'Aring': 197,
  22708. 'Atilde': 195,
  22709. 'Auml': 196,
  22710. 'Ccedil': 199,
  22711. 'ETH': 208,
  22712. 'Eacute': 201,
  22713. 'Ecirc': 202,
  22714. 'Egrave': 200,
  22715. 'Euml': 203,
  22716. 'Iacute': 205,
  22717. 'Icirc': 206,
  22718. 'Igrave': 204,
  22719. 'Iuml': 207,
  22720. 'Ntilde': 209,
  22721. 'Oacute': 211,
  22722. 'Ocirc': 212,
  22723. 'Ograve': 210,
  22724. 'Oslash': 216,
  22725. 'Otilde': 213,
  22726. 'Ouml': 214,
  22727. 'THORN': 222,
  22728. 'Uacute': 218,
  22729. 'Ucirc': 219,
  22730. 'Ugrave': 217,
  22731. 'Uuml': 220,
  22732. 'Yacute': 221,
  22733. 'aacute': 225,
  22734. 'acirc': 226,
  22735. 'aelig': 230,
  22736. 'agrave': 224,
  22737. 'aring': 229,
  22738. 'atilde': 227,
  22739. 'auml': 228,
  22740. 'ccedil': 231,
  22741. 'eacute': 233,
  22742. 'ecirc': 234,
  22743. 'egrave': 232,
  22744. 'eth': 240,
  22745. 'euml': 235,
  22746. 'iacute': 237,
  22747. 'icirc': 238,
  22748. 'igrave': 236,
  22749. 'iuml': 239,
  22750. 'ntilde': 241,
  22751. 'oacute': 243,
  22752. 'ocirc': 244,
  22753. 'ograve': 242,
  22754. 'oslash': 248,
  22755. 'otilde': 245,
  22756. 'ouml': 246,
  22757. 'szlig': 223,
  22758. 'thorn': 254,
  22759. 'uacute': 250,
  22760. 'ucirc': 251,
  22761. 'ugrave': 249,
  22762. 'uuml': 252,
  22763. 'yacute': 253,
  22764. 'yuml': 255,
  22765. 'copy': 169,
  22766. 'reg': 174,
  22767. 'nbsp': 160,
  22768. 'iexcl': 161,
  22769. 'cent': 162,
  22770. 'pound': 163,
  22771. 'curren': 164,
  22772. 'yen': 165,
  22773. 'brvbar': 166,
  22774. 'sect': 167,
  22775. 'uml': 168,
  22776. 'ordf': 170,
  22777. 'laquo': 171,
  22778. 'not': 172,
  22779. 'shy': 173,
  22780. 'macr': 175,
  22781. 'deg': 176,
  22782. 'plusmn': 177,
  22783. 'sup1': 185,
  22784. 'sup2': 178,
  22785. 'sup3': 179,
  22786. 'acute': 180,
  22787. 'micro': 181,
  22788. 'para': 182,
  22789. 'middot': 183,
  22790. 'cedil': 184,
  22791. 'ordm': 186,
  22792. 'raquo': 187,
  22793. 'frac14': 188,
  22794. 'frac12': 189,
  22795. 'frac34': 190,
  22796. 'iquest': 191,
  22797. 'times': 215,
  22798. 'divide': 247,
  22799. 'OElig': 338,
  22800. 'oelig': 339,
  22801. 'Scaron': 352,
  22802. 'scaron': 353,
  22803. 'Yuml': 376,
  22804. 'fnof': 402,
  22805. 'circ': 710,
  22806. 'tilde': 732,
  22807. 'Alpha': 913,
  22808. 'Beta': 914,
  22809. 'Gamma': 915,
  22810. 'Delta': 916,
  22811. 'Epsilon': 917,
  22812. 'Zeta': 918,
  22813. 'Eta': 919,
  22814. 'Theta': 920,
  22815. 'Iota': 921,
  22816. 'Kappa': 922,
  22817. 'Lambda': 923,
  22818. 'Mu': 924,
  22819. 'Nu': 925,
  22820. 'Xi': 926,
  22821. 'Omicron': 927,
  22822. 'Pi': 928,
  22823. 'Rho': 929,
  22824. 'Sigma': 931,
  22825. 'Tau': 932,
  22826. 'Upsilon': 933,
  22827. 'Phi': 934,
  22828. 'Chi': 935,
  22829. 'Psi': 936,
  22830. 'Omega': 937,
  22831. 'alpha': 945,
  22832. 'beta': 946,
  22833. 'gamma': 947,
  22834. 'delta': 948,
  22835. 'epsilon': 949,
  22836. 'zeta': 950,
  22837. 'eta': 951,
  22838. 'theta': 952,
  22839. 'iota': 953,
  22840. 'kappa': 954,
  22841. 'lambda': 955,
  22842. 'mu': 956,
  22843. 'nu': 957,
  22844. 'xi': 958,
  22845. 'omicron': 959,
  22846. 'pi': 960,
  22847. 'rho': 961,
  22848. 'sigmaf': 962,
  22849. 'sigma': 963,
  22850. 'tau': 964,
  22851. 'upsilon': 965,
  22852. 'phi': 966,
  22853. 'chi': 967,
  22854. 'psi': 968,
  22855. 'omega': 969,
  22856. 'thetasym': 977,
  22857. 'upsih': 978,
  22858. 'piv': 982,
  22859. 'ensp': 8194,
  22860. 'emsp': 8195,
  22861. 'thinsp': 8201,
  22862. 'zwnj': 8204,
  22863. 'zwj': 8205,
  22864. 'lrm': 8206,
  22865. 'rlm': 8207,
  22866. 'ndash': 8211,
  22867. 'mdash': 8212,
  22868. 'lsquo': 8216,
  22869. 'rsquo': 8217,
  22870. 'sbquo': 8218,
  22871. 'ldquo': 8220,
  22872. 'rdquo': 8221,
  22873. 'bdquo': 8222,
  22874. 'dagger': 8224,
  22875. 'Dagger': 8225,
  22876. 'bull': 8226,
  22877. 'hellip': 8230,
  22878. 'permil': 8240,
  22879. 'prime': 8242,
  22880. 'Prime': 8243,
  22881. 'lsaquo': 8249,
  22882. 'rsaquo': 8250,
  22883. 'oline': 8254,
  22884. 'frasl': 8260,
  22885. 'euro': 8364,
  22886. 'image': 8465,
  22887. 'weierp': 8472,
  22888. 'real': 8476,
  22889. 'trade': 8482,
  22890. 'alefsym': 8501,
  22891. 'larr': 8592,
  22892. 'uarr': 8593,
  22893. 'rarr': 8594,
  22894. 'darr': 8595,
  22895. 'harr': 8596,
  22896. 'crarr': 8629,
  22897. 'lArr': 8656,
  22898. 'uArr': 8657,
  22899. 'rArr': 8658,
  22900. 'dArr': 8659,
  22901. 'hArr': 8660,
  22902. 'forall': 8704,
  22903. 'part': 8706,
  22904. 'exist': 8707,
  22905. 'empty': 8709,
  22906. 'nabla': 8711,
  22907. 'isin': 8712,
  22908. 'notin': 8713,
  22909. 'ni': 8715,
  22910. 'prod': 8719,
  22911. 'sum': 8721,
  22912. 'minus': 8722,
  22913. 'lowast': 8727,
  22914. 'radic': 8730,
  22915. 'prop': 8733,
  22916. 'infin': 8734,
  22917. 'ang': 8736,
  22918. 'and': 8743,
  22919. 'or': 8744,
  22920. 'cap': 8745,
  22921. 'cup': 8746,
  22922. 'int': 8747,
  22923. 'there4': 8756,
  22924. 'sim': 8764,
  22925. 'cong': 8773,
  22926. 'asymp': 8776,
  22927. 'ne': 8800,
  22928. 'equiv': 8801,
  22929. 'le': 8804,
  22930. 'ge': 8805,
  22931. 'sub': 8834,
  22932. 'sup': 8835,
  22933. 'nsub': 8836,
  22934. 'sube': 8838,
  22935. 'supe': 8839,
  22936. 'oplus': 8853,
  22937. 'otimes': 8855,
  22938. 'perp': 8869,
  22939. 'sdot': 8901,
  22940. 'lceil': 8968,
  22941. 'rceil': 8969,
  22942. 'lfloor': 8970,
  22943. 'rfloor': 8971,
  22944. 'lang': 9001,
  22945. 'rang': 9002,
  22946. 'loz': 9674,
  22947. 'spades': 9824,
  22948. 'clubs': 9827,
  22949. 'hearts': 9829,
  22950. 'diams': 9830
  22951. }
  22952. Object.keys(sax.ENTITIES).forEach(function (key) {
  22953. var e = sax.ENTITIES[key]
  22954. var s = typeof e === 'number' ? String.fromCharCode(e) : e
  22955. sax.ENTITIES[key] = s
  22956. })
  22957. for (var s in sax.STATE) {
  22958. sax.STATE[sax.STATE[s]] = s
  22959. }
  22960. // shorthand
  22961. S = sax.STATE
  22962. function emit (parser, event, data) {
  22963. parser[event] && parser[event](data)
  22964. }
  22965. function emitNode (parser, nodeType, data) {
  22966. if (parser.textNode) closeText(parser)
  22967. emit(parser, nodeType, data)
  22968. }
  22969. function closeText (parser) {
  22970. parser.textNode = textopts(parser.opt, parser.textNode)
  22971. if (parser.textNode) emit(parser, 'ontext', parser.textNode)
  22972. parser.textNode = ''
  22973. }
  22974. function textopts (opt, text) {
  22975. if (opt.trim) text = text.trim()
  22976. if (opt.normalize) text = text.replace(/\s+/g, ' ')
  22977. return text
  22978. }
  22979. function error (parser, er) {
  22980. closeText(parser)
  22981. if (parser.trackPosition) {
  22982. er += '\nLine: ' + parser.line +
  22983. '\nColumn: ' + parser.column +
  22984. '\nChar: ' + parser.c
  22985. }
  22986. er = new Error(er)
  22987. parser.error = er
  22988. emit(parser, 'onerror', er)
  22989. return parser
  22990. }
  22991. function end (parser) {
  22992. if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
  22993. if ((parser.state !== S.BEGIN) &&
  22994. (parser.state !== S.BEGIN_WHITESPACE) &&
  22995. (parser.state !== S.TEXT)) {
  22996. error(parser, 'Unexpected end')
  22997. }
  22998. closeText(parser)
  22999. parser.c = ''
  23000. parser.closed = true
  23001. emit(parser, 'onend')
  23002. SAXParser.call(parser, parser.strict, parser.opt)
  23003. return parser
  23004. }
  23005. function strictFail (parser, message) {
  23006. if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
  23007. throw new Error('bad call to strictFail')
  23008. }
  23009. if (parser.strict) {
  23010. error(parser, message)
  23011. }
  23012. }
  23013. function newTag (parser) {
  23014. if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
  23015. var parent = parser.tags[parser.tags.length - 1] || parser
  23016. var tag = parser.tag = { name: parser.tagName, attributes: {} }
  23017. // will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
  23018. if (parser.opt.xmlns) {
  23019. tag.ns = parent.ns
  23020. }
  23021. parser.attribList.length = 0
  23022. }
  23023. function qname (name, attribute) {
  23024. var i = name.indexOf(':')
  23025. var qualName = i < 0 ? [ '', name ] : name.split(':')
  23026. var prefix = qualName[0]
  23027. var local = qualName[1]
  23028. // <x "xmlns"="http://foo">
  23029. if (attribute && name === 'xmlns') {
  23030. prefix = 'xmlns'
  23031. local = ''
  23032. }
  23033. return { prefix: prefix, local: local }
  23034. }
  23035. function attrib (parser) {
  23036. if (!parser.strict) {
  23037. parser.attribName = parser.attribName[parser.looseCase]()
  23038. }
  23039. if (parser.attribList.indexOf(parser.attribName) !== -1 ||
  23040. parser.tag.attributes.hasOwnProperty(parser.attribName)) {
  23041. parser.attribName = parser.attribValue = ''
  23042. return
  23043. }
  23044. if (parser.opt.xmlns) {
  23045. var qn = qname(parser.attribName, true)
  23046. var prefix = qn.prefix
  23047. var local = qn.local
  23048. if (prefix === 'xmlns') {
  23049. // namespace binding attribute. push the binding into scope
  23050. if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
  23051. strictFail(parser,
  23052. 'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
  23053. 'Actual: ' + parser.attribValue)
  23054. } else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
  23055. strictFail(parser,
  23056. 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
  23057. 'Actual: ' + parser.attribValue)
  23058. } else {
  23059. var tag = parser.tag
  23060. var parent = parser.tags[parser.tags.length - 1] || parser
  23061. if (tag.ns === parent.ns) {
  23062. tag.ns = Object.create(parent.ns)
  23063. }
  23064. tag.ns[local] = parser.attribValue
  23065. }
  23066. }
  23067. // defer onattribute events until all attributes have been seen
  23068. // so any new bindings can take effect. preserve attribute order
  23069. // so deferred events can be emitted in document order
  23070. parser.attribList.push([parser.attribName, parser.attribValue])
  23071. } else {
  23072. // in non-xmlns mode, we can emit the event right away
  23073. parser.tag.attributes[parser.attribName] = parser.attribValue
  23074. emitNode(parser, 'onattribute', {
  23075. name: parser.attribName,
  23076. value: parser.attribValue
  23077. })
  23078. }
  23079. parser.attribName = parser.attribValue = ''
  23080. }
  23081. function openTag (parser, selfClosing) {
  23082. if (parser.opt.xmlns) {
  23083. // emit namespace binding events
  23084. var tag = parser.tag
  23085. // add namespace info to tag
  23086. var qn = qname(parser.tagName)
  23087. tag.prefix = qn.prefix
  23088. tag.local = qn.local
  23089. tag.uri = tag.ns[qn.prefix] || ''
  23090. if (tag.prefix && !tag.uri) {
  23091. strictFail(parser, 'Unbound namespace prefix: ' +
  23092. JSON.stringify(parser.tagName))
  23093. tag.uri = qn.prefix
  23094. }
  23095. var parent = parser.tags[parser.tags.length - 1] || parser
  23096. if (tag.ns && parent.ns !== tag.ns) {
  23097. Object.keys(tag.ns).forEach(function (p) {
  23098. emitNode(parser, 'onopennamespace', {
  23099. prefix: p,
  23100. uri: tag.ns[p]
  23101. })
  23102. })
  23103. }
  23104. // handle deferred onattribute events
  23105. // Note: do not apply default ns to attributes:
  23106. // http://www.w3.org/TR/REC-xml-names/#defaulting
  23107. for (var i = 0, l = parser.attribList.length; i < l; i++) {
  23108. var nv = parser.attribList[i]
  23109. var name = nv[0]
  23110. var value = nv[1]
  23111. var qualName = qname(name, true)
  23112. var prefix = qualName.prefix
  23113. var local = qualName.local
  23114. var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
  23115. var a = {
  23116. name: name,
  23117. value: value,
  23118. prefix: prefix,
  23119. local: local,
  23120. uri: uri
  23121. }
  23122. // if there's any attributes with an undefined namespace,
  23123. // then fail on them now.
  23124. if (prefix && prefix !== 'xmlns' && !uri) {
  23125. strictFail(parser, 'Unbound namespace prefix: ' +
  23126. JSON.stringify(prefix))
  23127. a.uri = prefix
  23128. }
  23129. parser.tag.attributes[name] = a
  23130. emitNode(parser, 'onattribute', a)
  23131. }
  23132. parser.attribList.length = 0
  23133. }
  23134. parser.tag.isSelfClosing = !!selfClosing
  23135. // process the tag
  23136. parser.sawRoot = true
  23137. parser.tags.push(parser.tag)
  23138. emitNode(parser, 'onopentag', parser.tag)
  23139. if (!selfClosing) {
  23140. // special case for <script> in non-strict mode.
  23141. if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
  23142. parser.state = S.SCRIPT
  23143. } else {
  23144. parser.state = S.TEXT
  23145. }
  23146. parser.tag = null
  23147. parser.tagName = ''
  23148. }
  23149. parser.attribName = parser.attribValue = ''
  23150. parser.attribList.length = 0
  23151. }
  23152. function closeTag (parser) {
  23153. if (!parser.tagName) {
  23154. strictFail(parser, 'Weird empty close tag.')
  23155. parser.textNode += '</>'
  23156. parser.state = S.TEXT
  23157. return
  23158. }
  23159. if (parser.script) {
  23160. if (parser.tagName !== 'script') {
  23161. parser.script += '</' + parser.tagName + '>'
  23162. parser.tagName = ''
  23163. parser.state = S.SCRIPT
  23164. return
  23165. }
  23166. emitNode(parser, 'onscript', parser.script)
  23167. parser.script = ''
  23168. }
  23169. // first make sure that the closing tag actually exists.
  23170. // <a><b></c></b></a> will close everything, otherwise.
  23171. var t = parser.tags.length
  23172. var tagName = parser.tagName
  23173. if (!parser.strict) {
  23174. tagName = tagName[parser.looseCase]()
  23175. }
  23176. var closeTo = tagName
  23177. while (t--) {
  23178. var close = parser.tags[t]
  23179. if (close.name !== closeTo) {
  23180. // fail the first time in strict mode
  23181. strictFail(parser, 'Unexpected close tag')
  23182. } else {
  23183. break
  23184. }
  23185. }
  23186. // didn't find it. we already failed for strict, so just abort.
  23187. if (t < 0) {
  23188. strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
  23189. parser.textNode += '</' + parser.tagName + '>'
  23190. parser.state = S.TEXT
  23191. return
  23192. }
  23193. parser.tagName = tagName
  23194. var s = parser.tags.length
  23195. while (s-- > t) {
  23196. var tag = parser.tag = parser.tags.pop()
  23197. parser.tagName = parser.tag.name
  23198. emitNode(parser, 'onclosetag', parser.tagName)
  23199. var x = {}
  23200. for (var i in tag.ns) {
  23201. x[i] = tag.ns[i]
  23202. }
  23203. var parent = parser.tags[parser.tags.length - 1] || parser
  23204. if (parser.opt.xmlns && tag.ns !== parent.ns) {
  23205. // remove namespace bindings introduced by tag
  23206. Object.keys(tag.ns).forEach(function (p) {
  23207. var n = tag.ns[p]
  23208. emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
  23209. })
  23210. }
  23211. }
  23212. if (t === 0) parser.closedRoot = true
  23213. parser.tagName = parser.attribValue = parser.attribName = ''
  23214. parser.attribList.length = 0
  23215. parser.state = S.TEXT
  23216. }
  23217. function parseEntity (parser) {
  23218. var entity = parser.entity
  23219. var entityLC = entity.toLowerCase()
  23220. var num
  23221. var numStr = ''
  23222. if (parser.ENTITIES[entity]) {
  23223. return parser.ENTITIES[entity]
  23224. }
  23225. if (parser.ENTITIES[entityLC]) {
  23226. return parser.ENTITIES[entityLC]
  23227. }
  23228. entity = entityLC
  23229. if (entity.charAt(0) === '#') {
  23230. if (entity.charAt(1) === 'x') {
  23231. entity = entity.slice(2)
  23232. num = parseInt(entity, 16)
  23233. numStr = num.toString(16)
  23234. } else {
  23235. entity = entity.slice(1)
  23236. num = parseInt(entity, 10)
  23237. numStr = num.toString(10)
  23238. }
  23239. }
  23240. entity = entity.replace(/^0+/, '')
  23241. if (numStr.toLowerCase() !== entity) {
  23242. strictFail(parser, 'Invalid character entity')
  23243. return '&' + parser.entity + ';'
  23244. }
  23245. return String.fromCodePoint(num)
  23246. }
  23247. function beginWhiteSpace (parser, c) {
  23248. if (c === '<') {
  23249. parser.state = S.OPEN_WAKA
  23250. parser.startTagPosition = parser.position
  23251. } else if (not(whitespace, c)) {
  23252. // have to process this as a text node.
  23253. // weird, but happens.
  23254. strictFail(parser, 'Non-whitespace before first tag.')
  23255. parser.textNode = c
  23256. parser.state = S.TEXT
  23257. }
  23258. }
  23259. function write (chunk) {
  23260. var parser = this
  23261. if (this.error) {
  23262. throw this.error
  23263. }
  23264. if (parser.closed) {
  23265. return error(parser,
  23266. 'Cannot write after close. Assign an onready handler.')
  23267. }
  23268. if (chunk === null) {
  23269. return end(parser)
  23270. }
  23271. var i = 0
  23272. var c = ''
  23273. while (true) {
  23274. c = chunk.charAt(i++)
  23275. parser.c = c
  23276. if (!c) {
  23277. break
  23278. }
  23279. if (parser.trackPosition) {
  23280. parser.position++
  23281. if (c === '\n') {
  23282. parser.line++
  23283. parser.column = 0
  23284. } else {
  23285. parser.column++
  23286. }
  23287. }
  23288. switch (parser.state) {
  23289. case S.BEGIN:
  23290. parser.state = S.BEGIN_WHITESPACE
  23291. if (c === '\uFEFF') {
  23292. continue
  23293. }
  23294. beginWhiteSpace(parser, c)
  23295. continue
  23296. case S.BEGIN_WHITESPACE:
  23297. beginWhiteSpace(parser, c)
  23298. continue
  23299. case S.TEXT:
  23300. if (parser.sawRoot && !parser.closedRoot) {
  23301. var starti = i - 1
  23302. while (c && c !== '<' && c !== '&') {
  23303. c = chunk.charAt(i++)
  23304. if (c && parser.trackPosition) {
  23305. parser.position++
  23306. if (c === '\n') {
  23307. parser.line++
  23308. parser.column = 0
  23309. } else {
  23310. parser.column++
  23311. }
  23312. }
  23313. }
  23314. parser.textNode += chunk.substring(starti, i - 1)
  23315. }
  23316. if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
  23317. parser.state = S.OPEN_WAKA
  23318. parser.startTagPosition = parser.position
  23319. } else {
  23320. if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {
  23321. strictFail(parser, 'Text data outside of root node.')
  23322. }
  23323. if (c === '&') {
  23324. parser.state = S.TEXT_ENTITY
  23325. } else {
  23326. parser.textNode += c
  23327. }
  23328. }
  23329. continue
  23330. case S.SCRIPT:
  23331. // only non-strict
  23332. if (c === '<') {
  23333. parser.state = S.SCRIPT_ENDING
  23334. } else {
  23335. parser.script += c
  23336. }
  23337. continue
  23338. case S.SCRIPT_ENDING:
  23339. if (c === '/') {
  23340. parser.state = S.CLOSE_TAG
  23341. } else {
  23342. parser.script += '<' + c
  23343. parser.state = S.SCRIPT
  23344. }
  23345. continue
  23346. case S.OPEN_WAKA:
  23347. // either a /, ?, !, or text is coming next.
  23348. if (c === '!') {
  23349. parser.state = S.SGML_DECL
  23350. parser.sgmlDecl = ''
  23351. } else if (is(whitespace, c)) {
  23352. // wait for it...
  23353. } else if (is(nameStart, c)) {
  23354. parser.state = S.OPEN_TAG
  23355. parser.tagName = c
  23356. } else if (c === '/') {
  23357. parser.state = S.CLOSE_TAG
  23358. parser.tagName = ''
  23359. } else if (c === '?') {
  23360. parser.state = S.PROC_INST
  23361. parser.procInstName = parser.procInstBody = ''
  23362. } else {
  23363. strictFail(parser, 'Unencoded <')
  23364. // if there was some whitespace, then add that in.
  23365. if (parser.startTagPosition + 1 < parser.position) {
  23366. var pad = parser.position - parser.startTagPosition
  23367. c = new Array(pad).join(' ') + c
  23368. }
  23369. parser.textNode += '<' + c
  23370. parser.state = S.TEXT
  23371. }
  23372. continue
  23373. case S.SGML_DECL:
  23374. if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
  23375. emitNode(parser, 'onopencdata')
  23376. parser.state = S.CDATA
  23377. parser.sgmlDecl = ''
  23378. parser.cdata = ''
  23379. } else if (parser.sgmlDecl + c === '--') {
  23380. parser.state = S.COMMENT
  23381. parser.comment = ''
  23382. parser.sgmlDecl = ''
  23383. } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
  23384. parser.state = S.DOCTYPE
  23385. if (parser.doctype || parser.sawRoot) {
  23386. strictFail(parser,
  23387. 'Inappropriately located doctype declaration')
  23388. }
  23389. parser.doctype = ''
  23390. parser.sgmlDecl = ''
  23391. } else if (c === '>') {
  23392. emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
  23393. parser.sgmlDecl = ''
  23394. parser.state = S.TEXT
  23395. } else if (is(quote, c)) {
  23396. parser.state = S.SGML_DECL_QUOTED
  23397. parser.sgmlDecl += c
  23398. } else {
  23399. parser.sgmlDecl += c
  23400. }
  23401. continue
  23402. case S.SGML_DECL_QUOTED:
  23403. if (c === parser.q) {
  23404. parser.state = S.SGML_DECL
  23405. parser.q = ''
  23406. }
  23407. parser.sgmlDecl += c
  23408. continue
  23409. case S.DOCTYPE:
  23410. if (c === '>') {
  23411. parser.state = S.TEXT
  23412. emitNode(parser, 'ondoctype', parser.doctype)
  23413. parser.doctype = true // just remember that we saw it.
  23414. } else {
  23415. parser.doctype += c
  23416. if (c === '[') {
  23417. parser.state = S.DOCTYPE_DTD
  23418. } else if (is(quote, c)) {
  23419. parser.state = S.DOCTYPE_QUOTED
  23420. parser.q = c
  23421. }
  23422. }
  23423. continue
  23424. case S.DOCTYPE_QUOTED:
  23425. parser.doctype += c
  23426. if (c === parser.q) {
  23427. parser.q = ''
  23428. parser.state = S.DOCTYPE
  23429. }
  23430. continue
  23431. case S.DOCTYPE_DTD:
  23432. parser.doctype += c
  23433. if (c === ']') {
  23434. parser.state = S.DOCTYPE
  23435. } else if (is(quote, c)) {
  23436. parser.state = S.DOCTYPE_DTD_QUOTED
  23437. parser.q = c
  23438. }
  23439. continue
  23440. case S.DOCTYPE_DTD_QUOTED:
  23441. parser.doctype += c
  23442. if (c === parser.q) {
  23443. parser.state = S.DOCTYPE_DTD
  23444. parser.q = ''
  23445. }
  23446. continue
  23447. case S.COMMENT:
  23448. if (c === '-') {
  23449. parser.state = S.COMMENT_ENDING
  23450. } else {
  23451. parser.comment += c
  23452. }
  23453. continue
  23454. case S.COMMENT_ENDING:
  23455. if (c === '-') {
  23456. parser.state = S.COMMENT_ENDED
  23457. parser.comment = textopts(parser.opt, parser.comment)
  23458. if (parser.comment) {
  23459. emitNode(parser, 'oncomment', parser.comment)
  23460. }
  23461. parser.comment = ''
  23462. } else {
  23463. parser.comment += '-' + c
  23464. parser.state = S.COMMENT
  23465. }
  23466. continue
  23467. case S.COMMENT_ENDED:
  23468. if (c !== '>') {
  23469. strictFail(parser, 'Malformed comment')
  23470. // allow <!-- blah -- bloo --> in non-strict mode,
  23471. // which is a comment of " blah -- bloo "
  23472. parser.comment += '--' + c
  23473. parser.state = S.COMMENT
  23474. } else {
  23475. parser.state = S.TEXT
  23476. }
  23477. continue
  23478. case S.CDATA:
  23479. if (c === ']') {
  23480. parser.state = S.CDATA_ENDING
  23481. } else {
  23482. parser.cdata += c
  23483. }
  23484. continue
  23485. case S.CDATA_ENDING:
  23486. if (c === ']') {
  23487. parser.state = S.CDATA_ENDING_2
  23488. } else {
  23489. parser.cdata += ']' + c
  23490. parser.state = S.CDATA
  23491. }
  23492. continue
  23493. case S.CDATA_ENDING_2:
  23494. if (c === '>') {
  23495. if (parser.cdata) {
  23496. emitNode(parser, 'oncdata', parser.cdata)
  23497. }
  23498. emitNode(parser, 'onclosecdata')
  23499. parser.cdata = ''
  23500. parser.state = S.TEXT
  23501. } else if (c === ']') {
  23502. parser.cdata += ']'
  23503. } else {
  23504. parser.cdata += ']]' + c
  23505. parser.state = S.CDATA
  23506. }
  23507. continue
  23508. case S.PROC_INST:
  23509. if (c === '?') {
  23510. parser.state = S.PROC_INST_ENDING
  23511. } else if (is(whitespace, c)) {
  23512. parser.state = S.PROC_INST_BODY
  23513. } else {
  23514. parser.procInstName += c
  23515. }
  23516. continue
  23517. case S.PROC_INST_BODY:
  23518. if (!parser.procInstBody && is(whitespace, c)) {
  23519. continue
  23520. } else if (c === '?') {
  23521. parser.state = S.PROC_INST_ENDING
  23522. } else {
  23523. parser.procInstBody += c
  23524. }
  23525. continue
  23526. case S.PROC_INST_ENDING:
  23527. if (c === '>') {
  23528. emitNode(parser, 'onprocessinginstruction', {
  23529. name: parser.procInstName,
  23530. body: parser.procInstBody
  23531. })
  23532. parser.procInstName = parser.procInstBody = ''
  23533. parser.state = S.TEXT
  23534. } else {
  23535. parser.procInstBody += '?' + c
  23536. parser.state = S.PROC_INST_BODY
  23537. }
  23538. continue
  23539. case S.OPEN_TAG:
  23540. if (is(nameBody, c)) {
  23541. parser.tagName += c
  23542. } else {
  23543. newTag(parser)
  23544. if (c === '>') {
  23545. openTag(parser)
  23546. } else if (c === '/') {
  23547. parser.state = S.OPEN_TAG_SLASH
  23548. } else {
  23549. if (not(whitespace, c)) {
  23550. strictFail(parser, 'Invalid character in tag name')
  23551. }
  23552. parser.state = S.ATTRIB
  23553. }
  23554. }
  23555. continue
  23556. case S.OPEN_TAG_SLASH:
  23557. if (c === '>') {
  23558. openTag(parser, true)
  23559. closeTag(parser)
  23560. } else {
  23561. strictFail(parser, 'Forward-slash in opening tag not followed by >')
  23562. parser.state = S.ATTRIB
  23563. }
  23564. continue
  23565. case S.ATTRIB:
  23566. // haven't read the attribute name yet.
  23567. if (is(whitespace, c)) {
  23568. continue
  23569. } else if (c === '>') {
  23570. openTag(parser)
  23571. } else if (c === '/') {
  23572. parser.state = S.OPEN_TAG_SLASH
  23573. } else if (is(nameStart, c)) {
  23574. parser.attribName = c
  23575. parser.attribValue = ''
  23576. parser.state = S.ATTRIB_NAME
  23577. } else {
  23578. strictFail(parser, 'Invalid attribute name')
  23579. }
  23580. continue
  23581. case S.ATTRIB_NAME:
  23582. if (c === '=') {
  23583. parser.state = S.ATTRIB_VALUE
  23584. } else if (c === '>') {
  23585. strictFail(parser, 'Attribute without value')
  23586. parser.attribValue = parser.attribName
  23587. attrib(parser)
  23588. openTag(parser)
  23589. } else if (is(whitespace, c)) {
  23590. parser.state = S.ATTRIB_NAME_SAW_WHITE
  23591. } else if (is(nameBody, c)) {
  23592. parser.attribName += c
  23593. } else {
  23594. strictFail(parser, 'Invalid attribute name')
  23595. }
  23596. continue
  23597. case S.ATTRIB_NAME_SAW_WHITE:
  23598. if (c === '=') {
  23599. parser.state = S.ATTRIB_VALUE
  23600. } else if (is(whitespace, c)) {
  23601. continue
  23602. } else {
  23603. strictFail(parser, 'Attribute without value')
  23604. parser.tag.attributes[parser.attribName] = ''
  23605. parser.attribValue = ''
  23606. emitNode(parser, 'onattribute', {
  23607. name: parser.attribName,
  23608. value: ''
  23609. })
  23610. parser.attribName = ''
  23611. if (c === '>') {
  23612. openTag(parser)
  23613. } else if (is(nameStart, c)) {
  23614. parser.attribName = c
  23615. parser.state = S.ATTRIB_NAME
  23616. } else {
  23617. strictFail(parser, 'Invalid attribute name')
  23618. parser.state = S.ATTRIB
  23619. }
  23620. }
  23621. continue
  23622. case S.ATTRIB_VALUE:
  23623. if (is(whitespace, c)) {
  23624. continue
  23625. } else if (is(quote, c)) {
  23626. parser.q = c
  23627. parser.state = S.ATTRIB_VALUE_QUOTED
  23628. } else {
  23629. strictFail(parser, 'Unquoted attribute value')
  23630. parser.state = S.ATTRIB_VALUE_UNQUOTED
  23631. parser.attribValue = c
  23632. }
  23633. continue
  23634. case S.ATTRIB_VALUE_QUOTED:
  23635. if (c !== parser.q) {
  23636. if (c === '&') {
  23637. parser.state = S.ATTRIB_VALUE_ENTITY_Q
  23638. } else {
  23639. parser.attribValue += c
  23640. }
  23641. continue
  23642. }
  23643. attrib(parser)
  23644. parser.q = ''
  23645. parser.state = S.ATTRIB_VALUE_CLOSED
  23646. continue
  23647. case S.ATTRIB_VALUE_CLOSED:
  23648. if (is(whitespace, c)) {
  23649. parser.state = S.ATTRIB
  23650. } else if (c === '>') {
  23651. openTag(parser)
  23652. } else if (c === '/') {
  23653. parser.state = S.OPEN_TAG_SLASH
  23654. } else if (is(nameStart, c)) {
  23655. strictFail(parser, 'No whitespace between attributes')
  23656. parser.attribName = c
  23657. parser.attribValue = ''
  23658. parser.state = S.ATTRIB_NAME
  23659. } else {
  23660. strictFail(parser, 'Invalid attribute name')
  23661. }
  23662. continue
  23663. case S.ATTRIB_VALUE_UNQUOTED:
  23664. if (not(attribEnd, c)) {
  23665. if (c === '&') {
  23666. parser.state = S.ATTRIB_VALUE_ENTITY_U
  23667. } else {
  23668. parser.attribValue += c
  23669. }
  23670. continue
  23671. }
  23672. attrib(parser)
  23673. if (c === '>') {
  23674. openTag(parser)
  23675. } else {
  23676. parser.state = S.ATTRIB
  23677. }
  23678. continue
  23679. case S.CLOSE_TAG:
  23680. if (!parser.tagName) {
  23681. if (is(whitespace, c)) {
  23682. continue
  23683. } else if (not(nameStart, c)) {
  23684. if (parser.script) {
  23685. parser.script += '</' + c
  23686. parser.state = S.SCRIPT
  23687. } else {
  23688. strictFail(parser, 'Invalid tagname in closing tag.')
  23689. }
  23690. } else {
  23691. parser.tagName = c
  23692. }
  23693. } else if (c === '>') {
  23694. closeTag(parser)
  23695. } else if (is(nameBody, c)) {
  23696. parser.tagName += c
  23697. } else if (parser.script) {
  23698. parser.script += '</' + parser.tagName
  23699. parser.tagName = ''
  23700. parser.state = S.SCRIPT
  23701. } else {
  23702. if (not(whitespace, c)) {
  23703. strictFail(parser, 'Invalid tagname in closing tag')
  23704. }
  23705. parser.state = S.CLOSE_TAG_SAW_WHITE
  23706. }
  23707. continue
  23708. case S.CLOSE_TAG_SAW_WHITE:
  23709. if (is(whitespace, c)) {
  23710. continue
  23711. }
  23712. if (c === '>') {
  23713. closeTag(parser)
  23714. } else {
  23715. strictFail(parser, 'Invalid characters in closing tag')
  23716. }
  23717. continue
  23718. case S.TEXT_ENTITY:
  23719. case S.ATTRIB_VALUE_ENTITY_Q:
  23720. case S.ATTRIB_VALUE_ENTITY_U:
  23721. var returnState
  23722. var buffer
  23723. switch (parser.state) {
  23724. case S.TEXT_ENTITY:
  23725. returnState = S.TEXT
  23726. buffer = 'textNode'
  23727. break
  23728. case S.ATTRIB_VALUE_ENTITY_Q:
  23729. returnState = S.ATTRIB_VALUE_QUOTED
  23730. buffer = 'attribValue'
  23731. break
  23732. case S.ATTRIB_VALUE_ENTITY_U:
  23733. returnState = S.ATTRIB_VALUE_UNQUOTED
  23734. buffer = 'attribValue'
  23735. break
  23736. }
  23737. if (c === ';') {
  23738. parser[buffer] += parseEntity(parser)
  23739. parser.entity = ''
  23740. parser.state = returnState
  23741. } else if (is(parser.entity.length ? entityBody : entityStart, c)) {
  23742. parser.entity += c
  23743. } else {
  23744. strictFail(parser, 'Invalid character in entity name')
  23745. parser[buffer] += '&' + parser.entity + c
  23746. parser.entity = ''
  23747. parser.state = returnState
  23748. }
  23749. continue
  23750. default:
  23751. throw new Error(parser, 'Unknown state: ' + parser.state)
  23752. }
  23753. } // while
  23754. if (parser.position >= parser.bufferCheckPosition) {
  23755. checkBufferLength(parser)
  23756. }
  23757. return parser
  23758. }
  23759. /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
  23760. if (!String.fromCodePoint) {
  23761. (function () {
  23762. var stringFromCharCode = String.fromCharCode
  23763. var floor = Math.floor
  23764. var fromCodePoint = function () {
  23765. var MAX_SIZE = 0x4000
  23766. var codeUnits = []
  23767. var highSurrogate
  23768. var lowSurrogate
  23769. var index = -1
  23770. var length = arguments.length
  23771. if (!length) {
  23772. return ''
  23773. }
  23774. var result = ''
  23775. while (++index < length) {
  23776. var codePoint = Number(arguments[index])
  23777. if (
  23778. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  23779. codePoint < 0 || // not a valid Unicode code point
  23780. codePoint > 0x10FFFF || // not a valid Unicode code point
  23781. floor(codePoint) !== codePoint // not an integer
  23782. ) {
  23783. throw RangeError('Invalid code point: ' + codePoint)
  23784. }
  23785. if (codePoint <= 0xFFFF) { // BMP code point
  23786. codeUnits.push(codePoint)
  23787. } else { // Astral code point; split in surrogate halves
  23788. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  23789. codePoint -= 0x10000
  23790. highSurrogate = (codePoint >> 10) + 0xD800
  23791. lowSurrogate = (codePoint % 0x400) + 0xDC00
  23792. codeUnits.push(highSurrogate, lowSurrogate)
  23793. }
  23794. if (index + 1 === length || codeUnits.length > MAX_SIZE) {
  23795. result += stringFromCharCode.apply(null, codeUnits)
  23796. codeUnits.length = 0
  23797. }
  23798. }
  23799. return result
  23800. }
  23801. if (Object.defineProperty) {
  23802. Object.defineProperty(String, 'fromCodePoint', {
  23803. value: fromCodePoint,
  23804. configurable: true,
  23805. writable: true
  23806. })
  23807. } else {
  23808. String.fromCodePoint = fromCodePoint
  23809. }
  23810. }())
  23811. }
  23812. })(typeof exports === 'undefined' ? this.sax = {} : exports)
  23813. }).call(this,require("buffer").Buffer)
  23814. },{"buffer":73,"stream":97,"string_decoder":98}],154:[function(require,module,exports){
  23815. // Underscore.js 1.6.0
  23816. // http://underscorejs.org
  23817. // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  23818. // Underscore may be freely distributed under the MIT license.
  23819. (function() {
  23820. // Baseline setup
  23821. // --------------
  23822. // Establish the root object, `window` in the browser, or `exports` on the server.
  23823. var root = this;
  23824. // Save the previous value of the `_` variable.
  23825. var previousUnderscore = root._;
  23826. // Establish the object that gets returned to break out of a loop iteration.
  23827. var breaker = {};
  23828. // Save bytes in the minified (but not gzipped) version:
  23829. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  23830. // Create quick reference variables for speed access to core prototypes.
  23831. var
  23832. push = ArrayProto.push,
  23833. slice = ArrayProto.slice,
  23834. concat = ArrayProto.concat,
  23835. toString = ObjProto.toString,
  23836. hasOwnProperty = ObjProto.hasOwnProperty;
  23837. // All **ECMAScript 5** native function implementations that we hope to use
  23838. // are declared here.
  23839. var
  23840. nativeForEach = ArrayProto.forEach,
  23841. nativeMap = ArrayProto.map,
  23842. nativeReduce = ArrayProto.reduce,
  23843. nativeReduceRight = ArrayProto.reduceRight,
  23844. nativeFilter = ArrayProto.filter,
  23845. nativeEvery = ArrayProto.every,
  23846. nativeSome = ArrayProto.some,
  23847. nativeIndexOf = ArrayProto.indexOf,
  23848. nativeLastIndexOf = ArrayProto.lastIndexOf,
  23849. nativeIsArray = Array.isArray,
  23850. nativeKeys = Object.keys,
  23851. nativeBind = FuncProto.bind;
  23852. // Create a safe reference to the Underscore object for use below.
  23853. var _ = function(obj) {
  23854. if (obj instanceof _) return obj;
  23855. if (!(this instanceof _)) return new _(obj);
  23856. this._wrapped = obj;
  23857. };
  23858. // Export the Underscore object for **Node.js**, with
  23859. // backwards-compatibility for the old `require()` API. If we're in
  23860. // the browser, add `_` as a global object via a string identifier,
  23861. // for Closure Compiler "advanced" mode.
  23862. if (typeof exports !== 'undefined') {
  23863. if (typeof module !== 'undefined' && module.exports) {
  23864. exports = module.exports = _;
  23865. }
  23866. exports._ = _;
  23867. } else {
  23868. root._ = _;
  23869. }
  23870. // Current version.
  23871. _.VERSION = '1.6.0';
  23872. // Collection Functions
  23873. // --------------------
  23874. // The cornerstone, an `each` implementation, aka `forEach`.
  23875. // Handles objects with the built-in `forEach`, arrays, and raw objects.
  23876. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  23877. var each = _.each = _.forEach = function(obj, iterator, context) {
  23878. if (obj == null) return obj;
  23879. if (nativeForEach && obj.forEach === nativeForEach) {
  23880. obj.forEach(iterator, context);
  23881. } else if (obj.length === +obj.length) {
  23882. for (var i = 0, length = obj.length; i < length; i++) {
  23883. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  23884. }
  23885. } else {
  23886. var keys = _.keys(obj);
  23887. for (var i = 0, length = keys.length; i < length; i++) {
  23888. if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
  23889. }
  23890. }
  23891. return obj;
  23892. };
  23893. // Return the results of applying the iterator to each element.
  23894. // Delegates to **ECMAScript 5**'s native `map` if available.
  23895. _.map = _.collect = function(obj, iterator, context) {
  23896. var results = [];
  23897. if (obj == null) return results;
  23898. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  23899. each(obj, function(value, index, list) {
  23900. results.push(iterator.call(context, value, index, list));
  23901. });
  23902. return results;
  23903. };
  23904. var reduceError = 'Reduce of empty array with no initial value';
  23905. // **Reduce** builds up a single result from a list of values, aka `inject`,
  23906. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  23907. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  23908. var initial = arguments.length > 2;
  23909. if (obj == null) obj = [];
  23910. if (nativeReduce && obj.reduce === nativeReduce) {
  23911. if (context) iterator = _.bind(iterator, context);
  23912. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  23913. }
  23914. each(obj, function(value, index, list) {
  23915. if (!initial) {
  23916. memo = value;
  23917. initial = true;
  23918. } else {
  23919. memo = iterator.call(context, memo, value, index, list);
  23920. }
  23921. });
  23922. if (!initial) throw new TypeError(reduceError);
  23923. return memo;
  23924. };
  23925. // The right-associative version of reduce, also known as `foldr`.
  23926. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  23927. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  23928. var initial = arguments.length > 2;
  23929. if (obj == null) obj = [];
  23930. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  23931. if (context) iterator = _.bind(iterator, context);
  23932. return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  23933. }
  23934. var length = obj.length;
  23935. if (length !== +length) {
  23936. var keys = _.keys(obj);
  23937. length = keys.length;
  23938. }
  23939. each(obj, function(value, index, list) {
  23940. index = keys ? keys[--length] : --length;
  23941. if (!initial) {
  23942. memo = obj[index];
  23943. initial = true;
  23944. } else {
  23945. memo = iterator.call(context, memo, obj[index], index, list);
  23946. }
  23947. });
  23948. if (!initial) throw new TypeError(reduceError);
  23949. return memo;
  23950. };
  23951. // Return the first value which passes a truth test. Aliased as `detect`.
  23952. _.find = _.detect = function(obj, predicate, context) {
  23953. var result;
  23954. any(obj, function(value, index, list) {
  23955. if (predicate.call(context, value, index, list)) {
  23956. result = value;
  23957. return true;
  23958. }
  23959. });
  23960. return result;
  23961. };
  23962. // Return all the elements that pass a truth test.
  23963. // Delegates to **ECMAScript 5**'s native `filter` if available.
  23964. // Aliased as `select`.
  23965. _.filter = _.select = function(obj, predicate, context) {
  23966. var results = [];
  23967. if (obj == null) return results;
  23968. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
  23969. each(obj, function(value, index, list) {
  23970. if (predicate.call(context, value, index, list)) results.push(value);
  23971. });
  23972. return results;
  23973. };
  23974. // Return all the elements for which a truth test fails.
  23975. _.reject = function(obj, predicate, context) {
  23976. return _.filter(obj, function(value, index, list) {
  23977. return !predicate.call(context, value, index, list);
  23978. }, context);
  23979. };
  23980. // Determine whether all of the elements match a truth test.
  23981. // Delegates to **ECMAScript 5**'s native `every` if available.
  23982. // Aliased as `all`.
  23983. _.every = _.all = function(obj, predicate, context) {
  23984. predicate || (predicate = _.identity);
  23985. var result = true;
  23986. if (obj == null) return result;
  23987. if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
  23988. each(obj, function(value, index, list) {
  23989. if (!(result = result && predicate.call(context, value, index, list))) return breaker;
  23990. });
  23991. return !!result;
  23992. };
  23993. // Determine if at least one element in the object matches a truth test.
  23994. // Delegates to **ECMAScript 5**'s native `some` if available.
  23995. // Aliased as `any`.
  23996. var any = _.some = _.any = function(obj, predicate, context) {
  23997. predicate || (predicate = _.identity);
  23998. var result = false;
  23999. if (obj == null) return result;
  24000. if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
  24001. each(obj, function(value, index, list) {
  24002. if (result || (result = predicate.call(context, value, index, list))) return breaker;
  24003. });
  24004. return !!result;
  24005. };
  24006. // Determine if the array or object contains a given value (using `===`).
  24007. // Aliased as `include`.
  24008. _.contains = _.include = function(obj, target) {
  24009. if (obj == null) return false;
  24010. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  24011. return any(obj, function(value) {
  24012. return value === target;
  24013. });
  24014. };
  24015. // Invoke a method (with arguments) on every item in a collection.
  24016. _.invoke = function(obj, method) {
  24017. var args = slice.call(arguments, 2);
  24018. var isFunc = _.isFunction(method);
  24019. return _.map(obj, function(value) {
  24020. return (isFunc ? method : value[method]).apply(value, args);
  24021. });
  24022. };
  24023. // Convenience version of a common use case of `map`: fetching a property.
  24024. _.pluck = function(obj, key) {
  24025. return _.map(obj, _.property(key));
  24026. };
  24027. // Convenience version of a common use case of `filter`: selecting only objects
  24028. // containing specific `key:value` pairs.
  24029. _.where = function(obj, attrs) {
  24030. return _.filter(obj, _.matches(attrs));
  24031. };
  24032. // Convenience version of a common use case of `find`: getting the first object
  24033. // containing specific `key:value` pairs.
  24034. _.findWhere = function(obj, attrs) {
  24035. return _.find(obj, _.matches(attrs));
  24036. };
  24037. // Return the maximum element or (element-based computation).
  24038. // Can't optimize arrays of integers longer than 65,535 elements.
  24039. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
  24040. _.max = function(obj, iterator, context) {
  24041. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  24042. return Math.max.apply(Math, obj);
  24043. }
  24044. var result = -Infinity, lastComputed = -Infinity;
  24045. each(obj, function(value, index, list) {
  24046. var computed = iterator ? iterator.call(context, value, index, list) : value;
  24047. if (computed > lastComputed) {
  24048. result = value;
  24049. lastComputed = computed;
  24050. }
  24051. });
  24052. return result;
  24053. };
  24054. // Return the minimum element (or element-based computation).
  24055. _.min = function(obj, iterator, context) {
  24056. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  24057. return Math.min.apply(Math, obj);
  24058. }
  24059. var result = Infinity, lastComputed = Infinity;
  24060. each(obj, function(value, index, list) {
  24061. var computed = iterator ? iterator.call(context, value, index, list) : value;
  24062. if (computed < lastComputed) {
  24063. result = value;
  24064. lastComputed = computed;
  24065. }
  24066. });
  24067. return result;
  24068. };
  24069. // Shuffle an array, using the modern version of the
  24070. // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  24071. _.shuffle = function(obj) {
  24072. var rand;
  24073. var index = 0;
  24074. var shuffled = [];
  24075. each(obj, function(value) {
  24076. rand = _.random(index++);
  24077. shuffled[index - 1] = shuffled[rand];
  24078. shuffled[rand] = value;
  24079. });
  24080. return shuffled;
  24081. };
  24082. // Sample **n** random values from a collection.
  24083. // If **n** is not specified, returns a single random element.
  24084. // The internal `guard` argument allows it to work with `map`.
  24085. _.sample = function(obj, n, guard) {
  24086. if (n == null || guard) {
  24087. if (obj.length !== +obj.length) obj = _.values(obj);
  24088. return obj[_.random(obj.length - 1)];
  24089. }
  24090. return _.shuffle(obj).slice(0, Math.max(0, n));
  24091. };
  24092. // An internal function to generate lookup iterators.
  24093. var lookupIterator = function(value) {
  24094. if (value == null) return _.identity;
  24095. if (_.isFunction(value)) return value;
  24096. return _.property(value);
  24097. };
  24098. // Sort the object's values by a criterion produced by an iterator.
  24099. _.sortBy = function(obj, iterator, context) {
  24100. iterator = lookupIterator(iterator);
  24101. return _.pluck(_.map(obj, function(value, index, list) {
  24102. return {
  24103. value: value,
  24104. index: index,
  24105. criteria: iterator.call(context, value, index, list)
  24106. };
  24107. }).sort(function(left, right) {
  24108. var a = left.criteria;
  24109. var b = right.criteria;
  24110. if (a !== b) {
  24111. if (a > b || a === void 0) return 1;
  24112. if (a < b || b === void 0) return -1;
  24113. }
  24114. return left.index - right.index;
  24115. }), 'value');
  24116. };
  24117. // An internal function used for aggregate "group by" operations.
  24118. var group = function(behavior) {
  24119. return function(obj, iterator, context) {
  24120. var result = {};
  24121. iterator = lookupIterator(iterator);
  24122. each(obj, function(value, index) {
  24123. var key = iterator.call(context, value, index, obj);
  24124. behavior(result, key, value);
  24125. });
  24126. return result;
  24127. };
  24128. };
  24129. // Groups the object's values by a criterion. Pass either a string attribute
  24130. // to group by, or a function that returns the criterion.
  24131. _.groupBy = group(function(result, key, value) {
  24132. _.has(result, key) ? result[key].push(value) : result[key] = [value];
  24133. });
  24134. // Indexes the object's values by a criterion, similar to `groupBy`, but for
  24135. // when you know that your index values will be unique.
  24136. _.indexBy = group(function(result, key, value) {
  24137. result[key] = value;
  24138. });
  24139. // Counts instances of an object that group by a certain criterion. Pass
  24140. // either a string attribute to count by, or a function that returns the
  24141. // criterion.
  24142. _.countBy = group(function(result, key) {
  24143. _.has(result, key) ? result[key]++ : result[key] = 1;
  24144. });
  24145. // Use a comparator function to figure out the smallest index at which
  24146. // an object should be inserted so as to maintain order. Uses binary search.
  24147. _.sortedIndex = function(array, obj, iterator, context) {
  24148. iterator = lookupIterator(iterator);
  24149. var value = iterator.call(context, obj);
  24150. var low = 0, high = array.length;
  24151. while (low < high) {
  24152. var mid = (low + high) >>> 1;
  24153. iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
  24154. }
  24155. return low;
  24156. };
  24157. // Safely create a real, live array from anything iterable.
  24158. _.toArray = function(obj) {
  24159. if (!obj) return [];
  24160. if (_.isArray(obj)) return slice.call(obj);
  24161. if (obj.length === +obj.length) return _.map(obj, _.identity);
  24162. return _.values(obj);
  24163. };
  24164. // Return the number of elements in an object.
  24165. _.size = function(obj) {
  24166. if (obj == null) return 0;
  24167. return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  24168. };
  24169. // Array Functions
  24170. // ---------------
  24171. // Get the first element of an array. Passing **n** will return the first N
  24172. // values in the array. Aliased as `head` and `take`. The **guard** check
  24173. // allows it to work with `_.map`.
  24174. _.first = _.head = _.take = function(array, n, guard) {
  24175. if (array == null) return void 0;
  24176. if ((n == null) || guard) return array[0];
  24177. if (n < 0) return [];
  24178. return slice.call(array, 0, n);
  24179. };
  24180. // Returns everything but the last entry of the array. Especially useful on
  24181. // the arguments object. Passing **n** will return all the values in
  24182. // the array, excluding the last N. The **guard** check allows it to work with
  24183. // `_.map`.
  24184. _.initial = function(array, n, guard) {
  24185. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  24186. };
  24187. // Get the last element of an array. Passing **n** will return the last N
  24188. // values in the array. The **guard** check allows it to work with `_.map`.
  24189. _.last = function(array, n, guard) {
  24190. if (array == null) return void 0;
  24191. if ((n == null) || guard) return array[array.length - 1];
  24192. return slice.call(array, Math.max(array.length - n, 0));
  24193. };
  24194. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  24195. // Especially useful on the arguments object. Passing an **n** will return
  24196. // the rest N values in the array. The **guard**
  24197. // check allows it to work with `_.map`.
  24198. _.rest = _.tail = _.drop = function(array, n, guard) {
  24199. return slice.call(array, (n == null) || guard ? 1 : n);
  24200. };
  24201. // Trim out all falsy values from an array.
  24202. _.compact = function(array) {
  24203. return _.filter(array, _.identity);
  24204. };
  24205. // Internal implementation of a recursive `flatten` function.
  24206. var flatten = function(input, shallow, output) {
  24207. if (shallow && _.every(input, _.isArray)) {
  24208. return concat.apply(output, input);
  24209. }
  24210. each(input, function(value) {
  24211. if (_.isArray(value) || _.isArguments(value)) {
  24212. shallow ? push.apply(output, value) : flatten(value, shallow, output);
  24213. } else {
  24214. output.push(value);
  24215. }
  24216. });
  24217. return output;
  24218. };
  24219. // Flatten out an array, either recursively (by default), or just one level.
  24220. _.flatten = function(array, shallow) {
  24221. return flatten(array, shallow, []);
  24222. };
  24223. // Return a version of the array that does not contain the specified value(s).
  24224. _.without = function(array) {
  24225. return _.difference(array, slice.call(arguments, 1));
  24226. };
  24227. // Split an array into two arrays: one whose elements all satisfy the given
  24228. // predicate, and one whose elements all do not satisfy the predicate.
  24229. _.partition = function(array, predicate) {
  24230. var pass = [], fail = [];
  24231. each(array, function(elem) {
  24232. (predicate(elem) ? pass : fail).push(elem);
  24233. });
  24234. return [pass, fail];
  24235. };
  24236. // Produce a duplicate-free version of the array. If the array has already
  24237. // been sorted, you have the option of using a faster algorithm.
  24238. // Aliased as `unique`.
  24239. _.uniq = _.unique = function(array, isSorted, iterator, context) {
  24240. if (_.isFunction(isSorted)) {
  24241. context = iterator;
  24242. iterator = isSorted;
  24243. isSorted = false;
  24244. }
  24245. var initial = iterator ? _.map(array, iterator, context) : array;
  24246. var results = [];
  24247. var seen = [];
  24248. each(initial, function(value, index) {
  24249. if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
  24250. seen.push(value);
  24251. results.push(array[index]);
  24252. }
  24253. });
  24254. return results;
  24255. };
  24256. // Produce an array that contains the union: each distinct element from all of
  24257. // the passed-in arrays.
  24258. _.union = function() {
  24259. return _.uniq(_.flatten(arguments, true));
  24260. };
  24261. // Produce an array that contains every item shared between all the
  24262. // passed-in arrays.
  24263. _.intersection = function(array) {
  24264. var rest = slice.call(arguments, 1);
  24265. return _.filter(_.uniq(array), function(item) {
  24266. return _.every(rest, function(other) {
  24267. return _.contains(other, item);
  24268. });
  24269. });
  24270. };
  24271. // Take the difference between one array and a number of other arrays.
  24272. // Only the elements present in just the first array will remain.
  24273. _.difference = function(array) {
  24274. var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
  24275. return _.filter(array, function(value){ return !_.contains(rest, value); });
  24276. };
  24277. // Zip together multiple lists into a single array -- elements that share
  24278. // an index go together.
  24279. _.zip = function() {
  24280. var length = _.max(_.pluck(arguments, 'length').concat(0));
  24281. var results = new Array(length);
  24282. for (var i = 0; i < length; i++) {
  24283. results[i] = _.pluck(arguments, '' + i);
  24284. }
  24285. return results;
  24286. };
  24287. // Converts lists into objects. Pass either a single array of `[key, value]`
  24288. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  24289. // the corresponding values.
  24290. _.object = function(list, values) {
  24291. if (list == null) return {};
  24292. var result = {};
  24293. for (var i = 0, length = list.length; i < length; i++) {
  24294. if (values) {
  24295. result[list[i]] = values[i];
  24296. } else {
  24297. result[list[i][0]] = list[i][1];
  24298. }
  24299. }
  24300. return result;
  24301. };
  24302. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  24303. // we need this function. Return the position of the first occurrence of an
  24304. // item in an array, or -1 if the item is not included in the array.
  24305. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  24306. // If the array is large and already in sort order, pass `true`
  24307. // for **isSorted** to use binary search.
  24308. _.indexOf = function(array, item, isSorted) {
  24309. if (array == null) return -1;
  24310. var i = 0, length = array.length;
  24311. if (isSorted) {
  24312. if (typeof isSorted == 'number') {
  24313. i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
  24314. } else {
  24315. i = _.sortedIndex(array, item);
  24316. return array[i] === item ? i : -1;
  24317. }
  24318. }
  24319. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
  24320. for (; i < length; i++) if (array[i] === item) return i;
  24321. return -1;
  24322. };
  24323. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  24324. _.lastIndexOf = function(array, item, from) {
  24325. if (array == null) return -1;
  24326. var hasIndex = from != null;
  24327. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
  24328. return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
  24329. }
  24330. var i = (hasIndex ? from : array.length);
  24331. while (i--) if (array[i] === item) return i;
  24332. return -1;
  24333. };
  24334. // Generate an integer Array containing an arithmetic progression. A port of
  24335. // the native Python `range()` function. See
  24336. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  24337. _.range = function(start, stop, step) {
  24338. if (arguments.length <= 1) {
  24339. stop = start || 0;
  24340. start = 0;
  24341. }
  24342. step = arguments[2] || 1;
  24343. var length = Math.max(Math.ceil((stop - start) / step), 0);
  24344. var idx = 0;
  24345. var range = new Array(length);
  24346. while(idx < length) {
  24347. range[idx++] = start;
  24348. start += step;
  24349. }
  24350. return range;
  24351. };
  24352. // Function (ahem) Functions
  24353. // ------------------
  24354. // Reusable constructor function for prototype setting.
  24355. var ctor = function(){};
  24356. // Create a function bound to a given object (assigning `this`, and arguments,
  24357. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  24358. // available.
  24359. _.bind = function(func, context) {
  24360. var args, bound;
  24361. if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  24362. if (!_.isFunction(func)) throw new TypeError;
  24363. args = slice.call(arguments, 2);
  24364. return bound = function() {
  24365. if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
  24366. ctor.prototype = func.prototype;
  24367. var self = new ctor;
  24368. ctor.prototype = null;
  24369. var result = func.apply(self, args.concat(slice.call(arguments)));
  24370. if (Object(result) === result) return result;
  24371. return self;
  24372. };
  24373. };
  24374. // Partially apply a function by creating a version that has had some of its
  24375. // arguments pre-filled, without changing its dynamic `this` context. _ acts
  24376. // as a placeholder, allowing any combination of arguments to be pre-filled.
  24377. _.partial = function(func) {
  24378. var boundArgs = slice.call(arguments, 1);
  24379. return function() {
  24380. var position = 0;
  24381. var args = boundArgs.slice();
  24382. for (var i = 0, length = args.length; i < length; i++) {
  24383. if (args[i] === _) args[i] = arguments[position++];
  24384. }
  24385. while (position < arguments.length) args.push(arguments[position++]);
  24386. return func.apply(this, args);
  24387. };
  24388. };
  24389. // Bind a number of an object's methods to that object. Remaining arguments
  24390. // are the method names to be bound. Useful for ensuring that all callbacks
  24391. // defined on an object belong to it.
  24392. _.bindAll = function(obj) {
  24393. var funcs = slice.call(arguments, 1);
  24394. if (funcs.length === 0) throw new Error('bindAll must be passed function names');
  24395. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  24396. return obj;
  24397. };
  24398. // Memoize an expensive function by storing its results.
  24399. _.memoize = function(func, hasher) {
  24400. var memo = {};
  24401. hasher || (hasher = _.identity);
  24402. return function() {
  24403. var key = hasher.apply(this, arguments);
  24404. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  24405. };
  24406. };
  24407. // Delays a function for the given number of milliseconds, and then calls
  24408. // it with the arguments supplied.
  24409. _.delay = function(func, wait) {
  24410. var args = slice.call(arguments, 2);
  24411. return setTimeout(function(){ return func.apply(null, args); }, wait);
  24412. };
  24413. // Defers a function, scheduling it to run after the current call stack has
  24414. // cleared.
  24415. _.defer = function(func) {
  24416. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  24417. };
  24418. // Returns a function, that, when invoked, will only be triggered at most once
  24419. // during a given window of time. Normally, the throttled function will run
  24420. // as much as it can, without ever going more than once per `wait` duration;
  24421. // but if you'd like to disable the execution on the leading edge, pass
  24422. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  24423. _.throttle = function(func, wait, options) {
  24424. var context, args, result;
  24425. var timeout = null;
  24426. var previous = 0;
  24427. options || (options = {});
  24428. var later = function() {
  24429. previous = options.leading === false ? 0 : _.now();
  24430. timeout = null;
  24431. result = func.apply(context, args);
  24432. context = args = null;
  24433. };
  24434. return function() {
  24435. var now = _.now();
  24436. if (!previous && options.leading === false) previous = now;
  24437. var remaining = wait - (now - previous);
  24438. context = this;
  24439. args = arguments;
  24440. if (remaining <= 0) {
  24441. clearTimeout(timeout);
  24442. timeout = null;
  24443. previous = now;
  24444. result = func.apply(context, args);
  24445. context = args = null;
  24446. } else if (!timeout && options.trailing !== false) {
  24447. timeout = setTimeout(later, remaining);
  24448. }
  24449. return result;
  24450. };
  24451. };
  24452. // Returns a function, that, as long as it continues to be invoked, will not
  24453. // be triggered. The function will be called after it stops being called for
  24454. // N milliseconds. If `immediate` is passed, trigger the function on the
  24455. // leading edge, instead of the trailing.
  24456. _.debounce = function(func, wait, immediate) {
  24457. var timeout, args, context, timestamp, result;
  24458. var later = function() {
  24459. var last = _.now() - timestamp;
  24460. if (last < wait) {
  24461. timeout = setTimeout(later, wait - last);
  24462. } else {
  24463. timeout = null;
  24464. if (!immediate) {
  24465. result = func.apply(context, args);
  24466. context = args = null;
  24467. }
  24468. }
  24469. };
  24470. return function() {
  24471. context = this;
  24472. args = arguments;
  24473. timestamp = _.now();
  24474. var callNow = immediate && !timeout;
  24475. if (!timeout) {
  24476. timeout = setTimeout(later, wait);
  24477. }
  24478. if (callNow) {
  24479. result = func.apply(context, args);
  24480. context = args = null;
  24481. }
  24482. return result;
  24483. };
  24484. };
  24485. // Returns a function that will be executed at most one time, no matter how
  24486. // often you call it. Useful for lazy initialization.
  24487. _.once = function(func) {
  24488. var ran = false, memo;
  24489. return function() {
  24490. if (ran) return memo;
  24491. ran = true;
  24492. memo = func.apply(this, arguments);
  24493. func = null;
  24494. return memo;
  24495. };
  24496. };
  24497. // Returns the first function passed as an argument to the second,
  24498. // allowing you to adjust arguments, run code before and after, and
  24499. // conditionally execute the original function.
  24500. _.wrap = function(func, wrapper) {
  24501. return _.partial(wrapper, func);
  24502. };
  24503. // Returns a function that is the composition of a list of functions, each
  24504. // consuming the return value of the function that follows.
  24505. _.compose = function() {
  24506. var funcs = arguments;
  24507. return function() {
  24508. var args = arguments;
  24509. for (var i = funcs.length - 1; i >= 0; i--) {
  24510. args = [funcs[i].apply(this, args)];
  24511. }
  24512. return args[0];
  24513. };
  24514. };
  24515. // Returns a function that will only be executed after being called N times.
  24516. _.after = function(times, func) {
  24517. return function() {
  24518. if (--times < 1) {
  24519. return func.apply(this, arguments);
  24520. }
  24521. };
  24522. };
  24523. // Object Functions
  24524. // ----------------
  24525. // Retrieve the names of an object's properties.
  24526. // Delegates to **ECMAScript 5**'s native `Object.keys`
  24527. _.keys = function(obj) {
  24528. if (!_.isObject(obj)) return [];
  24529. if (nativeKeys) return nativeKeys(obj);
  24530. var keys = [];
  24531. for (var key in obj) if (_.has(obj, key)) keys.push(key);
  24532. return keys;
  24533. };
  24534. // Retrieve the values of an object's properties.
  24535. _.values = function(obj) {
  24536. var keys = _.keys(obj);
  24537. var length = keys.length;
  24538. var values = new Array(length);
  24539. for (var i = 0; i < length; i++) {
  24540. values[i] = obj[keys[i]];
  24541. }
  24542. return values;
  24543. };
  24544. // Convert an object into a list of `[key, value]` pairs.
  24545. _.pairs = function(obj) {
  24546. var keys = _.keys(obj);
  24547. var length = keys.length;
  24548. var pairs = new Array(length);
  24549. for (var i = 0; i < length; i++) {
  24550. pairs[i] = [keys[i], obj[keys[i]]];
  24551. }
  24552. return pairs;
  24553. };
  24554. // Invert the keys and values of an object. The values must be serializable.
  24555. _.invert = function(obj) {
  24556. var result = {};
  24557. var keys = _.keys(obj);
  24558. for (var i = 0, length = keys.length; i < length; i++) {
  24559. result[obj[keys[i]]] = keys[i];
  24560. }
  24561. return result;
  24562. };
  24563. // Return a sorted list of the function names available on the object.
  24564. // Aliased as `methods`
  24565. _.functions = _.methods = function(obj) {
  24566. var names = [];
  24567. for (var key in obj) {
  24568. if (_.isFunction(obj[key])) names.push(key);
  24569. }
  24570. return names.sort();
  24571. };
  24572. // Extend a given object with all the properties in passed-in object(s).
  24573. _.extend = function(obj) {
  24574. each(slice.call(arguments, 1), function(source) {
  24575. if (source) {
  24576. for (var prop in source) {
  24577. obj[prop] = source[prop];
  24578. }
  24579. }
  24580. });
  24581. return obj;
  24582. };
  24583. // Return a copy of the object only containing the whitelisted properties.
  24584. _.pick = function(obj) {
  24585. var copy = {};
  24586. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  24587. each(keys, function(key) {
  24588. if (key in obj) copy[key] = obj[key];
  24589. });
  24590. return copy;
  24591. };
  24592. // Return a copy of the object without the blacklisted properties.
  24593. _.omit = function(obj) {
  24594. var copy = {};
  24595. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  24596. for (var key in obj) {
  24597. if (!_.contains(keys, key)) copy[key] = obj[key];
  24598. }
  24599. return copy;
  24600. };
  24601. // Fill in a given object with default properties.
  24602. _.defaults = function(obj) {
  24603. each(slice.call(arguments, 1), function(source) {
  24604. if (source) {
  24605. for (var prop in source) {
  24606. if (obj[prop] === void 0) obj[prop] = source[prop];
  24607. }
  24608. }
  24609. });
  24610. return obj;
  24611. };
  24612. // Create a (shallow-cloned) duplicate of an object.
  24613. _.clone = function(obj) {
  24614. if (!_.isObject(obj)) return obj;
  24615. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  24616. };
  24617. // Invokes interceptor with the obj, and then returns obj.
  24618. // The primary purpose of this method is to "tap into" a method chain, in
  24619. // order to perform operations on intermediate results within the chain.
  24620. _.tap = function(obj, interceptor) {
  24621. interceptor(obj);
  24622. return obj;
  24623. };
  24624. // Internal recursive comparison function for `isEqual`.
  24625. var eq = function(a, b, aStack, bStack) {
  24626. // Identical objects are equal. `0 === -0`, but they aren't identical.
  24627. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
  24628. if (a === b) return a !== 0 || 1 / a == 1 / b;
  24629. // A strict comparison is necessary because `null == undefined`.
  24630. if (a == null || b == null) return a === b;
  24631. // Unwrap any wrapped objects.
  24632. if (a instanceof _) a = a._wrapped;
  24633. if (b instanceof _) b = b._wrapped;
  24634. // Compare `[[Class]]` names.
  24635. var className = toString.call(a);
  24636. if (className != toString.call(b)) return false;
  24637. switch (className) {
  24638. // Strings, numbers, dates, and booleans are compared by value.
  24639. case '[object String]':
  24640. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  24641. // equivalent to `new String("5")`.
  24642. return a == String(b);
  24643. case '[object Number]':
  24644. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  24645. // other numeric values.
  24646. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  24647. case '[object Date]':
  24648. case '[object Boolean]':
  24649. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  24650. // millisecond representations. Note that invalid dates with millisecond representations
  24651. // of `NaN` are not equivalent.
  24652. return +a == +b;
  24653. // RegExps are compared by their source patterns and flags.
  24654. case '[object RegExp]':
  24655. return a.source == b.source &&
  24656. a.global == b.global &&
  24657. a.multiline == b.multiline &&
  24658. a.ignoreCase == b.ignoreCase;
  24659. }
  24660. if (typeof a != 'object' || typeof b != 'object') return false;
  24661. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  24662. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  24663. var length = aStack.length;
  24664. while (length--) {
  24665. // Linear search. Performance is inversely proportional to the number of
  24666. // unique nested structures.
  24667. if (aStack[length] == a) return bStack[length] == b;
  24668. }
  24669. // Objects with different constructors are not equivalent, but `Object`s
  24670. // from different frames are.
  24671. var aCtor = a.constructor, bCtor = b.constructor;
  24672. if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
  24673. _.isFunction(bCtor) && (bCtor instanceof bCtor))
  24674. && ('constructor' in a && 'constructor' in b)) {
  24675. return false;
  24676. }
  24677. // Add the first object to the stack of traversed objects.
  24678. aStack.push(a);
  24679. bStack.push(b);
  24680. var size = 0, result = true;
  24681. // Recursively compare objects and arrays.
  24682. if (className == '[object Array]') {
  24683. // Compare array lengths to determine if a deep comparison is necessary.
  24684. size = a.length;
  24685. result = size == b.length;
  24686. if (result) {
  24687. // Deep compare the contents, ignoring non-numeric properties.
  24688. while (size--) {
  24689. if (!(result = eq(a[size], b[size], aStack, bStack))) break;
  24690. }
  24691. }
  24692. } else {
  24693. // Deep compare objects.
  24694. for (var key in a) {
  24695. if (_.has(a, key)) {
  24696. // Count the expected number of properties.
  24697. size++;
  24698. // Deep compare each member.
  24699. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
  24700. }
  24701. }
  24702. // Ensure that both objects contain the same number of properties.
  24703. if (result) {
  24704. for (key in b) {
  24705. if (_.has(b, key) && !(size--)) break;
  24706. }
  24707. result = !size;
  24708. }
  24709. }
  24710. // Remove the first object from the stack of traversed objects.
  24711. aStack.pop();
  24712. bStack.pop();
  24713. return result;
  24714. };
  24715. // Perform a deep comparison to check if two objects are equal.
  24716. _.isEqual = function(a, b) {
  24717. return eq(a, b, [], []);
  24718. };
  24719. // Is a given array, string, or object empty?
  24720. // An "empty" object has no enumerable own-properties.
  24721. _.isEmpty = function(obj) {
  24722. if (obj == null) return true;
  24723. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  24724. for (var key in obj) if (_.has(obj, key)) return false;
  24725. return true;
  24726. };
  24727. // Is a given value a DOM element?
  24728. _.isElement = function(obj) {
  24729. return !!(obj && obj.nodeType === 1);
  24730. };
  24731. // Is a given value an array?
  24732. // Delegates to ECMA5's native Array.isArray
  24733. _.isArray = nativeIsArray || function(obj) {
  24734. return toString.call(obj) == '[object Array]';
  24735. };
  24736. // Is a given variable an object?
  24737. _.isObject = function(obj) {
  24738. return obj === Object(obj);
  24739. };
  24740. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  24741. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
  24742. _['is' + name] = function(obj) {
  24743. return toString.call(obj) == '[object ' + name + ']';
  24744. };
  24745. });
  24746. // Define a fallback version of the method in browsers (ahem, IE), where
  24747. // there isn't any inspectable "Arguments" type.
  24748. if (!_.isArguments(arguments)) {
  24749. _.isArguments = function(obj) {
  24750. return !!(obj && _.has(obj, 'callee'));
  24751. };
  24752. }
  24753. // Optimize `isFunction` if appropriate.
  24754. if (typeof (/./) !== 'function') {
  24755. _.isFunction = function(obj) {
  24756. return typeof obj === 'function';
  24757. };
  24758. }
  24759. // Is a given object a finite number?
  24760. _.isFinite = function(obj) {
  24761. return isFinite(obj) && !isNaN(parseFloat(obj));
  24762. };
  24763. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  24764. _.isNaN = function(obj) {
  24765. return _.isNumber(obj) && obj != +obj;
  24766. };
  24767. // Is a given value a boolean?
  24768. _.isBoolean = function(obj) {
  24769. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  24770. };
  24771. // Is a given value equal to null?
  24772. _.isNull = function(obj) {
  24773. return obj === null;
  24774. };
  24775. // Is a given variable undefined?
  24776. _.isUndefined = function(obj) {
  24777. return obj === void 0;
  24778. };
  24779. // Shortcut function for checking if an object has a given property directly
  24780. // on itself (in other words, not on a prototype).
  24781. _.has = function(obj, key) {
  24782. return hasOwnProperty.call(obj, key);
  24783. };
  24784. // Utility Functions
  24785. // -----------------
  24786. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  24787. // previous owner. Returns a reference to the Underscore object.
  24788. _.noConflict = function() {
  24789. root._ = previousUnderscore;
  24790. return this;
  24791. };
  24792. // Keep the identity function around for default iterators.
  24793. _.identity = function(value) {
  24794. return value;
  24795. };
  24796. _.constant = function(value) {
  24797. return function () {
  24798. return value;
  24799. };
  24800. };
  24801. _.property = function(key) {
  24802. return function(obj) {
  24803. return obj[key];
  24804. };
  24805. };
  24806. // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
  24807. _.matches = function(attrs) {
  24808. return function(obj) {
  24809. if (obj === attrs) return true; //avoid comparing an object to itself.
  24810. for (var key in attrs) {
  24811. if (attrs[key] !== obj[key])
  24812. return false;
  24813. }
  24814. return true;
  24815. }
  24816. };
  24817. // Run a function **n** times.
  24818. _.times = function(n, iterator, context) {
  24819. var accum = Array(Math.max(0, n));
  24820. for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
  24821. return accum;
  24822. };
  24823. // Return a random integer between min and max (inclusive).
  24824. _.random = function(min, max) {
  24825. if (max == null) {
  24826. max = min;
  24827. min = 0;
  24828. }
  24829. return min + Math.floor(Math.random() * (max - min + 1));
  24830. };
  24831. // A (possibly faster) way to get the current timestamp as an integer.
  24832. _.now = Date.now || function() { return new Date().getTime(); };
  24833. // List of HTML entities for escaping.
  24834. var entityMap = {
  24835. escape: {
  24836. '&': '&amp;',
  24837. '<': '&lt;',
  24838. '>': '&gt;',
  24839. '"': '&quot;',
  24840. "'": '&#x27;'
  24841. }
  24842. };
  24843. entityMap.unescape = _.invert(entityMap.escape);
  24844. // Regexes containing the keys and values listed immediately above.
  24845. var entityRegexes = {
  24846. escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  24847. unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  24848. };
  24849. // Functions for escaping and unescaping strings to/from HTML interpolation.
  24850. _.each(['escape', 'unescape'], function(method) {
  24851. _[method] = function(string) {
  24852. if (string == null) return '';
  24853. return ('' + string).replace(entityRegexes[method], function(match) {
  24854. return entityMap[method][match];
  24855. });
  24856. };
  24857. });
  24858. // If the value of the named `property` is a function then invoke it with the
  24859. // `object` as context; otherwise, return it.
  24860. _.result = function(object, property) {
  24861. if (object == null) return void 0;
  24862. var value = object[property];
  24863. return _.isFunction(value) ? value.call(object) : value;
  24864. };
  24865. // Add your own custom functions to the Underscore object.
  24866. _.mixin = function(obj) {
  24867. each(_.functions(obj), function(name) {
  24868. var func = _[name] = obj[name];
  24869. _.prototype[name] = function() {
  24870. var args = [this._wrapped];
  24871. push.apply(args, arguments);
  24872. return result.call(this, func.apply(_, args));
  24873. };
  24874. });
  24875. };
  24876. // Generate a unique integer id (unique within the entire client session).
  24877. // Useful for temporary DOM ids.
  24878. var idCounter = 0;
  24879. _.uniqueId = function(prefix) {
  24880. var id = ++idCounter + '';
  24881. return prefix ? prefix + id : id;
  24882. };
  24883. // By default, Underscore uses ERB-style template delimiters, change the
  24884. // following template settings to use alternative delimiters.
  24885. _.templateSettings = {
  24886. evaluate : /<%([\s\S]+?)%>/g,
  24887. interpolate : /<%=([\s\S]+?)%>/g,
  24888. escape : /<%-([\s\S]+?)%>/g
  24889. };
  24890. // When customizing `templateSettings`, if you don't want to define an
  24891. // interpolation, evaluation or escaping regex, we need one that is
  24892. // guaranteed not to match.
  24893. var noMatch = /(.)^/;
  24894. // Certain characters need to be escaped so that they can be put into a
  24895. // string literal.
  24896. var escapes = {
  24897. "'": "'",
  24898. '\\': '\\',
  24899. '\r': 'r',
  24900. '\n': 'n',
  24901. '\t': 't',
  24902. '\u2028': 'u2028',
  24903. '\u2029': 'u2029'
  24904. };
  24905. var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  24906. // JavaScript micro-templating, similar to John Resig's implementation.
  24907. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  24908. // and correctly escapes quotes within interpolated code.
  24909. _.template = function(text, data, settings) {
  24910. var render;
  24911. settings = _.defaults({}, settings, _.templateSettings);
  24912. // Combine delimiters into one regular expression via alternation.
  24913. var matcher = new RegExp([
  24914. (settings.escape || noMatch).source,
  24915. (settings.interpolate || noMatch).source,
  24916. (settings.evaluate || noMatch).source
  24917. ].join('|') + '|$', 'g');
  24918. // Compile the template source, escaping string literals appropriately.
  24919. var index = 0;
  24920. var source = "__p+='";
  24921. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  24922. source += text.slice(index, offset)
  24923. .replace(escaper, function(match) { return '\\' + escapes[match]; });
  24924. if (escape) {
  24925. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  24926. }
  24927. if (interpolate) {
  24928. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  24929. }
  24930. if (evaluate) {
  24931. source += "';\n" + evaluate + "\n__p+='";
  24932. }
  24933. index = offset + match.length;
  24934. return match;
  24935. });
  24936. source += "';\n";
  24937. // If a variable is not specified, place data values in local scope.
  24938. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  24939. source = "var __t,__p='',__j=Array.prototype.join," +
  24940. "print=function(){__p+=__j.call(arguments,'');};\n" +
  24941. source + "return __p;\n";
  24942. try {
  24943. render = new Function(settings.variable || 'obj', '_', source);
  24944. } catch (e) {
  24945. e.source = source;
  24946. throw e;
  24947. }
  24948. if (data) return render(data, _);
  24949. var template = function(data) {
  24950. return render.call(this, data, _);
  24951. };
  24952. // Provide the compiled function source as a convenience for precompilation.
  24953. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
  24954. return template;
  24955. };
  24956. // Add a "chain" function, which will delegate to the wrapper.
  24957. _.chain = function(obj) {
  24958. return _(obj).chain();
  24959. };
  24960. // OOP
  24961. // ---------------
  24962. // If Underscore is called as a function, it returns a wrapped object that
  24963. // can be used OO-style. This wrapper holds altered versions of all the
  24964. // underscore functions. Wrapped objects may be chained.
  24965. // Helper function to continue chaining intermediate results.
  24966. var result = function(obj) {
  24967. return this._chain ? _(obj).chain() : obj;
  24968. };
  24969. // Add all of the Underscore functions to the wrapper object.
  24970. _.mixin(_);
  24971. // Add all mutator Array functions to the wrapper.
  24972. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  24973. var method = ArrayProto[name];
  24974. _.prototype[name] = function() {
  24975. var obj = this._wrapped;
  24976. method.apply(obj, arguments);
  24977. if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
  24978. return result.call(this, obj);
  24979. };
  24980. });
  24981. // Add all accessor Array functions to the wrapper.
  24982. each(['concat', 'join', 'slice'], function(name) {
  24983. var method = ArrayProto[name];
  24984. _.prototype[name] = function() {
  24985. return result.call(this, method.apply(this._wrapped, arguments));
  24986. };
  24987. });
  24988. _.extend(_.prototype, {
  24989. // Start chaining a wrapped Underscore object.
  24990. chain: function() {
  24991. this._chain = true;
  24992. return this;
  24993. },
  24994. // Extracts the result from a wrapped and chained object.
  24995. value: function() {
  24996. return this._wrapped;
  24997. }
  24998. });
  24999. // AMD registration happens at the end for compatibility with AMD loaders
  25000. // that may not enforce next-turn semantics on modules. Even though general
  25001. // practice for AMD registration is to be anonymous, underscore registers
  25002. // as a named module because, like jQuery, it is a base library that is
  25003. // popular enough to be bundled in a third party lib, but not be part of
  25004. // an AMD load request. Those cases could generate an error when an
  25005. // anonymous define() is called outside of a loader request.
  25006. if (typeof define === 'function' && define.amd) {
  25007. define('underscore', [], function() {
  25008. return _;
  25009. });
  25010. }
  25011. }).call(this);
  25012. },{}],155:[function(require,module,exports){
  25013. // Generated by CoffeeScript 1.9.1
  25014. (function() {
  25015. var XMLAttribute, create;
  25016. create = require('lodash/object/create');
  25017. module.exports = XMLAttribute = (function() {
  25018. function XMLAttribute(parent, name, value) {
  25019. this.stringify = parent.stringify;
  25020. if (name == null) {
  25021. throw new Error("Missing attribute name of element " + parent.name);
  25022. }
  25023. if (value == null) {
  25024. throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name);
  25025. }
  25026. this.name = this.stringify.attName(name);
  25027. this.value = this.stringify.attValue(value);
  25028. }
  25029. XMLAttribute.prototype.clone = function() {
  25030. return create(XMLAttribute.prototype, this);
  25031. };
  25032. XMLAttribute.prototype.toString = function(options, level) {
  25033. return ' ' + this.name + '="' + this.value + '"';
  25034. };
  25035. return XMLAttribute;
  25036. })();
  25037. }).call(this);
  25038. },{"lodash/object/create":225}],156:[function(require,module,exports){
  25039. // Generated by CoffeeScript 1.9.1
  25040. (function() {
  25041. var XMLBuilder, XMLDeclaration, XMLDocType, XMLElement, XMLStringifier;
  25042. XMLStringifier = require('./XMLStringifier');
  25043. XMLDeclaration = require('./XMLDeclaration');
  25044. XMLDocType = require('./XMLDocType');
  25045. XMLElement = require('./XMLElement');
  25046. module.exports = XMLBuilder = (function() {
  25047. function XMLBuilder(name, options) {
  25048. var root, temp;
  25049. if (name == null) {
  25050. throw new Error("Root element needs a name");
  25051. }
  25052. if (options == null) {
  25053. options = {};
  25054. }
  25055. this.options = options;
  25056. this.stringify = new XMLStringifier(options);
  25057. temp = new XMLElement(this, 'doc');
  25058. root = temp.element(name);
  25059. root.isRoot = true;
  25060. root.documentObject = this;
  25061. this.rootObject = root;
  25062. if (!options.headless) {
  25063. root.declaration(options);
  25064. if ((options.pubID != null) || (options.sysID != null)) {
  25065. root.doctype(options);
  25066. }
  25067. }
  25068. }
  25069. XMLBuilder.prototype.root = function() {
  25070. return this.rootObject;
  25071. };
  25072. XMLBuilder.prototype.end = function(options) {
  25073. return this.toString(options);
  25074. };
  25075. XMLBuilder.prototype.toString = function(options) {
  25076. var indent, newline, offset, pretty, r, ref, ref1, ref2;
  25077. pretty = (options != null ? options.pretty : void 0) || false;
  25078. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25079. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25080. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25081. r = '';
  25082. if (this.xmldec != null) {
  25083. r += this.xmldec.toString(options);
  25084. }
  25085. if (this.doctype != null) {
  25086. r += this.doctype.toString(options);
  25087. }
  25088. r += this.rootObject.toString(options);
  25089. if (pretty && r.slice(-newline.length) === newline) {
  25090. r = r.slice(0, -newline.length);
  25091. }
  25092. return r;
  25093. };
  25094. return XMLBuilder;
  25095. })();
  25096. }).call(this);
  25097. },{"./XMLDeclaration":163,"./XMLDocType":164,"./XMLElement":165,"./XMLStringifier":169}],157:[function(require,module,exports){
  25098. // Generated by CoffeeScript 1.9.1
  25099. (function() {
  25100. var XMLCData, XMLNode, create,
  25101. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  25102. hasProp = {}.hasOwnProperty;
  25103. create = require('lodash/object/create');
  25104. XMLNode = require('./XMLNode');
  25105. module.exports = XMLCData = (function(superClass) {
  25106. extend(XMLCData, superClass);
  25107. function XMLCData(parent, text) {
  25108. XMLCData.__super__.constructor.call(this, parent);
  25109. if (text == null) {
  25110. throw new Error("Missing CDATA text");
  25111. }
  25112. this.text = this.stringify.cdata(text);
  25113. }
  25114. XMLCData.prototype.clone = function() {
  25115. return create(XMLCData.prototype, this);
  25116. };
  25117. XMLCData.prototype.toString = function(options, level) {
  25118. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25119. pretty = (options != null ? options.pretty : void 0) || false;
  25120. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25121. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25122. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25123. level || (level = 0);
  25124. space = new Array(level + offset + 1).join(indent);
  25125. r = '';
  25126. if (pretty) {
  25127. r += space;
  25128. }
  25129. r += '<![CDATA[' + this.text + ']]>';
  25130. if (pretty) {
  25131. r += newline;
  25132. }
  25133. return r;
  25134. };
  25135. return XMLCData;
  25136. })(XMLNode);
  25137. }).call(this);
  25138. },{"./XMLNode":166,"lodash/object/create":225}],158:[function(require,module,exports){
  25139. // Generated by CoffeeScript 1.9.1
  25140. (function() {
  25141. var XMLComment, XMLNode, create,
  25142. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  25143. hasProp = {}.hasOwnProperty;
  25144. create = require('lodash/object/create');
  25145. XMLNode = require('./XMLNode');
  25146. module.exports = XMLComment = (function(superClass) {
  25147. extend(XMLComment, superClass);
  25148. function XMLComment(parent, text) {
  25149. XMLComment.__super__.constructor.call(this, parent);
  25150. if (text == null) {
  25151. throw new Error("Missing comment text");
  25152. }
  25153. this.text = this.stringify.comment(text);
  25154. }
  25155. XMLComment.prototype.clone = function() {
  25156. return create(XMLComment.prototype, this);
  25157. };
  25158. XMLComment.prototype.toString = function(options, level) {
  25159. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25160. pretty = (options != null ? options.pretty : void 0) || false;
  25161. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25162. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25163. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25164. level || (level = 0);
  25165. space = new Array(level + offset + 1).join(indent);
  25166. r = '';
  25167. if (pretty) {
  25168. r += space;
  25169. }
  25170. r += '<!-- ' + this.text + ' -->';
  25171. if (pretty) {
  25172. r += newline;
  25173. }
  25174. return r;
  25175. };
  25176. return XMLComment;
  25177. })(XMLNode);
  25178. }).call(this);
  25179. },{"./XMLNode":166,"lodash/object/create":225}],159:[function(require,module,exports){
  25180. // Generated by CoffeeScript 1.9.1
  25181. (function() {
  25182. var XMLDTDAttList, create;
  25183. create = require('lodash/object/create');
  25184. module.exports = XMLDTDAttList = (function() {
  25185. function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  25186. this.stringify = parent.stringify;
  25187. if (elementName == null) {
  25188. throw new Error("Missing DTD element name");
  25189. }
  25190. if (attributeName == null) {
  25191. throw new Error("Missing DTD attribute name");
  25192. }
  25193. if (!attributeType) {
  25194. throw new Error("Missing DTD attribute type");
  25195. }
  25196. if (!defaultValueType) {
  25197. throw new Error("Missing DTD attribute default");
  25198. }
  25199. if (defaultValueType.indexOf('#') !== 0) {
  25200. defaultValueType = '#' + defaultValueType;
  25201. }
  25202. if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
  25203. throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT");
  25204. }
  25205. if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
  25206. throw new Error("Default value only applies to #FIXED or #DEFAULT");
  25207. }
  25208. this.elementName = this.stringify.eleName(elementName);
  25209. this.attributeName = this.stringify.attName(attributeName);
  25210. this.attributeType = this.stringify.dtdAttType(attributeType);
  25211. this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
  25212. this.defaultValueType = defaultValueType;
  25213. }
  25214. XMLDTDAttList.prototype.clone = function() {
  25215. return create(XMLDTDAttList.prototype, this);
  25216. };
  25217. XMLDTDAttList.prototype.toString = function(options, level) {
  25218. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25219. pretty = (options != null ? options.pretty : void 0) || false;
  25220. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25221. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25222. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25223. level || (level = 0);
  25224. space = new Array(level + offset + 1).join(indent);
  25225. r = '';
  25226. if (pretty) {
  25227. r += space;
  25228. }
  25229. r += '<!ATTLIST ' + this.elementName + ' ' + this.attributeName + ' ' + this.attributeType;
  25230. if (this.defaultValueType !== '#DEFAULT') {
  25231. r += ' ' + this.defaultValueType;
  25232. }
  25233. if (this.defaultValue) {
  25234. r += ' "' + this.defaultValue + '"';
  25235. }
  25236. r += '>';
  25237. if (pretty) {
  25238. r += newline;
  25239. }
  25240. return r;
  25241. };
  25242. return XMLDTDAttList;
  25243. })();
  25244. }).call(this);
  25245. },{"lodash/object/create":225}],160:[function(require,module,exports){
  25246. // Generated by CoffeeScript 1.9.1
  25247. (function() {
  25248. var XMLDTDElement, create;
  25249. create = require('lodash/object/create');
  25250. module.exports = XMLDTDElement = (function() {
  25251. function XMLDTDElement(parent, name, value) {
  25252. this.stringify = parent.stringify;
  25253. if (name == null) {
  25254. throw new Error("Missing DTD element name");
  25255. }
  25256. if (!value) {
  25257. value = '(#PCDATA)';
  25258. }
  25259. if (Array.isArray(value)) {
  25260. value = '(' + value.join(',') + ')';
  25261. }
  25262. this.name = this.stringify.eleName(name);
  25263. this.value = this.stringify.dtdElementValue(value);
  25264. }
  25265. XMLDTDElement.prototype.clone = function() {
  25266. return create(XMLDTDElement.prototype, this);
  25267. };
  25268. XMLDTDElement.prototype.toString = function(options, level) {
  25269. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25270. pretty = (options != null ? options.pretty : void 0) || false;
  25271. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25272. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25273. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25274. level || (level = 0);
  25275. space = new Array(level + offset + 1).join(indent);
  25276. r = '';
  25277. if (pretty) {
  25278. r += space;
  25279. }
  25280. r += '<!ELEMENT ' + this.name + ' ' + this.value + '>';
  25281. if (pretty) {
  25282. r += newline;
  25283. }
  25284. return r;
  25285. };
  25286. return XMLDTDElement;
  25287. })();
  25288. }).call(this);
  25289. },{"lodash/object/create":225}],161:[function(require,module,exports){
  25290. // Generated by CoffeeScript 1.9.1
  25291. (function() {
  25292. var XMLDTDEntity, create, isObject;
  25293. create = require('lodash/object/create');
  25294. isObject = require('lodash/lang/isObject');
  25295. module.exports = XMLDTDEntity = (function() {
  25296. function XMLDTDEntity(parent, pe, name, value) {
  25297. this.stringify = parent.stringify;
  25298. if (name == null) {
  25299. throw new Error("Missing entity name");
  25300. }
  25301. if (value == null) {
  25302. throw new Error("Missing entity value");
  25303. }
  25304. this.pe = !!pe;
  25305. this.name = this.stringify.eleName(name);
  25306. if (!isObject(value)) {
  25307. this.value = this.stringify.dtdEntityValue(value);
  25308. } else {
  25309. if (!value.pubID && !value.sysID) {
  25310. throw new Error("Public and/or system identifiers are required for an external entity");
  25311. }
  25312. if (value.pubID && !value.sysID) {
  25313. throw new Error("System identifier is required for a public external entity");
  25314. }
  25315. if (value.pubID != null) {
  25316. this.pubID = this.stringify.dtdPubID(value.pubID);
  25317. }
  25318. if (value.sysID != null) {
  25319. this.sysID = this.stringify.dtdSysID(value.sysID);
  25320. }
  25321. if (value.nData != null) {
  25322. this.nData = this.stringify.dtdNData(value.nData);
  25323. }
  25324. if (this.pe && this.nData) {
  25325. throw new Error("Notation declaration is not allowed in a parameter entity");
  25326. }
  25327. }
  25328. }
  25329. XMLDTDEntity.prototype.clone = function() {
  25330. return create(XMLDTDEntity.prototype, this);
  25331. };
  25332. XMLDTDEntity.prototype.toString = function(options, level) {
  25333. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25334. pretty = (options != null ? options.pretty : void 0) || false;
  25335. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25336. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25337. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25338. level || (level = 0);
  25339. space = new Array(level + offset + 1).join(indent);
  25340. r = '';
  25341. if (pretty) {
  25342. r += space;
  25343. }
  25344. r += '<!ENTITY';
  25345. if (this.pe) {
  25346. r += ' %';
  25347. }
  25348. r += ' ' + this.name;
  25349. if (this.value) {
  25350. r += ' "' + this.value + '"';
  25351. } else {
  25352. if (this.pubID && this.sysID) {
  25353. r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
  25354. } else if (this.sysID) {
  25355. r += ' SYSTEM "' + this.sysID + '"';
  25356. }
  25357. if (this.nData) {
  25358. r += ' NDATA ' + this.nData;
  25359. }
  25360. }
  25361. r += '>';
  25362. if (pretty) {
  25363. r += newline;
  25364. }
  25365. return r;
  25366. };
  25367. return XMLDTDEntity;
  25368. })();
  25369. }).call(this);
  25370. },{"lodash/lang/isObject":221,"lodash/object/create":225}],162:[function(require,module,exports){
  25371. // Generated by CoffeeScript 1.9.1
  25372. (function() {
  25373. var XMLDTDNotation, create;
  25374. create = require('lodash/object/create');
  25375. module.exports = XMLDTDNotation = (function() {
  25376. function XMLDTDNotation(parent, name, value) {
  25377. this.stringify = parent.stringify;
  25378. if (name == null) {
  25379. throw new Error("Missing notation name");
  25380. }
  25381. if (!value.pubID && !value.sysID) {
  25382. throw new Error("Public or system identifiers are required for an external entity");
  25383. }
  25384. this.name = this.stringify.eleName(name);
  25385. if (value.pubID != null) {
  25386. this.pubID = this.stringify.dtdPubID(value.pubID);
  25387. }
  25388. if (value.sysID != null) {
  25389. this.sysID = this.stringify.dtdSysID(value.sysID);
  25390. }
  25391. }
  25392. XMLDTDNotation.prototype.clone = function() {
  25393. return create(XMLDTDNotation.prototype, this);
  25394. };
  25395. XMLDTDNotation.prototype.toString = function(options, level) {
  25396. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25397. pretty = (options != null ? options.pretty : void 0) || false;
  25398. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25399. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25400. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25401. level || (level = 0);
  25402. space = new Array(level + offset + 1).join(indent);
  25403. r = '';
  25404. if (pretty) {
  25405. r += space;
  25406. }
  25407. r += '<!NOTATION ' + this.name;
  25408. if (this.pubID && this.sysID) {
  25409. r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
  25410. } else if (this.pubID) {
  25411. r += ' PUBLIC "' + this.pubID + '"';
  25412. } else if (this.sysID) {
  25413. r += ' SYSTEM "' + this.sysID + '"';
  25414. }
  25415. r += '>';
  25416. if (pretty) {
  25417. r += newline;
  25418. }
  25419. return r;
  25420. };
  25421. return XMLDTDNotation;
  25422. })();
  25423. }).call(this);
  25424. },{"lodash/object/create":225}],163:[function(require,module,exports){
  25425. // Generated by CoffeeScript 1.9.1
  25426. (function() {
  25427. var XMLDeclaration, XMLNode, create, isObject,
  25428. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  25429. hasProp = {}.hasOwnProperty;
  25430. create = require('lodash/object/create');
  25431. isObject = require('lodash/lang/isObject');
  25432. XMLNode = require('./XMLNode');
  25433. module.exports = XMLDeclaration = (function(superClass) {
  25434. extend(XMLDeclaration, superClass);
  25435. function XMLDeclaration(parent, version, encoding, standalone) {
  25436. var ref;
  25437. XMLDeclaration.__super__.constructor.call(this, parent);
  25438. if (isObject(version)) {
  25439. ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
  25440. }
  25441. if (!version) {
  25442. version = '1.0';
  25443. }
  25444. if (version != null) {
  25445. this.version = this.stringify.xmlVersion(version);
  25446. }
  25447. if (encoding != null) {
  25448. this.encoding = this.stringify.xmlEncoding(encoding);
  25449. }
  25450. if (standalone != null) {
  25451. this.standalone = this.stringify.xmlStandalone(standalone);
  25452. }
  25453. }
  25454. XMLDeclaration.prototype.clone = function() {
  25455. return create(XMLDeclaration.prototype, this);
  25456. };
  25457. XMLDeclaration.prototype.toString = function(options, level) {
  25458. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  25459. pretty = (options != null ? options.pretty : void 0) || false;
  25460. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25461. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25462. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25463. level || (level = 0);
  25464. space = new Array(level + offset + 1).join(indent);
  25465. r = '';
  25466. if (pretty) {
  25467. r += space;
  25468. }
  25469. r += '<?xml';
  25470. if (this.version != null) {
  25471. r += ' version="' + this.version + '"';
  25472. }
  25473. if (this.encoding != null) {
  25474. r += ' encoding="' + this.encoding + '"';
  25475. }
  25476. if (this.standalone != null) {
  25477. r += ' standalone="' + this.standalone + '"';
  25478. }
  25479. r += '?>';
  25480. if (pretty) {
  25481. r += newline;
  25482. }
  25483. return r;
  25484. };
  25485. return XMLDeclaration;
  25486. })(XMLNode);
  25487. }).call(this);
  25488. },{"./XMLNode":166,"lodash/lang/isObject":221,"lodash/object/create":225}],164:[function(require,module,exports){
  25489. // Generated by CoffeeScript 1.9.1
  25490. (function() {
  25491. var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLProcessingInstruction, create, isObject;
  25492. create = require('lodash/object/create');
  25493. isObject = require('lodash/lang/isObject');
  25494. XMLCData = require('./XMLCData');
  25495. XMLComment = require('./XMLComment');
  25496. XMLDTDAttList = require('./XMLDTDAttList');
  25497. XMLDTDEntity = require('./XMLDTDEntity');
  25498. XMLDTDElement = require('./XMLDTDElement');
  25499. XMLDTDNotation = require('./XMLDTDNotation');
  25500. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  25501. module.exports = XMLDocType = (function() {
  25502. function XMLDocType(parent, pubID, sysID) {
  25503. var ref, ref1;
  25504. this.documentObject = parent;
  25505. this.stringify = this.documentObject.stringify;
  25506. this.children = [];
  25507. if (isObject(pubID)) {
  25508. ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
  25509. }
  25510. if (sysID == null) {
  25511. ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
  25512. }
  25513. if (pubID != null) {
  25514. this.pubID = this.stringify.dtdPubID(pubID);
  25515. }
  25516. if (sysID != null) {
  25517. this.sysID = this.stringify.dtdSysID(sysID);
  25518. }
  25519. }
  25520. XMLDocType.prototype.clone = function() {
  25521. return create(XMLDocType.prototype, this);
  25522. };
  25523. XMLDocType.prototype.element = function(name, value) {
  25524. var child;
  25525. child = new XMLDTDElement(this, name, value);
  25526. this.children.push(child);
  25527. return this;
  25528. };
  25529. XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  25530. var child;
  25531. child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
  25532. this.children.push(child);
  25533. return this;
  25534. };
  25535. XMLDocType.prototype.entity = function(name, value) {
  25536. var child;
  25537. child = new XMLDTDEntity(this, false, name, value);
  25538. this.children.push(child);
  25539. return this;
  25540. };
  25541. XMLDocType.prototype.pEntity = function(name, value) {
  25542. var child;
  25543. child = new XMLDTDEntity(this, true, name, value);
  25544. this.children.push(child);
  25545. return this;
  25546. };
  25547. XMLDocType.prototype.notation = function(name, value) {
  25548. var child;
  25549. child = new XMLDTDNotation(this, name, value);
  25550. this.children.push(child);
  25551. return this;
  25552. };
  25553. XMLDocType.prototype.cdata = function(value) {
  25554. var child;
  25555. child = new XMLCData(this, value);
  25556. this.children.push(child);
  25557. return this;
  25558. };
  25559. XMLDocType.prototype.comment = function(value) {
  25560. var child;
  25561. child = new XMLComment(this, value);
  25562. this.children.push(child);
  25563. return this;
  25564. };
  25565. XMLDocType.prototype.instruction = function(target, value) {
  25566. var child;
  25567. child = new XMLProcessingInstruction(this, target, value);
  25568. this.children.push(child);
  25569. return this;
  25570. };
  25571. XMLDocType.prototype.root = function() {
  25572. return this.documentObject.root();
  25573. };
  25574. XMLDocType.prototype.document = function() {
  25575. return this.documentObject;
  25576. };
  25577. XMLDocType.prototype.toString = function(options, level) {
  25578. var child, i, indent, len, newline, offset, pretty, r, ref, ref1, ref2, ref3, space;
  25579. pretty = (options != null ? options.pretty : void 0) || false;
  25580. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25581. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25582. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25583. level || (level = 0);
  25584. space = new Array(level + offset + 1).join(indent);
  25585. r = '';
  25586. if (pretty) {
  25587. r += space;
  25588. }
  25589. r += '<!DOCTYPE ' + this.root().name;
  25590. if (this.pubID && this.sysID) {
  25591. r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
  25592. } else if (this.sysID) {
  25593. r += ' SYSTEM "' + this.sysID + '"';
  25594. }
  25595. if (this.children.length > 0) {
  25596. r += ' [';
  25597. if (pretty) {
  25598. r += newline;
  25599. }
  25600. ref3 = this.children;
  25601. for (i = 0, len = ref3.length; i < len; i++) {
  25602. child = ref3[i];
  25603. r += child.toString(options, level + 1);
  25604. }
  25605. r += ']';
  25606. }
  25607. r += '>';
  25608. if (pretty) {
  25609. r += newline;
  25610. }
  25611. return r;
  25612. };
  25613. XMLDocType.prototype.ele = function(name, value) {
  25614. return this.element(name, value);
  25615. };
  25616. XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  25617. return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
  25618. };
  25619. XMLDocType.prototype.ent = function(name, value) {
  25620. return this.entity(name, value);
  25621. };
  25622. XMLDocType.prototype.pent = function(name, value) {
  25623. return this.pEntity(name, value);
  25624. };
  25625. XMLDocType.prototype.not = function(name, value) {
  25626. return this.notation(name, value);
  25627. };
  25628. XMLDocType.prototype.dat = function(value) {
  25629. return this.cdata(value);
  25630. };
  25631. XMLDocType.prototype.com = function(value) {
  25632. return this.comment(value);
  25633. };
  25634. XMLDocType.prototype.ins = function(target, value) {
  25635. return this.instruction(target, value);
  25636. };
  25637. XMLDocType.prototype.up = function() {
  25638. return this.root();
  25639. };
  25640. XMLDocType.prototype.doc = function() {
  25641. return this.document();
  25642. };
  25643. return XMLDocType;
  25644. })();
  25645. }).call(this);
  25646. },{"./XMLCData":157,"./XMLComment":158,"./XMLDTDAttList":159,"./XMLDTDElement":160,"./XMLDTDEntity":161,"./XMLDTDNotation":162,"./XMLProcessingInstruction":167,"lodash/lang/isObject":221,"lodash/object/create":225}],165:[function(require,module,exports){
  25647. // Generated by CoffeeScript 1.9.1
  25648. (function() {
  25649. var XMLAttribute, XMLElement, XMLNode, XMLProcessingInstruction, create, every, isFunction, isObject,
  25650. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  25651. hasProp = {}.hasOwnProperty;
  25652. create = require('lodash/object/create');
  25653. isObject = require('lodash/lang/isObject');
  25654. isFunction = require('lodash/lang/isFunction');
  25655. every = require('lodash/collection/every');
  25656. XMLNode = require('./XMLNode');
  25657. XMLAttribute = require('./XMLAttribute');
  25658. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  25659. module.exports = XMLElement = (function(superClass) {
  25660. extend(XMLElement, superClass);
  25661. function XMLElement(parent, name, attributes) {
  25662. XMLElement.__super__.constructor.call(this, parent);
  25663. if (name == null) {
  25664. throw new Error("Missing element name");
  25665. }
  25666. this.name = this.stringify.eleName(name);
  25667. this.children = [];
  25668. this.instructions = [];
  25669. this.attributes = {};
  25670. if (attributes != null) {
  25671. this.attribute(attributes);
  25672. }
  25673. }
  25674. XMLElement.prototype.clone = function() {
  25675. var att, attName, clonedSelf, i, len, pi, ref, ref1;
  25676. clonedSelf = create(XMLElement.prototype, this);
  25677. if (clonedSelf.isRoot) {
  25678. clonedSelf.documentObject = null;
  25679. }
  25680. clonedSelf.attributes = {};
  25681. ref = this.attributes;
  25682. for (attName in ref) {
  25683. if (!hasProp.call(ref, attName)) continue;
  25684. att = ref[attName];
  25685. clonedSelf.attributes[attName] = att.clone();
  25686. }
  25687. clonedSelf.instructions = [];
  25688. ref1 = this.instructions;
  25689. for (i = 0, len = ref1.length; i < len; i++) {
  25690. pi = ref1[i];
  25691. clonedSelf.instructions.push(pi.clone());
  25692. }
  25693. clonedSelf.children = [];
  25694. this.children.forEach(function(child) {
  25695. var clonedChild;
  25696. clonedChild = child.clone();
  25697. clonedChild.parent = clonedSelf;
  25698. return clonedSelf.children.push(clonedChild);
  25699. });
  25700. return clonedSelf;
  25701. };
  25702. XMLElement.prototype.attribute = function(name, value) {
  25703. var attName, attValue;
  25704. if (name != null) {
  25705. name = name.valueOf();
  25706. }
  25707. if (isObject(name)) {
  25708. for (attName in name) {
  25709. if (!hasProp.call(name, attName)) continue;
  25710. attValue = name[attName];
  25711. this.attribute(attName, attValue);
  25712. }
  25713. } else {
  25714. if (isFunction(value)) {
  25715. value = value.apply();
  25716. }
  25717. if (!this.options.skipNullAttributes || (value != null)) {
  25718. this.attributes[name] = new XMLAttribute(this, name, value);
  25719. }
  25720. }
  25721. return this;
  25722. };
  25723. XMLElement.prototype.removeAttribute = function(name) {
  25724. var attName, i, len;
  25725. if (name == null) {
  25726. throw new Error("Missing attribute name");
  25727. }
  25728. name = name.valueOf();
  25729. if (Array.isArray(name)) {
  25730. for (i = 0, len = name.length; i < len; i++) {
  25731. attName = name[i];
  25732. delete this.attributes[attName];
  25733. }
  25734. } else {
  25735. delete this.attributes[name];
  25736. }
  25737. return this;
  25738. };
  25739. XMLElement.prototype.instruction = function(target, value) {
  25740. var i, insTarget, insValue, instruction, len;
  25741. if (target != null) {
  25742. target = target.valueOf();
  25743. }
  25744. if (value != null) {
  25745. value = value.valueOf();
  25746. }
  25747. if (Array.isArray(target)) {
  25748. for (i = 0, len = target.length; i < len; i++) {
  25749. insTarget = target[i];
  25750. this.instruction(insTarget);
  25751. }
  25752. } else if (isObject(target)) {
  25753. for (insTarget in target) {
  25754. if (!hasProp.call(target, insTarget)) continue;
  25755. insValue = target[insTarget];
  25756. this.instruction(insTarget, insValue);
  25757. }
  25758. } else {
  25759. if (isFunction(value)) {
  25760. value = value.apply();
  25761. }
  25762. instruction = new XMLProcessingInstruction(this, target, value);
  25763. this.instructions.push(instruction);
  25764. }
  25765. return this;
  25766. };
  25767. XMLElement.prototype.toString = function(options, level) {
  25768. var att, child, i, indent, instruction, j, len, len1, name, newline, offset, pretty, r, ref, ref1, ref2, ref3, ref4, ref5, space;
  25769. pretty = (options != null ? options.pretty : void 0) || false;
  25770. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  25771. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  25772. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  25773. level || (level = 0);
  25774. space = new Array(level + offset + 1).join(indent);
  25775. r = '';
  25776. ref3 = this.instructions;
  25777. for (i = 0, len = ref3.length; i < len; i++) {
  25778. instruction = ref3[i];
  25779. r += instruction.toString(options, level);
  25780. }
  25781. if (pretty) {
  25782. r += space;
  25783. }
  25784. r += '<' + this.name;
  25785. ref4 = this.attributes;
  25786. for (name in ref4) {
  25787. if (!hasProp.call(ref4, name)) continue;
  25788. att = ref4[name];
  25789. r += att.toString(options);
  25790. }
  25791. if (this.children.length === 0 || every(this.children, function(e) {
  25792. return e.value === '';
  25793. })) {
  25794. r += '/>';
  25795. if (pretty) {
  25796. r += newline;
  25797. }
  25798. } else if (pretty && this.children.length === 1 && (this.children[0].value != null)) {
  25799. r += '>';
  25800. r += this.children[0].value;
  25801. r += '</' + this.name + '>';
  25802. r += newline;
  25803. } else {
  25804. r += '>';
  25805. if (pretty) {
  25806. r += newline;
  25807. }
  25808. ref5 = this.children;
  25809. for (j = 0, len1 = ref5.length; j < len1; j++) {
  25810. child = ref5[j];
  25811. r += child.toString(options, level + 1);
  25812. }
  25813. if (pretty) {
  25814. r += space;
  25815. }
  25816. r += '</' + this.name + '>';
  25817. if (pretty) {
  25818. r += newline;
  25819. }
  25820. }
  25821. return r;
  25822. };
  25823. XMLElement.prototype.att = function(name, value) {
  25824. return this.attribute(name, value);
  25825. };
  25826. XMLElement.prototype.ins = function(target, value) {
  25827. return this.instruction(target, value);
  25828. };
  25829. XMLElement.prototype.a = function(name, value) {
  25830. return this.attribute(name, value);
  25831. };
  25832. XMLElement.prototype.i = function(target, value) {
  25833. return this.instruction(target, value);
  25834. };
  25835. return XMLElement;
  25836. })(XMLNode);
  25837. }).call(this);
  25838. },{"./XMLAttribute":155,"./XMLNode":166,"./XMLProcessingInstruction":167,"lodash/collection/every":173,"lodash/lang/isFunction":219,"lodash/lang/isObject":221,"lodash/object/create":225}],166:[function(require,module,exports){
  25839. // Generated by CoffeeScript 1.9.1
  25840. (function() {
  25841. var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLRaw, XMLText, isEmpty, isFunction, isObject,
  25842. hasProp = {}.hasOwnProperty;
  25843. isObject = require('lodash/lang/isObject');
  25844. isFunction = require('lodash/lang/isFunction');
  25845. isEmpty = require('lodash/lang/isEmpty');
  25846. XMLElement = null;
  25847. XMLCData = null;
  25848. XMLComment = null;
  25849. XMLDeclaration = null;
  25850. XMLDocType = null;
  25851. XMLRaw = null;
  25852. XMLText = null;
  25853. module.exports = XMLNode = (function() {
  25854. function XMLNode(parent) {
  25855. this.parent = parent;
  25856. this.options = this.parent.options;
  25857. this.stringify = this.parent.stringify;
  25858. if (XMLElement === null) {
  25859. XMLElement = require('./XMLElement');
  25860. XMLCData = require('./XMLCData');
  25861. XMLComment = require('./XMLComment');
  25862. XMLDeclaration = require('./XMLDeclaration');
  25863. XMLDocType = require('./XMLDocType');
  25864. XMLRaw = require('./XMLRaw');
  25865. XMLText = require('./XMLText');
  25866. }
  25867. }
  25868. XMLNode.prototype.clone = function() {
  25869. throw new Error("Cannot clone generic XMLNode");
  25870. };
  25871. XMLNode.prototype.element = function(name, attributes, text) {
  25872. var item, j, key, lastChild, len, ref, val;
  25873. lastChild = null;
  25874. if (attributes == null) {
  25875. attributes = {};
  25876. }
  25877. attributes = attributes.valueOf();
  25878. if (!isObject(attributes)) {
  25879. ref = [attributes, text], text = ref[0], attributes = ref[1];
  25880. }
  25881. if (name != null) {
  25882. name = name.valueOf();
  25883. }
  25884. if (Array.isArray(name)) {
  25885. for (j = 0, len = name.length; j < len; j++) {
  25886. item = name[j];
  25887. lastChild = this.element(item);
  25888. }
  25889. } else if (isFunction(name)) {
  25890. lastChild = this.element(name.apply());
  25891. } else if (isObject(name)) {
  25892. for (key in name) {
  25893. if (!hasProp.call(name, key)) continue;
  25894. val = name[key];
  25895. if (isFunction(val)) {
  25896. val = val.apply();
  25897. }
  25898. if ((isObject(val)) && (isEmpty(val))) {
  25899. val = null;
  25900. }
  25901. if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
  25902. lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
  25903. } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && key.indexOf(this.stringify.convertPIKey) === 0) {
  25904. lastChild = this.instruction(key.substr(this.stringify.convertPIKey.length), val);
  25905. } else if (isObject(val)) {
  25906. if (!this.options.ignoreDecorators && this.stringify.convertListKey && key.indexOf(this.stringify.convertListKey) === 0 && Array.isArray(val)) {
  25907. lastChild = this.element(val);
  25908. } else {
  25909. lastChild = this.element(key);
  25910. lastChild.element(val);
  25911. }
  25912. } else {
  25913. lastChild = this.element(key, val);
  25914. }
  25915. }
  25916. } else {
  25917. if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
  25918. lastChild = this.text(text);
  25919. } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
  25920. lastChild = this.cdata(text);
  25921. } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
  25922. lastChild = this.comment(text);
  25923. } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
  25924. lastChild = this.raw(text);
  25925. } else {
  25926. lastChild = this.node(name, attributes, text);
  25927. }
  25928. }
  25929. if (lastChild == null) {
  25930. throw new Error("Could not create any elements with: " + name);
  25931. }
  25932. return lastChild;
  25933. };
  25934. XMLNode.prototype.insertBefore = function(name, attributes, text) {
  25935. var child, i, removed;
  25936. if (this.isRoot) {
  25937. throw new Error("Cannot insert elements at root level");
  25938. }
  25939. i = this.parent.children.indexOf(this);
  25940. removed = this.parent.children.splice(i);
  25941. child = this.parent.element(name, attributes, text);
  25942. Array.prototype.push.apply(this.parent.children, removed);
  25943. return child;
  25944. };
  25945. XMLNode.prototype.insertAfter = function(name, attributes, text) {
  25946. var child, i, removed;
  25947. if (this.isRoot) {
  25948. throw new Error("Cannot insert elements at root level");
  25949. }
  25950. i = this.parent.children.indexOf(this);
  25951. removed = this.parent.children.splice(i + 1);
  25952. child = this.parent.element(name, attributes, text);
  25953. Array.prototype.push.apply(this.parent.children, removed);
  25954. return child;
  25955. };
  25956. XMLNode.prototype.remove = function() {
  25957. var i, ref;
  25958. if (this.isRoot) {
  25959. throw new Error("Cannot remove the root element");
  25960. }
  25961. i = this.parent.children.indexOf(this);
  25962. [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref = [])), ref;
  25963. return this.parent;
  25964. };
  25965. XMLNode.prototype.node = function(name, attributes, text) {
  25966. var child, ref;
  25967. if (name != null) {
  25968. name = name.valueOf();
  25969. }
  25970. if (attributes == null) {
  25971. attributes = {};
  25972. }
  25973. attributes = attributes.valueOf();
  25974. if (!isObject(attributes)) {
  25975. ref = [attributes, text], text = ref[0], attributes = ref[1];
  25976. }
  25977. child = new XMLElement(this, name, attributes);
  25978. if (text != null) {
  25979. child.text(text);
  25980. }
  25981. this.children.push(child);
  25982. return child;
  25983. };
  25984. XMLNode.prototype.text = function(value) {
  25985. var child;
  25986. child = new XMLText(this, value);
  25987. this.children.push(child);
  25988. return this;
  25989. };
  25990. XMLNode.prototype.cdata = function(value) {
  25991. var child;
  25992. child = new XMLCData(this, value);
  25993. this.children.push(child);
  25994. return this;
  25995. };
  25996. XMLNode.prototype.comment = function(value) {
  25997. var child;
  25998. child = new XMLComment(this, value);
  25999. this.children.push(child);
  26000. return this;
  26001. };
  26002. XMLNode.prototype.raw = function(value) {
  26003. var child;
  26004. child = new XMLRaw(this, value);
  26005. this.children.push(child);
  26006. return this;
  26007. };
  26008. XMLNode.prototype.declaration = function(version, encoding, standalone) {
  26009. var doc, xmldec;
  26010. doc = this.document();
  26011. xmldec = new XMLDeclaration(doc, version, encoding, standalone);
  26012. doc.xmldec = xmldec;
  26013. return doc.root();
  26014. };
  26015. XMLNode.prototype.doctype = function(pubID, sysID) {
  26016. var doc, doctype;
  26017. doc = this.document();
  26018. doctype = new XMLDocType(doc, pubID, sysID);
  26019. doc.doctype = doctype;
  26020. return doctype;
  26021. };
  26022. XMLNode.prototype.up = function() {
  26023. if (this.isRoot) {
  26024. throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
  26025. }
  26026. return this.parent;
  26027. };
  26028. XMLNode.prototype.root = function() {
  26029. var child;
  26030. if (this.isRoot) {
  26031. return this;
  26032. }
  26033. child = this.parent;
  26034. while (!child.isRoot) {
  26035. child = child.parent;
  26036. }
  26037. return child;
  26038. };
  26039. XMLNode.prototype.document = function() {
  26040. return this.root().documentObject;
  26041. };
  26042. XMLNode.prototype.end = function(options) {
  26043. return this.document().toString(options);
  26044. };
  26045. XMLNode.prototype.prev = function() {
  26046. var i;
  26047. if (this.isRoot) {
  26048. throw new Error("Root node has no siblings");
  26049. }
  26050. i = this.parent.children.indexOf(this);
  26051. if (i < 1) {
  26052. throw new Error("Already at the first node");
  26053. }
  26054. return this.parent.children[i - 1];
  26055. };
  26056. XMLNode.prototype.next = function() {
  26057. var i;
  26058. if (this.isRoot) {
  26059. throw new Error("Root node has no siblings");
  26060. }
  26061. i = this.parent.children.indexOf(this);
  26062. if (i === -1 || i === this.parent.children.length - 1) {
  26063. throw new Error("Already at the last node");
  26064. }
  26065. return this.parent.children[i + 1];
  26066. };
  26067. XMLNode.prototype.importXMLBuilder = function(xmlbuilder) {
  26068. var clonedRoot;
  26069. clonedRoot = xmlbuilder.root().clone();
  26070. clonedRoot.parent = this;
  26071. clonedRoot.isRoot = false;
  26072. this.children.push(clonedRoot);
  26073. return this;
  26074. };
  26075. XMLNode.prototype.ele = function(name, attributes, text) {
  26076. return this.element(name, attributes, text);
  26077. };
  26078. XMLNode.prototype.nod = function(name, attributes, text) {
  26079. return this.node(name, attributes, text);
  26080. };
  26081. XMLNode.prototype.txt = function(value) {
  26082. return this.text(value);
  26083. };
  26084. XMLNode.prototype.dat = function(value) {
  26085. return this.cdata(value);
  26086. };
  26087. XMLNode.prototype.com = function(value) {
  26088. return this.comment(value);
  26089. };
  26090. XMLNode.prototype.doc = function() {
  26091. return this.document();
  26092. };
  26093. XMLNode.prototype.dec = function(version, encoding, standalone) {
  26094. return this.declaration(version, encoding, standalone);
  26095. };
  26096. XMLNode.prototype.dtd = function(pubID, sysID) {
  26097. return this.doctype(pubID, sysID);
  26098. };
  26099. XMLNode.prototype.e = function(name, attributes, text) {
  26100. return this.element(name, attributes, text);
  26101. };
  26102. XMLNode.prototype.n = function(name, attributes, text) {
  26103. return this.node(name, attributes, text);
  26104. };
  26105. XMLNode.prototype.t = function(value) {
  26106. return this.text(value);
  26107. };
  26108. XMLNode.prototype.d = function(value) {
  26109. return this.cdata(value);
  26110. };
  26111. XMLNode.prototype.c = function(value) {
  26112. return this.comment(value);
  26113. };
  26114. XMLNode.prototype.r = function(value) {
  26115. return this.raw(value);
  26116. };
  26117. XMLNode.prototype.u = function() {
  26118. return this.up();
  26119. };
  26120. return XMLNode;
  26121. })();
  26122. }).call(this);
  26123. },{"./XMLCData":157,"./XMLComment":158,"./XMLDeclaration":163,"./XMLDocType":164,"./XMLElement":165,"./XMLRaw":168,"./XMLText":170,"lodash/lang/isEmpty":218,"lodash/lang/isFunction":219,"lodash/lang/isObject":221}],167:[function(require,module,exports){
  26124. // Generated by CoffeeScript 1.9.1
  26125. (function() {
  26126. var XMLProcessingInstruction, create;
  26127. create = require('lodash/object/create');
  26128. module.exports = XMLProcessingInstruction = (function() {
  26129. function XMLProcessingInstruction(parent, target, value) {
  26130. this.stringify = parent.stringify;
  26131. if (target == null) {
  26132. throw new Error("Missing instruction target");
  26133. }
  26134. this.target = this.stringify.insTarget(target);
  26135. if (value) {
  26136. this.value = this.stringify.insValue(value);
  26137. }
  26138. }
  26139. XMLProcessingInstruction.prototype.clone = function() {
  26140. return create(XMLProcessingInstruction.prototype, this);
  26141. };
  26142. XMLProcessingInstruction.prototype.toString = function(options, level) {
  26143. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  26144. pretty = (options != null ? options.pretty : void 0) || false;
  26145. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  26146. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  26147. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  26148. level || (level = 0);
  26149. space = new Array(level + offset + 1).join(indent);
  26150. r = '';
  26151. if (pretty) {
  26152. r += space;
  26153. }
  26154. r += '<?';
  26155. r += this.target;
  26156. if (this.value) {
  26157. r += ' ' + this.value;
  26158. }
  26159. r += '?>';
  26160. if (pretty) {
  26161. r += newline;
  26162. }
  26163. return r;
  26164. };
  26165. return XMLProcessingInstruction;
  26166. })();
  26167. }).call(this);
  26168. },{"lodash/object/create":225}],168:[function(require,module,exports){
  26169. // Generated by CoffeeScript 1.9.1
  26170. (function() {
  26171. var XMLNode, XMLRaw, create,
  26172. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  26173. hasProp = {}.hasOwnProperty;
  26174. create = require('lodash/object/create');
  26175. XMLNode = require('./XMLNode');
  26176. module.exports = XMLRaw = (function(superClass) {
  26177. extend(XMLRaw, superClass);
  26178. function XMLRaw(parent, text) {
  26179. XMLRaw.__super__.constructor.call(this, parent);
  26180. if (text == null) {
  26181. throw new Error("Missing raw text");
  26182. }
  26183. this.value = this.stringify.raw(text);
  26184. }
  26185. XMLRaw.prototype.clone = function() {
  26186. return create(XMLRaw.prototype, this);
  26187. };
  26188. XMLRaw.prototype.toString = function(options, level) {
  26189. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  26190. pretty = (options != null ? options.pretty : void 0) || false;
  26191. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  26192. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  26193. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  26194. level || (level = 0);
  26195. space = new Array(level + offset + 1).join(indent);
  26196. r = '';
  26197. if (pretty) {
  26198. r += space;
  26199. }
  26200. r += this.value;
  26201. if (pretty) {
  26202. r += newline;
  26203. }
  26204. return r;
  26205. };
  26206. return XMLRaw;
  26207. })(XMLNode);
  26208. }).call(this);
  26209. },{"./XMLNode":166,"lodash/object/create":225}],169:[function(require,module,exports){
  26210. // Generated by CoffeeScript 1.9.1
  26211. (function() {
  26212. var XMLStringifier,
  26213. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  26214. hasProp = {}.hasOwnProperty;
  26215. module.exports = XMLStringifier = (function() {
  26216. function XMLStringifier(options) {
  26217. this.assertLegalChar = bind(this.assertLegalChar, this);
  26218. var key, ref, value;
  26219. this.allowSurrogateChars = options != null ? options.allowSurrogateChars : void 0;
  26220. ref = (options != null ? options.stringify : void 0) || {};
  26221. for (key in ref) {
  26222. if (!hasProp.call(ref, key)) continue;
  26223. value = ref[key];
  26224. this[key] = value;
  26225. }
  26226. }
  26227. XMLStringifier.prototype.eleName = function(val) {
  26228. val = '' + val || '';
  26229. return this.assertLegalChar(val);
  26230. };
  26231. XMLStringifier.prototype.eleText = function(val) {
  26232. val = '' + val || '';
  26233. return this.assertLegalChar(this.elEscape(val));
  26234. };
  26235. XMLStringifier.prototype.cdata = function(val) {
  26236. val = '' + val || '';
  26237. if (val.match(/]]>/)) {
  26238. throw new Error("Invalid CDATA text: " + val);
  26239. }
  26240. return this.assertLegalChar(val);
  26241. };
  26242. XMLStringifier.prototype.comment = function(val) {
  26243. val = '' + val || '';
  26244. if (val.match(/--/)) {
  26245. throw new Error("Comment text cannot contain double-hypen: " + val);
  26246. }
  26247. return this.assertLegalChar(val);
  26248. };
  26249. XMLStringifier.prototype.raw = function(val) {
  26250. return '' + val || '';
  26251. };
  26252. XMLStringifier.prototype.attName = function(val) {
  26253. return '' + val || '';
  26254. };
  26255. XMLStringifier.prototype.attValue = function(val) {
  26256. val = '' + val || '';
  26257. return this.attEscape(val);
  26258. };
  26259. XMLStringifier.prototype.insTarget = function(val) {
  26260. return '' + val || '';
  26261. };
  26262. XMLStringifier.prototype.insValue = function(val) {
  26263. val = '' + val || '';
  26264. if (val.match(/\?>/)) {
  26265. throw new Error("Invalid processing instruction value: " + val);
  26266. }
  26267. return val;
  26268. };
  26269. XMLStringifier.prototype.xmlVersion = function(val) {
  26270. val = '' + val || '';
  26271. if (!val.match(/1\.[0-9]+/)) {
  26272. throw new Error("Invalid version number: " + val);
  26273. }
  26274. return val;
  26275. };
  26276. XMLStringifier.prototype.xmlEncoding = function(val) {
  26277. val = '' + val || '';
  26278. if (!val.match(/[A-Za-z](?:[A-Za-z0-9._-]|-)*/)) {
  26279. throw new Error("Invalid encoding: " + val);
  26280. }
  26281. return val;
  26282. };
  26283. XMLStringifier.prototype.xmlStandalone = function(val) {
  26284. if (val) {
  26285. return "yes";
  26286. } else {
  26287. return "no";
  26288. }
  26289. };
  26290. XMLStringifier.prototype.dtdPubID = function(val) {
  26291. return '' + val || '';
  26292. };
  26293. XMLStringifier.prototype.dtdSysID = function(val) {
  26294. return '' + val || '';
  26295. };
  26296. XMLStringifier.prototype.dtdElementValue = function(val) {
  26297. return '' + val || '';
  26298. };
  26299. XMLStringifier.prototype.dtdAttType = function(val) {
  26300. return '' + val || '';
  26301. };
  26302. XMLStringifier.prototype.dtdAttDefault = function(val) {
  26303. if (val != null) {
  26304. return '' + val || '';
  26305. } else {
  26306. return val;
  26307. }
  26308. };
  26309. XMLStringifier.prototype.dtdEntityValue = function(val) {
  26310. return '' + val || '';
  26311. };
  26312. XMLStringifier.prototype.dtdNData = function(val) {
  26313. return '' + val || '';
  26314. };
  26315. XMLStringifier.prototype.convertAttKey = '@';
  26316. XMLStringifier.prototype.convertPIKey = '?';
  26317. XMLStringifier.prototype.convertTextKey = '#text';
  26318. XMLStringifier.prototype.convertCDataKey = '#cdata';
  26319. XMLStringifier.prototype.convertCommentKey = '#comment';
  26320. XMLStringifier.prototype.convertRawKey = '#raw';
  26321. XMLStringifier.prototype.convertListKey = '#list';
  26322. XMLStringifier.prototype.assertLegalChar = function(str) {
  26323. var chars, chr;
  26324. if (this.allowSurrogateChars) {
  26325. chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/;
  26326. } else {
  26327. chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/;
  26328. }
  26329. chr = str.match(chars);
  26330. if (chr) {
  26331. throw new Error("Invalid character (" + chr + ") in string: " + str + " at index " + chr.index);
  26332. }
  26333. return str;
  26334. };
  26335. XMLStringifier.prototype.elEscape = function(str) {
  26336. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
  26337. };
  26338. XMLStringifier.prototype.attEscape = function(str) {
  26339. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
  26340. };
  26341. return XMLStringifier;
  26342. })();
  26343. }).call(this);
  26344. },{}],170:[function(require,module,exports){
  26345. // Generated by CoffeeScript 1.9.1
  26346. (function() {
  26347. var XMLNode, XMLText, create,
  26348. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  26349. hasProp = {}.hasOwnProperty;
  26350. create = require('lodash/object/create');
  26351. XMLNode = require('./XMLNode');
  26352. module.exports = XMLText = (function(superClass) {
  26353. extend(XMLText, superClass);
  26354. function XMLText(parent, text) {
  26355. XMLText.__super__.constructor.call(this, parent);
  26356. if (text == null) {
  26357. throw new Error("Missing element text");
  26358. }
  26359. this.value = this.stringify.eleText(text);
  26360. }
  26361. XMLText.prototype.clone = function() {
  26362. return create(XMLText.prototype, this);
  26363. };
  26364. XMLText.prototype.toString = function(options, level) {
  26365. var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
  26366. pretty = (options != null ? options.pretty : void 0) || false;
  26367. indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
  26368. offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
  26369. newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
  26370. level || (level = 0);
  26371. space = new Array(level + offset + 1).join(indent);
  26372. r = '';
  26373. if (pretty) {
  26374. r += space;
  26375. }
  26376. r += this.value;
  26377. if (pretty) {
  26378. r += newline;
  26379. }
  26380. return r;
  26381. };
  26382. return XMLText;
  26383. })(XMLNode);
  26384. }).call(this);
  26385. },{"./XMLNode":166,"lodash/object/create":225}],171:[function(require,module,exports){
  26386. // Generated by CoffeeScript 1.9.1
  26387. (function() {
  26388. var XMLBuilder, assign;
  26389. assign = require('lodash/object/assign');
  26390. XMLBuilder = require('./XMLBuilder');
  26391. module.exports.create = function(name, xmldec, doctype, options) {
  26392. options = assign({}, xmldec, doctype, options);
  26393. return new XMLBuilder(name, options).root();
  26394. };
  26395. }).call(this);
  26396. },{"./XMLBuilder":156,"lodash/object/assign":224}],172:[function(require,module,exports){
  26397. /**
  26398. * Gets the last element of `array`.
  26399. *
  26400. * @static
  26401. * @memberOf _
  26402. * @category Array
  26403. * @param {Array} array The array to query.
  26404. * @returns {*} Returns the last element of `array`.
  26405. * @example
  26406. *
  26407. * _.last([1, 2, 3]);
  26408. * // => 3
  26409. */
  26410. function last(array) {
  26411. var length = array ? array.length : 0;
  26412. return length ? array[length - 1] : undefined;
  26413. }
  26414. module.exports = last;
  26415. },{}],173:[function(require,module,exports){
  26416. var arrayEvery = require('../internal/arrayEvery'),
  26417. baseCallback = require('../internal/baseCallback'),
  26418. baseEvery = require('../internal/baseEvery'),
  26419. isArray = require('../lang/isArray'),
  26420. isIterateeCall = require('../internal/isIterateeCall');
  26421. /**
  26422. * Checks if `predicate` returns truthy for **all** elements of `collection`.
  26423. * The predicate is bound to `thisArg` and invoked with three arguments:
  26424. * (value, index|key, collection).
  26425. *
  26426. * If a property name is provided for `predicate` the created `_.property`
  26427. * style callback returns the property value of the given element.
  26428. *
  26429. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  26430. * style callback returns `true` for elements that have a matching property
  26431. * value, else `false`.
  26432. *
  26433. * If an object is provided for `predicate` the created `_.matches` style
  26434. * callback returns `true` for elements that have the properties of the given
  26435. * object, else `false`.
  26436. *
  26437. * @static
  26438. * @memberOf _
  26439. * @alias all
  26440. * @category Collection
  26441. * @param {Array|Object|string} collection The collection to iterate over.
  26442. * @param {Function|Object|string} [predicate=_.identity] The function invoked
  26443. * per iteration.
  26444. * @param {*} [thisArg] The `this` binding of `predicate`.
  26445. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  26446. * else `false`.
  26447. * @example
  26448. *
  26449. * _.every([true, 1, null, 'yes'], Boolean);
  26450. * // => false
  26451. *
  26452. * var users = [
  26453. * { 'user': 'barney', 'active': false },
  26454. * { 'user': 'fred', 'active': false }
  26455. * ];
  26456. *
  26457. * // using the `_.matches` callback shorthand
  26458. * _.every(users, { 'user': 'barney', 'active': false });
  26459. * // => false
  26460. *
  26461. * // using the `_.matchesProperty` callback shorthand
  26462. * _.every(users, 'active', false);
  26463. * // => true
  26464. *
  26465. * // using the `_.property` callback shorthand
  26466. * _.every(users, 'active');
  26467. * // => false
  26468. */
  26469. function every(collection, predicate, thisArg) {
  26470. var func = isArray(collection) ? arrayEvery : baseEvery;
  26471. if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
  26472. predicate = undefined;
  26473. }
  26474. if (typeof predicate != 'function' || thisArg !== undefined) {
  26475. predicate = baseCallback(predicate, thisArg, 3);
  26476. }
  26477. return func(collection, predicate);
  26478. }
  26479. module.exports = every;
  26480. },{"../internal/arrayEvery":175,"../internal/baseCallback":179,"../internal/baseEvery":183,"../internal/isIterateeCall":208,"../lang/isArray":217}],174:[function(require,module,exports){
  26481. /** Used as the `TypeError` message for "Functions" methods. */
  26482. var FUNC_ERROR_TEXT = 'Expected a function';
  26483. /* Native method references for those with the same name as other `lodash` methods. */
  26484. var nativeMax = Math.max;
  26485. /**
  26486. * Creates a function that invokes `func` with the `this` binding of the
  26487. * created function and arguments from `start` and beyond provided as an array.
  26488. *
  26489. * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
  26490. *
  26491. * @static
  26492. * @memberOf _
  26493. * @category Function
  26494. * @param {Function} func The function to apply a rest parameter to.
  26495. * @param {number} [start=func.length-1] The start position of the rest parameter.
  26496. * @returns {Function} Returns the new function.
  26497. * @example
  26498. *
  26499. * var say = _.restParam(function(what, names) {
  26500. * return what + ' ' + _.initial(names).join(', ') +
  26501. * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  26502. * });
  26503. *
  26504. * say('hello', 'fred', 'barney', 'pebbles');
  26505. * // => 'hello fred, barney, & pebbles'
  26506. */
  26507. function restParam(func, start) {
  26508. if (typeof func != 'function') {
  26509. throw new TypeError(FUNC_ERROR_TEXT);
  26510. }
  26511. start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
  26512. return function() {
  26513. var args = arguments,
  26514. index = -1,
  26515. length = nativeMax(args.length - start, 0),
  26516. rest = Array(length);
  26517. while (++index < length) {
  26518. rest[index] = args[start + index];
  26519. }
  26520. switch (start) {
  26521. case 0: return func.call(this, rest);
  26522. case 1: return func.call(this, args[0], rest);
  26523. case 2: return func.call(this, args[0], args[1], rest);
  26524. }
  26525. var otherArgs = Array(start + 1);
  26526. index = -1;
  26527. while (++index < start) {
  26528. otherArgs[index] = args[index];
  26529. }
  26530. otherArgs[start] = rest;
  26531. return func.apply(this, otherArgs);
  26532. };
  26533. }
  26534. module.exports = restParam;
  26535. },{}],175:[function(require,module,exports){
  26536. /**
  26537. * A specialized version of `_.every` for arrays without support for callback
  26538. * shorthands and `this` binding.
  26539. *
  26540. * @private
  26541. * @param {Array} array The array to iterate over.
  26542. * @param {Function} predicate The function invoked per iteration.
  26543. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  26544. * else `false`.
  26545. */
  26546. function arrayEvery(array, predicate) {
  26547. var index = -1,
  26548. length = array.length;
  26549. while (++index < length) {
  26550. if (!predicate(array[index], index, array)) {
  26551. return false;
  26552. }
  26553. }
  26554. return true;
  26555. }
  26556. module.exports = arrayEvery;
  26557. },{}],176:[function(require,module,exports){
  26558. /**
  26559. * A specialized version of `_.some` for arrays without support for callback
  26560. * shorthands and `this` binding.
  26561. *
  26562. * @private
  26563. * @param {Array} array The array to iterate over.
  26564. * @param {Function} predicate The function invoked per iteration.
  26565. * @returns {boolean} Returns `true` if any element passes the predicate check,
  26566. * else `false`.
  26567. */
  26568. function arraySome(array, predicate) {
  26569. var index = -1,
  26570. length = array.length;
  26571. while (++index < length) {
  26572. if (predicate(array[index], index, array)) {
  26573. return true;
  26574. }
  26575. }
  26576. return false;
  26577. }
  26578. module.exports = arraySome;
  26579. },{}],177:[function(require,module,exports){
  26580. var keys = require('../object/keys');
  26581. /**
  26582. * A specialized version of `_.assign` for customizing assigned values without
  26583. * support for argument juggling, multiple sources, and `this` binding `customizer`
  26584. * functions.
  26585. *
  26586. * @private
  26587. * @param {Object} object The destination object.
  26588. * @param {Object} source The source object.
  26589. * @param {Function} customizer The function to customize assigned values.
  26590. * @returns {Object} Returns `object`.
  26591. */
  26592. function assignWith(object, source, customizer) {
  26593. var index = -1,
  26594. props = keys(source),
  26595. length = props.length;
  26596. while (++index < length) {
  26597. var key = props[index],
  26598. value = object[key],
  26599. result = customizer(value, source[key], key, object, source);
  26600. if ((result === result ? (result !== value) : (value === value)) ||
  26601. (value === undefined && !(key in object))) {
  26602. object[key] = result;
  26603. }
  26604. }
  26605. return object;
  26606. }
  26607. module.exports = assignWith;
  26608. },{"../object/keys":226}],178:[function(require,module,exports){
  26609. var baseCopy = require('./baseCopy'),
  26610. keys = require('../object/keys');
  26611. /**
  26612. * The base implementation of `_.assign` without support for argument juggling,
  26613. * multiple sources, and `customizer` functions.
  26614. *
  26615. * @private
  26616. * @param {Object} object The destination object.
  26617. * @param {Object} source The source object.
  26618. * @returns {Object} Returns `object`.
  26619. */
  26620. function baseAssign(object, source) {
  26621. return source == null
  26622. ? object
  26623. : baseCopy(source, keys(source), object);
  26624. }
  26625. module.exports = baseAssign;
  26626. },{"../object/keys":226,"./baseCopy":180}],179:[function(require,module,exports){
  26627. var baseMatches = require('./baseMatches'),
  26628. baseMatchesProperty = require('./baseMatchesProperty'),
  26629. bindCallback = require('./bindCallback'),
  26630. identity = require('../utility/identity'),
  26631. property = require('../utility/property');
  26632. /**
  26633. * The base implementation of `_.callback` which supports specifying the
  26634. * number of arguments to provide to `func`.
  26635. *
  26636. * @private
  26637. * @param {*} [func=_.identity] The value to convert to a callback.
  26638. * @param {*} [thisArg] The `this` binding of `func`.
  26639. * @param {number} [argCount] The number of arguments to provide to `func`.
  26640. * @returns {Function} Returns the callback.
  26641. */
  26642. function baseCallback(func, thisArg, argCount) {
  26643. var type = typeof func;
  26644. if (type == 'function') {
  26645. return thisArg === undefined
  26646. ? func
  26647. : bindCallback(func, thisArg, argCount);
  26648. }
  26649. if (func == null) {
  26650. return identity;
  26651. }
  26652. if (type == 'object') {
  26653. return baseMatches(func);
  26654. }
  26655. return thisArg === undefined
  26656. ? property(func)
  26657. : baseMatchesProperty(func, thisArg);
  26658. }
  26659. module.exports = baseCallback;
  26660. },{"../utility/identity":229,"../utility/property":230,"./baseMatches":190,"./baseMatchesProperty":191,"./bindCallback":196}],180:[function(require,module,exports){
  26661. /**
  26662. * Copies properties of `source` to `object`.
  26663. *
  26664. * @private
  26665. * @param {Object} source The object to copy properties from.
  26666. * @param {Array} props The property names to copy.
  26667. * @param {Object} [object={}] The object to copy properties to.
  26668. * @returns {Object} Returns `object`.
  26669. */
  26670. function baseCopy(source, props, object) {
  26671. object || (object = {});
  26672. var index = -1,
  26673. length = props.length;
  26674. while (++index < length) {
  26675. var key = props[index];
  26676. object[key] = source[key];
  26677. }
  26678. return object;
  26679. }
  26680. module.exports = baseCopy;
  26681. },{}],181:[function(require,module,exports){
  26682. var isObject = require('../lang/isObject');
  26683. /**
  26684. * The base implementation of `_.create` without support for assigning
  26685. * properties to the created object.
  26686. *
  26687. * @private
  26688. * @param {Object} prototype The object to inherit from.
  26689. * @returns {Object} Returns the new object.
  26690. */
  26691. var baseCreate = (function() {
  26692. function object() {}
  26693. return function(prototype) {
  26694. if (isObject(prototype)) {
  26695. object.prototype = prototype;
  26696. var result = new object;
  26697. object.prototype = undefined;
  26698. }
  26699. return result || {};
  26700. };
  26701. }());
  26702. module.exports = baseCreate;
  26703. },{"../lang/isObject":221}],182:[function(require,module,exports){
  26704. var baseForOwn = require('./baseForOwn'),
  26705. createBaseEach = require('./createBaseEach');
  26706. /**
  26707. * The base implementation of `_.forEach` without support for callback
  26708. * shorthands and `this` binding.
  26709. *
  26710. * @private
  26711. * @param {Array|Object|string} collection The collection to iterate over.
  26712. * @param {Function} iteratee The function invoked per iteration.
  26713. * @returns {Array|Object|string} Returns `collection`.
  26714. */
  26715. var baseEach = createBaseEach(baseForOwn);
  26716. module.exports = baseEach;
  26717. },{"./baseForOwn":185,"./createBaseEach":198}],183:[function(require,module,exports){
  26718. var baseEach = require('./baseEach');
  26719. /**
  26720. * The base implementation of `_.every` without support for callback
  26721. * shorthands and `this` binding.
  26722. *
  26723. * @private
  26724. * @param {Array|Object|string} collection The collection to iterate over.
  26725. * @param {Function} predicate The function invoked per iteration.
  26726. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  26727. * else `false`
  26728. */
  26729. function baseEvery(collection, predicate) {
  26730. var result = true;
  26731. baseEach(collection, function(value, index, collection) {
  26732. result = !!predicate(value, index, collection);
  26733. return result;
  26734. });
  26735. return result;
  26736. }
  26737. module.exports = baseEvery;
  26738. },{"./baseEach":182}],184:[function(require,module,exports){
  26739. var createBaseFor = require('./createBaseFor');
  26740. /**
  26741. * The base implementation of `baseForIn` and `baseForOwn` which iterates
  26742. * over `object` properties returned by `keysFunc` invoking `iteratee` for
  26743. * each property. Iteratee functions may exit iteration early by explicitly
  26744. * returning `false`.
  26745. *
  26746. * @private
  26747. * @param {Object} object The object to iterate over.
  26748. * @param {Function} iteratee The function invoked per iteration.
  26749. * @param {Function} keysFunc The function to get the keys of `object`.
  26750. * @returns {Object} Returns `object`.
  26751. */
  26752. var baseFor = createBaseFor();
  26753. module.exports = baseFor;
  26754. },{"./createBaseFor":199}],185:[function(require,module,exports){
  26755. var baseFor = require('./baseFor'),
  26756. keys = require('../object/keys');
  26757. /**
  26758. * The base implementation of `_.forOwn` without support for callback
  26759. * shorthands and `this` binding.
  26760. *
  26761. * @private
  26762. * @param {Object} object The object to iterate over.
  26763. * @param {Function} iteratee The function invoked per iteration.
  26764. * @returns {Object} Returns `object`.
  26765. */
  26766. function baseForOwn(object, iteratee) {
  26767. return baseFor(object, iteratee, keys);
  26768. }
  26769. module.exports = baseForOwn;
  26770. },{"../object/keys":226,"./baseFor":184}],186:[function(require,module,exports){
  26771. var toObject = require('./toObject');
  26772. /**
  26773. * The base implementation of `get` without support for string paths
  26774. * and default values.
  26775. *
  26776. * @private
  26777. * @param {Object} object The object to query.
  26778. * @param {Array} path The path of the property to get.
  26779. * @param {string} [pathKey] The key representation of path.
  26780. * @returns {*} Returns the resolved value.
  26781. */
  26782. function baseGet(object, path, pathKey) {
  26783. if (object == null) {
  26784. return;
  26785. }
  26786. if (pathKey !== undefined && pathKey in toObject(object)) {
  26787. path = [pathKey];
  26788. }
  26789. var index = 0,
  26790. length = path.length;
  26791. while (object != null && index < length) {
  26792. object = object[path[index++]];
  26793. }
  26794. return (index && index == length) ? object : undefined;
  26795. }
  26796. module.exports = baseGet;
  26797. },{"./toObject":214}],187:[function(require,module,exports){
  26798. var baseIsEqualDeep = require('./baseIsEqualDeep'),
  26799. isObject = require('../lang/isObject'),
  26800. isObjectLike = require('./isObjectLike');
  26801. /**
  26802. * The base implementation of `_.isEqual` without support for `this` binding
  26803. * `customizer` functions.
  26804. *
  26805. * @private
  26806. * @param {*} value The value to compare.
  26807. * @param {*} other The other value to compare.
  26808. * @param {Function} [customizer] The function to customize comparing values.
  26809. * @param {boolean} [isLoose] Specify performing partial comparisons.
  26810. * @param {Array} [stackA] Tracks traversed `value` objects.
  26811. * @param {Array} [stackB] Tracks traversed `other` objects.
  26812. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  26813. */
  26814. function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
  26815. if (value === other) {
  26816. return true;
  26817. }
  26818. if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
  26819. return value !== value && other !== other;
  26820. }
  26821. return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
  26822. }
  26823. module.exports = baseIsEqual;
  26824. },{"../lang/isObject":221,"./baseIsEqualDeep":188,"./isObjectLike":211}],188:[function(require,module,exports){
  26825. var equalArrays = require('./equalArrays'),
  26826. equalByTag = require('./equalByTag'),
  26827. equalObjects = require('./equalObjects'),
  26828. isArray = require('../lang/isArray'),
  26829. isTypedArray = require('../lang/isTypedArray');
  26830. /** `Object#toString` result references. */
  26831. var argsTag = '[object Arguments]',
  26832. arrayTag = '[object Array]',
  26833. objectTag = '[object Object]';
  26834. /** Used for native method references. */
  26835. var objectProto = Object.prototype;
  26836. /** Used to check objects for own properties. */
  26837. var hasOwnProperty = objectProto.hasOwnProperty;
  26838. /**
  26839. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  26840. * of values.
  26841. */
  26842. var objToString = objectProto.toString;
  26843. /**
  26844. * A specialized version of `baseIsEqual` for arrays and objects which performs
  26845. * deep comparisons and tracks traversed objects enabling objects with circular
  26846. * references to be compared.
  26847. *
  26848. * @private
  26849. * @param {Object} object The object to compare.
  26850. * @param {Object} other The other object to compare.
  26851. * @param {Function} equalFunc The function to determine equivalents of values.
  26852. * @param {Function} [customizer] The function to customize comparing objects.
  26853. * @param {boolean} [isLoose] Specify performing partial comparisons.
  26854. * @param {Array} [stackA=[]] Tracks traversed `value` objects.
  26855. * @param {Array} [stackB=[]] Tracks traversed `other` objects.
  26856. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  26857. */
  26858. function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
  26859. var objIsArr = isArray(object),
  26860. othIsArr = isArray(other),
  26861. objTag = arrayTag,
  26862. othTag = arrayTag;
  26863. if (!objIsArr) {
  26864. objTag = objToString.call(object);
  26865. if (objTag == argsTag) {
  26866. objTag = objectTag;
  26867. } else if (objTag != objectTag) {
  26868. objIsArr = isTypedArray(object);
  26869. }
  26870. }
  26871. if (!othIsArr) {
  26872. othTag = objToString.call(other);
  26873. if (othTag == argsTag) {
  26874. othTag = objectTag;
  26875. } else if (othTag != objectTag) {
  26876. othIsArr = isTypedArray(other);
  26877. }
  26878. }
  26879. var objIsObj = objTag == objectTag,
  26880. othIsObj = othTag == objectTag,
  26881. isSameTag = objTag == othTag;
  26882. if (isSameTag && !(objIsArr || objIsObj)) {
  26883. return equalByTag(object, other, objTag);
  26884. }
  26885. if (!isLoose) {
  26886. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  26887. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  26888. if (objIsWrapped || othIsWrapped) {
  26889. return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
  26890. }
  26891. }
  26892. if (!isSameTag) {
  26893. return false;
  26894. }
  26895. // Assume cyclic values are equal.
  26896. // For more information on detecting circular references see https://es5.github.io/#JO.
  26897. stackA || (stackA = []);
  26898. stackB || (stackB = []);
  26899. var length = stackA.length;
  26900. while (length--) {
  26901. if (stackA[length] == object) {
  26902. return stackB[length] == other;
  26903. }
  26904. }
  26905. // Add `object` and `other` to the stack of traversed objects.
  26906. stackA.push(object);
  26907. stackB.push(other);
  26908. var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
  26909. stackA.pop();
  26910. stackB.pop();
  26911. return result;
  26912. }
  26913. module.exports = baseIsEqualDeep;
  26914. },{"../lang/isArray":217,"../lang/isTypedArray":223,"./equalArrays":200,"./equalByTag":201,"./equalObjects":202}],189:[function(require,module,exports){
  26915. var baseIsEqual = require('./baseIsEqual'),
  26916. toObject = require('./toObject');
  26917. /**
  26918. * The base implementation of `_.isMatch` without support for callback
  26919. * shorthands and `this` binding.
  26920. *
  26921. * @private
  26922. * @param {Object} object The object to inspect.
  26923. * @param {Array} matchData The propery names, values, and compare flags to match.
  26924. * @param {Function} [customizer] The function to customize comparing objects.
  26925. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  26926. */
  26927. function baseIsMatch(object, matchData, customizer) {
  26928. var index = matchData.length,
  26929. length = index,
  26930. noCustomizer = !customizer;
  26931. if (object == null) {
  26932. return !length;
  26933. }
  26934. object = toObject(object);
  26935. while (index--) {
  26936. var data = matchData[index];
  26937. if ((noCustomizer && data[2])
  26938. ? data[1] !== object[data[0]]
  26939. : !(data[0] in object)
  26940. ) {
  26941. return false;
  26942. }
  26943. }
  26944. while (++index < length) {
  26945. data = matchData[index];
  26946. var key = data[0],
  26947. objValue = object[key],
  26948. srcValue = data[1];
  26949. if (noCustomizer && data[2]) {
  26950. if (objValue === undefined && !(key in object)) {
  26951. return false;
  26952. }
  26953. } else {
  26954. var result = customizer ? customizer(objValue, srcValue, key) : undefined;
  26955. if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
  26956. return false;
  26957. }
  26958. }
  26959. }
  26960. return true;
  26961. }
  26962. module.exports = baseIsMatch;
  26963. },{"./baseIsEqual":187,"./toObject":214}],190:[function(require,module,exports){
  26964. var baseIsMatch = require('./baseIsMatch'),
  26965. getMatchData = require('./getMatchData'),
  26966. toObject = require('./toObject');
  26967. /**
  26968. * The base implementation of `_.matches` which does not clone `source`.
  26969. *
  26970. * @private
  26971. * @param {Object} source The object of property values to match.
  26972. * @returns {Function} Returns the new function.
  26973. */
  26974. function baseMatches(source) {
  26975. var matchData = getMatchData(source);
  26976. if (matchData.length == 1 && matchData[0][2]) {
  26977. var key = matchData[0][0],
  26978. value = matchData[0][1];
  26979. return function(object) {
  26980. if (object == null) {
  26981. return false;
  26982. }
  26983. return object[key] === value && (value !== undefined || (key in toObject(object)));
  26984. };
  26985. }
  26986. return function(object) {
  26987. return baseIsMatch(object, matchData);
  26988. };
  26989. }
  26990. module.exports = baseMatches;
  26991. },{"./baseIsMatch":189,"./getMatchData":204,"./toObject":214}],191:[function(require,module,exports){
  26992. var baseGet = require('./baseGet'),
  26993. baseIsEqual = require('./baseIsEqual'),
  26994. baseSlice = require('./baseSlice'),
  26995. isArray = require('../lang/isArray'),
  26996. isKey = require('./isKey'),
  26997. isStrictComparable = require('./isStrictComparable'),
  26998. last = require('../array/last'),
  26999. toObject = require('./toObject'),
  27000. toPath = require('./toPath');
  27001. /**
  27002. * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
  27003. *
  27004. * @private
  27005. * @param {string} path The path of the property to get.
  27006. * @param {*} srcValue The value to compare.
  27007. * @returns {Function} Returns the new function.
  27008. */
  27009. function baseMatchesProperty(path, srcValue) {
  27010. var isArr = isArray(path),
  27011. isCommon = isKey(path) && isStrictComparable(srcValue),
  27012. pathKey = (path + '');
  27013. path = toPath(path);
  27014. return function(object) {
  27015. if (object == null) {
  27016. return false;
  27017. }
  27018. var key = pathKey;
  27019. object = toObject(object);
  27020. if ((isArr || !isCommon) && !(key in object)) {
  27021. object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
  27022. if (object == null) {
  27023. return false;
  27024. }
  27025. key = last(path);
  27026. object = toObject(object);
  27027. }
  27028. return object[key] === srcValue
  27029. ? (srcValue !== undefined || (key in object))
  27030. : baseIsEqual(srcValue, object[key], undefined, true);
  27031. };
  27032. }
  27033. module.exports = baseMatchesProperty;
  27034. },{"../array/last":172,"../lang/isArray":217,"./baseGet":186,"./baseIsEqual":187,"./baseSlice":194,"./isKey":209,"./isStrictComparable":212,"./toObject":214,"./toPath":215}],192:[function(require,module,exports){
  27035. /**
  27036. * The base implementation of `_.property` without support for deep paths.
  27037. *
  27038. * @private
  27039. * @param {string} key The key of the property to get.
  27040. * @returns {Function} Returns the new function.
  27041. */
  27042. function baseProperty(key) {
  27043. return function(object) {
  27044. return object == null ? undefined : object[key];
  27045. };
  27046. }
  27047. module.exports = baseProperty;
  27048. },{}],193:[function(require,module,exports){
  27049. var baseGet = require('./baseGet'),
  27050. toPath = require('./toPath');
  27051. /**
  27052. * A specialized version of `baseProperty` which supports deep paths.
  27053. *
  27054. * @private
  27055. * @param {Array|string} path The path of the property to get.
  27056. * @returns {Function} Returns the new function.
  27057. */
  27058. function basePropertyDeep(path) {
  27059. var pathKey = (path + '');
  27060. path = toPath(path);
  27061. return function(object) {
  27062. return baseGet(object, path, pathKey);
  27063. };
  27064. }
  27065. module.exports = basePropertyDeep;
  27066. },{"./baseGet":186,"./toPath":215}],194:[function(require,module,exports){
  27067. /**
  27068. * The base implementation of `_.slice` without an iteratee call guard.
  27069. *
  27070. * @private
  27071. * @param {Array} array The array to slice.
  27072. * @param {number} [start=0] The start position.
  27073. * @param {number} [end=array.length] The end position.
  27074. * @returns {Array} Returns the slice of `array`.
  27075. */
  27076. function baseSlice(array, start, end) {
  27077. var index = -1,
  27078. length = array.length;
  27079. start = start == null ? 0 : (+start || 0);
  27080. if (start < 0) {
  27081. start = -start > length ? 0 : (length + start);
  27082. }
  27083. end = (end === undefined || end > length) ? length : (+end || 0);
  27084. if (end < 0) {
  27085. end += length;
  27086. }
  27087. length = start > end ? 0 : ((end - start) >>> 0);
  27088. start >>>= 0;
  27089. var result = Array(length);
  27090. while (++index < length) {
  27091. result[index] = array[index + start];
  27092. }
  27093. return result;
  27094. }
  27095. module.exports = baseSlice;
  27096. },{}],195:[function(require,module,exports){
  27097. /**
  27098. * Converts `value` to a string if it's not one. An empty string is returned
  27099. * for `null` or `undefined` values.
  27100. *
  27101. * @private
  27102. * @param {*} value The value to process.
  27103. * @returns {string} Returns the string.
  27104. */
  27105. function baseToString(value) {
  27106. return value == null ? '' : (value + '');
  27107. }
  27108. module.exports = baseToString;
  27109. },{}],196:[function(require,module,exports){
  27110. var identity = require('../utility/identity');
  27111. /**
  27112. * A specialized version of `baseCallback` which only supports `this` binding
  27113. * and specifying the number of arguments to provide to `func`.
  27114. *
  27115. * @private
  27116. * @param {Function} func The function to bind.
  27117. * @param {*} thisArg The `this` binding of `func`.
  27118. * @param {number} [argCount] The number of arguments to provide to `func`.
  27119. * @returns {Function} Returns the callback.
  27120. */
  27121. function bindCallback(func, thisArg, argCount) {
  27122. if (typeof func != 'function') {
  27123. return identity;
  27124. }
  27125. if (thisArg === undefined) {
  27126. return func;
  27127. }
  27128. switch (argCount) {
  27129. case 1: return function(value) {
  27130. return func.call(thisArg, value);
  27131. };
  27132. case 3: return function(value, index, collection) {
  27133. return func.call(thisArg, value, index, collection);
  27134. };
  27135. case 4: return function(accumulator, value, index, collection) {
  27136. return func.call(thisArg, accumulator, value, index, collection);
  27137. };
  27138. case 5: return function(value, other, key, object, source) {
  27139. return func.call(thisArg, value, other, key, object, source);
  27140. };
  27141. }
  27142. return function() {
  27143. return func.apply(thisArg, arguments);
  27144. };
  27145. }
  27146. module.exports = bindCallback;
  27147. },{"../utility/identity":229}],197:[function(require,module,exports){
  27148. var bindCallback = require('./bindCallback'),
  27149. isIterateeCall = require('./isIterateeCall'),
  27150. restParam = require('../function/restParam');
  27151. /**
  27152. * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
  27153. *
  27154. * @private
  27155. * @param {Function} assigner The function to assign values.
  27156. * @returns {Function} Returns the new assigner function.
  27157. */
  27158. function createAssigner(assigner) {
  27159. return restParam(function(object, sources) {
  27160. var index = -1,
  27161. length = object == null ? 0 : sources.length,
  27162. customizer = length > 2 ? sources[length - 2] : undefined,
  27163. guard = length > 2 ? sources[2] : undefined,
  27164. thisArg = length > 1 ? sources[length - 1] : undefined;
  27165. if (typeof customizer == 'function') {
  27166. customizer = bindCallback(customizer, thisArg, 5);
  27167. length -= 2;
  27168. } else {
  27169. customizer = typeof thisArg == 'function' ? thisArg : undefined;
  27170. length -= (customizer ? 1 : 0);
  27171. }
  27172. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  27173. customizer = length < 3 ? undefined : customizer;
  27174. length = 1;
  27175. }
  27176. while (++index < length) {
  27177. var source = sources[index];
  27178. if (source) {
  27179. assigner(object, source, customizer);
  27180. }
  27181. }
  27182. return object;
  27183. });
  27184. }
  27185. module.exports = createAssigner;
  27186. },{"../function/restParam":174,"./bindCallback":196,"./isIterateeCall":208}],198:[function(require,module,exports){
  27187. var getLength = require('./getLength'),
  27188. isLength = require('./isLength'),
  27189. toObject = require('./toObject');
  27190. /**
  27191. * Creates a `baseEach` or `baseEachRight` function.
  27192. *
  27193. * @private
  27194. * @param {Function} eachFunc The function to iterate over a collection.
  27195. * @param {boolean} [fromRight] Specify iterating from right to left.
  27196. * @returns {Function} Returns the new base function.
  27197. */
  27198. function createBaseEach(eachFunc, fromRight) {
  27199. return function(collection, iteratee) {
  27200. var length = collection ? getLength(collection) : 0;
  27201. if (!isLength(length)) {
  27202. return eachFunc(collection, iteratee);
  27203. }
  27204. var index = fromRight ? length : -1,
  27205. iterable = toObject(collection);
  27206. while ((fromRight ? index-- : ++index < length)) {
  27207. if (iteratee(iterable[index], index, iterable) === false) {
  27208. break;
  27209. }
  27210. }
  27211. return collection;
  27212. };
  27213. }
  27214. module.exports = createBaseEach;
  27215. },{"./getLength":203,"./isLength":210,"./toObject":214}],199:[function(require,module,exports){
  27216. var toObject = require('./toObject');
  27217. /**
  27218. * Creates a base function for `_.forIn` or `_.forInRight`.
  27219. *
  27220. * @private
  27221. * @param {boolean} [fromRight] Specify iterating from right to left.
  27222. * @returns {Function} Returns the new base function.
  27223. */
  27224. function createBaseFor(fromRight) {
  27225. return function(object, iteratee, keysFunc) {
  27226. var iterable = toObject(object),
  27227. props = keysFunc(object),
  27228. length = props.length,
  27229. index = fromRight ? length : -1;
  27230. while ((fromRight ? index-- : ++index < length)) {
  27231. var key = props[index];
  27232. if (iteratee(iterable[key], key, iterable) === false) {
  27233. break;
  27234. }
  27235. }
  27236. return object;
  27237. };
  27238. }
  27239. module.exports = createBaseFor;
  27240. },{"./toObject":214}],200:[function(require,module,exports){
  27241. var arraySome = require('./arraySome');
  27242. /**
  27243. * A specialized version of `baseIsEqualDeep` for arrays with support for
  27244. * partial deep comparisons.
  27245. *
  27246. * @private
  27247. * @param {Array} array The array to compare.
  27248. * @param {Array} other The other array to compare.
  27249. * @param {Function} equalFunc The function to determine equivalents of values.
  27250. * @param {Function} [customizer] The function to customize comparing arrays.
  27251. * @param {boolean} [isLoose] Specify performing partial comparisons.
  27252. * @param {Array} [stackA] Tracks traversed `value` objects.
  27253. * @param {Array} [stackB] Tracks traversed `other` objects.
  27254. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  27255. */
  27256. function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
  27257. var index = -1,
  27258. arrLength = array.length,
  27259. othLength = other.length;
  27260. if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
  27261. return false;
  27262. }
  27263. // Ignore non-index properties.
  27264. while (++index < arrLength) {
  27265. var arrValue = array[index],
  27266. othValue = other[index],
  27267. result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
  27268. if (result !== undefined) {
  27269. if (result) {
  27270. continue;
  27271. }
  27272. return false;
  27273. }
  27274. // Recursively compare arrays (susceptible to call stack limits).
  27275. if (isLoose) {
  27276. if (!arraySome(other, function(othValue) {
  27277. return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
  27278. })) {
  27279. return false;
  27280. }
  27281. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
  27282. return false;
  27283. }
  27284. }
  27285. return true;
  27286. }
  27287. module.exports = equalArrays;
  27288. },{"./arraySome":176}],201:[function(require,module,exports){
  27289. /** `Object#toString` result references. */
  27290. var boolTag = '[object Boolean]',
  27291. dateTag = '[object Date]',
  27292. errorTag = '[object Error]',
  27293. numberTag = '[object Number]',
  27294. regexpTag = '[object RegExp]',
  27295. stringTag = '[object String]';
  27296. /**
  27297. * A specialized version of `baseIsEqualDeep` for comparing objects of
  27298. * the same `toStringTag`.
  27299. *
  27300. * **Note:** This function only supports comparing values with tags of
  27301. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  27302. *
  27303. * @private
  27304. * @param {Object} object The object to compare.
  27305. * @param {Object} other The other object to compare.
  27306. * @param {string} tag The `toStringTag` of the objects to compare.
  27307. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  27308. */
  27309. function equalByTag(object, other, tag) {
  27310. switch (tag) {
  27311. case boolTag:
  27312. case dateTag:
  27313. // Coerce dates and booleans to numbers, dates to milliseconds and booleans
  27314. // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
  27315. return +object == +other;
  27316. case errorTag:
  27317. return object.name == other.name && object.message == other.message;
  27318. case numberTag:
  27319. // Treat `NaN` vs. `NaN` as equal.
  27320. return (object != +object)
  27321. ? other != +other
  27322. : object == +other;
  27323. case regexpTag:
  27324. case stringTag:
  27325. // Coerce regexes to strings and treat strings primitives and string
  27326. // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
  27327. return object == (other + '');
  27328. }
  27329. return false;
  27330. }
  27331. module.exports = equalByTag;
  27332. },{}],202:[function(require,module,exports){
  27333. var keys = require('../object/keys');
  27334. /** Used for native method references. */
  27335. var objectProto = Object.prototype;
  27336. /** Used to check objects for own properties. */
  27337. var hasOwnProperty = objectProto.hasOwnProperty;
  27338. /**
  27339. * A specialized version of `baseIsEqualDeep` for objects with support for
  27340. * partial deep comparisons.
  27341. *
  27342. * @private
  27343. * @param {Object} object The object to compare.
  27344. * @param {Object} other The other object to compare.
  27345. * @param {Function} equalFunc The function to determine equivalents of values.
  27346. * @param {Function} [customizer] The function to customize comparing values.
  27347. * @param {boolean} [isLoose] Specify performing partial comparisons.
  27348. * @param {Array} [stackA] Tracks traversed `value` objects.
  27349. * @param {Array} [stackB] Tracks traversed `other` objects.
  27350. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  27351. */
  27352. function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
  27353. var objProps = keys(object),
  27354. objLength = objProps.length,
  27355. othProps = keys(other),
  27356. othLength = othProps.length;
  27357. if (objLength != othLength && !isLoose) {
  27358. return false;
  27359. }
  27360. var index = objLength;
  27361. while (index--) {
  27362. var key = objProps[index];
  27363. if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
  27364. return false;
  27365. }
  27366. }
  27367. var skipCtor = isLoose;
  27368. while (++index < objLength) {
  27369. key = objProps[index];
  27370. var objValue = object[key],
  27371. othValue = other[key],
  27372. result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
  27373. // Recursively compare objects (susceptible to call stack limits).
  27374. if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
  27375. return false;
  27376. }
  27377. skipCtor || (skipCtor = key == 'constructor');
  27378. }
  27379. if (!skipCtor) {
  27380. var objCtor = object.constructor,
  27381. othCtor = other.constructor;
  27382. // Non `Object` object instances with different constructors are not equal.
  27383. if (objCtor != othCtor &&
  27384. ('constructor' in object && 'constructor' in other) &&
  27385. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  27386. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  27387. return false;
  27388. }
  27389. }
  27390. return true;
  27391. }
  27392. module.exports = equalObjects;
  27393. },{"../object/keys":226}],203:[function(require,module,exports){
  27394. var baseProperty = require('./baseProperty');
  27395. /**
  27396. * Gets the "length" property value of `object`.
  27397. *
  27398. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  27399. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  27400. *
  27401. * @private
  27402. * @param {Object} object The object to query.
  27403. * @returns {*} Returns the "length" value.
  27404. */
  27405. var getLength = baseProperty('length');
  27406. module.exports = getLength;
  27407. },{"./baseProperty":192}],204:[function(require,module,exports){
  27408. var isStrictComparable = require('./isStrictComparable'),
  27409. pairs = require('../object/pairs');
  27410. /**
  27411. * Gets the propery names, values, and compare flags of `object`.
  27412. *
  27413. * @private
  27414. * @param {Object} object The object to query.
  27415. * @returns {Array} Returns the match data of `object`.
  27416. */
  27417. function getMatchData(object) {
  27418. var result = pairs(object),
  27419. length = result.length;
  27420. while (length--) {
  27421. result[length][2] = isStrictComparable(result[length][1]);
  27422. }
  27423. return result;
  27424. }
  27425. module.exports = getMatchData;
  27426. },{"../object/pairs":228,"./isStrictComparable":212}],205:[function(require,module,exports){
  27427. var isNative = require('../lang/isNative');
  27428. /**
  27429. * Gets the native function at `key` of `object`.
  27430. *
  27431. * @private
  27432. * @param {Object} object The object to query.
  27433. * @param {string} key The key of the method to get.
  27434. * @returns {*} Returns the function if it's native, else `undefined`.
  27435. */
  27436. function getNative(object, key) {
  27437. var value = object == null ? undefined : object[key];
  27438. return isNative(value) ? value : undefined;
  27439. }
  27440. module.exports = getNative;
  27441. },{"../lang/isNative":220}],206:[function(require,module,exports){
  27442. var getLength = require('./getLength'),
  27443. isLength = require('./isLength');
  27444. /**
  27445. * Checks if `value` is array-like.
  27446. *
  27447. * @private
  27448. * @param {*} value The value to check.
  27449. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  27450. */
  27451. function isArrayLike(value) {
  27452. return value != null && isLength(getLength(value));
  27453. }
  27454. module.exports = isArrayLike;
  27455. },{"./getLength":203,"./isLength":210}],207:[function(require,module,exports){
  27456. /** Used to detect unsigned integer values. */
  27457. var reIsUint = /^\d+$/;
  27458. /**
  27459. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  27460. * of an array-like value.
  27461. */
  27462. var MAX_SAFE_INTEGER = 9007199254740991;
  27463. /**
  27464. * Checks if `value` is a valid array-like index.
  27465. *
  27466. * @private
  27467. * @param {*} value The value to check.
  27468. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  27469. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  27470. */
  27471. function isIndex(value, length) {
  27472. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  27473. length = length == null ? MAX_SAFE_INTEGER : length;
  27474. return value > -1 && value % 1 == 0 && value < length;
  27475. }
  27476. module.exports = isIndex;
  27477. },{}],208:[function(require,module,exports){
  27478. var isArrayLike = require('./isArrayLike'),
  27479. isIndex = require('./isIndex'),
  27480. isObject = require('../lang/isObject');
  27481. /**
  27482. * Checks if the provided arguments are from an iteratee call.
  27483. *
  27484. * @private
  27485. * @param {*} value The potential iteratee value argument.
  27486. * @param {*} index The potential iteratee index or key argument.
  27487. * @param {*} object The potential iteratee object argument.
  27488. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
  27489. */
  27490. function isIterateeCall(value, index, object) {
  27491. if (!isObject(object)) {
  27492. return false;
  27493. }
  27494. var type = typeof index;
  27495. if (type == 'number'
  27496. ? (isArrayLike(object) && isIndex(index, object.length))
  27497. : (type == 'string' && index in object)) {
  27498. var other = object[index];
  27499. return value === value ? (value === other) : (other !== other);
  27500. }
  27501. return false;
  27502. }
  27503. module.exports = isIterateeCall;
  27504. },{"../lang/isObject":221,"./isArrayLike":206,"./isIndex":207}],209:[function(require,module,exports){
  27505. var isArray = require('../lang/isArray'),
  27506. toObject = require('./toObject');
  27507. /** Used to match property names within property paths. */
  27508. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
  27509. reIsPlainProp = /^\w*$/;
  27510. /**
  27511. * Checks if `value` is a property name and not a property path.
  27512. *
  27513. * @private
  27514. * @param {*} value The value to check.
  27515. * @param {Object} [object] The object to query keys on.
  27516. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  27517. */
  27518. function isKey(value, object) {
  27519. var type = typeof value;
  27520. if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
  27521. return true;
  27522. }
  27523. if (isArray(value)) {
  27524. return false;
  27525. }
  27526. var result = !reIsDeepProp.test(value);
  27527. return result || (object != null && value in toObject(object));
  27528. }
  27529. module.exports = isKey;
  27530. },{"../lang/isArray":217,"./toObject":214}],210:[function(require,module,exports){
  27531. /**
  27532. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  27533. * of an array-like value.
  27534. */
  27535. var MAX_SAFE_INTEGER = 9007199254740991;
  27536. /**
  27537. * Checks if `value` is a valid array-like length.
  27538. *
  27539. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  27540. *
  27541. * @private
  27542. * @param {*} value The value to check.
  27543. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  27544. */
  27545. function isLength(value) {
  27546. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  27547. }
  27548. module.exports = isLength;
  27549. },{}],211:[function(require,module,exports){
  27550. /**
  27551. * Checks if `value` is object-like.
  27552. *
  27553. * @private
  27554. * @param {*} value The value to check.
  27555. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  27556. */
  27557. function isObjectLike(value) {
  27558. return !!value && typeof value == 'object';
  27559. }
  27560. module.exports = isObjectLike;
  27561. },{}],212:[function(require,module,exports){
  27562. var isObject = require('../lang/isObject');
  27563. /**
  27564. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  27565. *
  27566. * @private
  27567. * @param {*} value The value to check.
  27568. * @returns {boolean} Returns `true` if `value` if suitable for strict
  27569. * equality comparisons, else `false`.
  27570. */
  27571. function isStrictComparable(value) {
  27572. return value === value && !isObject(value);
  27573. }
  27574. module.exports = isStrictComparable;
  27575. },{"../lang/isObject":221}],213:[function(require,module,exports){
  27576. var isArguments = require('../lang/isArguments'),
  27577. isArray = require('../lang/isArray'),
  27578. isIndex = require('./isIndex'),
  27579. isLength = require('./isLength'),
  27580. keysIn = require('../object/keysIn');
  27581. /** Used for native method references. */
  27582. var objectProto = Object.prototype;
  27583. /** Used to check objects for own properties. */
  27584. var hasOwnProperty = objectProto.hasOwnProperty;
  27585. /**
  27586. * A fallback implementation of `Object.keys` which creates an array of the
  27587. * own enumerable property names of `object`.
  27588. *
  27589. * @private
  27590. * @param {Object} object The object to query.
  27591. * @returns {Array} Returns the array of property names.
  27592. */
  27593. function shimKeys(object) {
  27594. var props = keysIn(object),
  27595. propsLength = props.length,
  27596. length = propsLength && object.length;
  27597. var allowIndexes = !!length && isLength(length) &&
  27598. (isArray(object) || isArguments(object));
  27599. var index = -1,
  27600. result = [];
  27601. while (++index < propsLength) {
  27602. var key = props[index];
  27603. if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
  27604. result.push(key);
  27605. }
  27606. }
  27607. return result;
  27608. }
  27609. module.exports = shimKeys;
  27610. },{"../lang/isArguments":216,"../lang/isArray":217,"../object/keysIn":227,"./isIndex":207,"./isLength":210}],214:[function(require,module,exports){
  27611. var isObject = require('../lang/isObject');
  27612. /**
  27613. * Converts `value` to an object if it's not one.
  27614. *
  27615. * @private
  27616. * @param {*} value The value to process.
  27617. * @returns {Object} Returns the object.
  27618. */
  27619. function toObject(value) {
  27620. return isObject(value) ? value : Object(value);
  27621. }
  27622. module.exports = toObject;
  27623. },{"../lang/isObject":221}],215:[function(require,module,exports){
  27624. var baseToString = require('./baseToString'),
  27625. isArray = require('../lang/isArray');
  27626. /** Used to match property names within property paths. */
  27627. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
  27628. /** Used to match backslashes in property paths. */
  27629. var reEscapeChar = /\\(\\)?/g;
  27630. /**
  27631. * Converts `value` to property path array if it's not one.
  27632. *
  27633. * @private
  27634. * @param {*} value The value to process.
  27635. * @returns {Array} Returns the property path array.
  27636. */
  27637. function toPath(value) {
  27638. if (isArray(value)) {
  27639. return value;
  27640. }
  27641. var result = [];
  27642. baseToString(value).replace(rePropName, function(match, number, quote, string) {
  27643. result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
  27644. });
  27645. return result;
  27646. }
  27647. module.exports = toPath;
  27648. },{"../lang/isArray":217,"./baseToString":195}],216:[function(require,module,exports){
  27649. var isArrayLike = require('../internal/isArrayLike'),
  27650. isObjectLike = require('../internal/isObjectLike');
  27651. /** Used for native method references. */
  27652. var objectProto = Object.prototype;
  27653. /** Used to check objects for own properties. */
  27654. var hasOwnProperty = objectProto.hasOwnProperty;
  27655. /** Native method references. */
  27656. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  27657. /**
  27658. * Checks if `value` is classified as an `arguments` object.
  27659. *
  27660. * @static
  27661. * @memberOf _
  27662. * @category Lang
  27663. * @param {*} value The value to check.
  27664. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  27665. * @example
  27666. *
  27667. * _.isArguments(function() { return arguments; }());
  27668. * // => true
  27669. *
  27670. * _.isArguments([1, 2, 3]);
  27671. * // => false
  27672. */
  27673. function isArguments(value) {
  27674. return isObjectLike(value) && isArrayLike(value) &&
  27675. hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
  27676. }
  27677. module.exports = isArguments;
  27678. },{"../internal/isArrayLike":206,"../internal/isObjectLike":211}],217:[function(require,module,exports){
  27679. var getNative = require('../internal/getNative'),
  27680. isLength = require('../internal/isLength'),
  27681. isObjectLike = require('../internal/isObjectLike');
  27682. /** `Object#toString` result references. */
  27683. var arrayTag = '[object Array]';
  27684. /** Used for native method references. */
  27685. var objectProto = Object.prototype;
  27686. /**
  27687. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  27688. * of values.
  27689. */
  27690. var objToString = objectProto.toString;
  27691. /* Native method references for those with the same name as other `lodash` methods. */
  27692. var nativeIsArray = getNative(Array, 'isArray');
  27693. /**
  27694. * Checks if `value` is classified as an `Array` object.
  27695. *
  27696. * @static
  27697. * @memberOf _
  27698. * @category Lang
  27699. * @param {*} value The value to check.
  27700. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  27701. * @example
  27702. *
  27703. * _.isArray([1, 2, 3]);
  27704. * // => true
  27705. *
  27706. * _.isArray(function() { return arguments; }());
  27707. * // => false
  27708. */
  27709. var isArray = nativeIsArray || function(value) {
  27710. return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
  27711. };
  27712. module.exports = isArray;
  27713. },{"../internal/getNative":205,"../internal/isLength":210,"../internal/isObjectLike":211}],218:[function(require,module,exports){
  27714. var isArguments = require('./isArguments'),
  27715. isArray = require('./isArray'),
  27716. isArrayLike = require('../internal/isArrayLike'),
  27717. isFunction = require('./isFunction'),
  27718. isObjectLike = require('../internal/isObjectLike'),
  27719. isString = require('./isString'),
  27720. keys = require('../object/keys');
  27721. /**
  27722. * Checks if `value` is empty. A value is considered empty unless it's an
  27723. * `arguments` object, array, string, or jQuery-like collection with a length
  27724. * greater than `0` or an object with own enumerable properties.
  27725. *
  27726. * @static
  27727. * @memberOf _
  27728. * @category Lang
  27729. * @param {Array|Object|string} value The value to inspect.
  27730. * @returns {boolean} Returns `true` if `value` is empty, else `false`.
  27731. * @example
  27732. *
  27733. * _.isEmpty(null);
  27734. * // => true
  27735. *
  27736. * _.isEmpty(true);
  27737. * // => true
  27738. *
  27739. * _.isEmpty(1);
  27740. * // => true
  27741. *
  27742. * _.isEmpty([1, 2, 3]);
  27743. * // => false
  27744. *
  27745. * _.isEmpty({ 'a': 1 });
  27746. * // => false
  27747. */
  27748. function isEmpty(value) {
  27749. if (value == null) {
  27750. return true;
  27751. }
  27752. if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
  27753. (isObjectLike(value) && isFunction(value.splice)))) {
  27754. return !value.length;
  27755. }
  27756. return !keys(value).length;
  27757. }
  27758. module.exports = isEmpty;
  27759. },{"../internal/isArrayLike":206,"../internal/isObjectLike":211,"../object/keys":226,"./isArguments":216,"./isArray":217,"./isFunction":219,"./isString":222}],219:[function(require,module,exports){
  27760. var isObject = require('./isObject');
  27761. /** `Object#toString` result references. */
  27762. var funcTag = '[object Function]';
  27763. /** Used for native method references. */
  27764. var objectProto = Object.prototype;
  27765. /**
  27766. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  27767. * of values.
  27768. */
  27769. var objToString = objectProto.toString;
  27770. /**
  27771. * Checks if `value` is classified as a `Function` object.
  27772. *
  27773. * @static
  27774. * @memberOf _
  27775. * @category Lang
  27776. * @param {*} value The value to check.
  27777. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  27778. * @example
  27779. *
  27780. * _.isFunction(_);
  27781. * // => true
  27782. *
  27783. * _.isFunction(/abc/);
  27784. * // => false
  27785. */
  27786. function isFunction(value) {
  27787. // The use of `Object#toString` avoids issues with the `typeof` operator
  27788. // in older versions of Chrome and Safari which return 'function' for regexes
  27789. // and Safari 8 which returns 'object' for typed array constructors.
  27790. return isObject(value) && objToString.call(value) == funcTag;
  27791. }
  27792. module.exports = isFunction;
  27793. },{"./isObject":221}],220:[function(require,module,exports){
  27794. var isFunction = require('./isFunction'),
  27795. isObjectLike = require('../internal/isObjectLike');
  27796. /** Used to detect host constructors (Safari > 5). */
  27797. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  27798. /** Used for native method references. */
  27799. var objectProto = Object.prototype;
  27800. /** Used to resolve the decompiled source of functions. */
  27801. var fnToString = Function.prototype.toString;
  27802. /** Used to check objects for own properties. */
  27803. var hasOwnProperty = objectProto.hasOwnProperty;
  27804. /** Used to detect if a method is native. */
  27805. var reIsNative = RegExp('^' +
  27806. fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  27807. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  27808. );
  27809. /**
  27810. * Checks if `value` is a native function.
  27811. *
  27812. * @static
  27813. * @memberOf _
  27814. * @category Lang
  27815. * @param {*} value The value to check.
  27816. * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
  27817. * @example
  27818. *
  27819. * _.isNative(Array.prototype.push);
  27820. * // => true
  27821. *
  27822. * _.isNative(_);
  27823. * // => false
  27824. */
  27825. function isNative(value) {
  27826. if (value == null) {
  27827. return false;
  27828. }
  27829. if (isFunction(value)) {
  27830. return reIsNative.test(fnToString.call(value));
  27831. }
  27832. return isObjectLike(value) && reIsHostCtor.test(value);
  27833. }
  27834. module.exports = isNative;
  27835. },{"../internal/isObjectLike":211,"./isFunction":219}],221:[function(require,module,exports){
  27836. /**
  27837. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  27838. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  27839. *
  27840. * @static
  27841. * @memberOf _
  27842. * @category Lang
  27843. * @param {*} value The value to check.
  27844. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  27845. * @example
  27846. *
  27847. * _.isObject({});
  27848. * // => true
  27849. *
  27850. * _.isObject([1, 2, 3]);
  27851. * // => true
  27852. *
  27853. * _.isObject(1);
  27854. * // => false
  27855. */
  27856. function isObject(value) {
  27857. // Avoid a V8 JIT bug in Chrome 19-20.
  27858. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  27859. var type = typeof value;
  27860. return !!value && (type == 'object' || type == 'function');
  27861. }
  27862. module.exports = isObject;
  27863. },{}],222:[function(require,module,exports){
  27864. var isObjectLike = require('../internal/isObjectLike');
  27865. /** `Object#toString` result references. */
  27866. var stringTag = '[object String]';
  27867. /** Used for native method references. */
  27868. var objectProto = Object.prototype;
  27869. /**
  27870. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  27871. * of values.
  27872. */
  27873. var objToString = objectProto.toString;
  27874. /**
  27875. * Checks if `value` is classified as a `String` primitive or object.
  27876. *
  27877. * @static
  27878. * @memberOf _
  27879. * @category Lang
  27880. * @param {*} value The value to check.
  27881. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  27882. * @example
  27883. *
  27884. * _.isString('abc');
  27885. * // => true
  27886. *
  27887. * _.isString(1);
  27888. * // => false
  27889. */
  27890. function isString(value) {
  27891. return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
  27892. }
  27893. module.exports = isString;
  27894. },{"../internal/isObjectLike":211}],223:[function(require,module,exports){
  27895. var isLength = require('../internal/isLength'),
  27896. isObjectLike = require('../internal/isObjectLike');
  27897. /** `Object#toString` result references. */
  27898. var argsTag = '[object Arguments]',
  27899. arrayTag = '[object Array]',
  27900. boolTag = '[object Boolean]',
  27901. dateTag = '[object Date]',
  27902. errorTag = '[object Error]',
  27903. funcTag = '[object Function]',
  27904. mapTag = '[object Map]',
  27905. numberTag = '[object Number]',
  27906. objectTag = '[object Object]',
  27907. regexpTag = '[object RegExp]',
  27908. setTag = '[object Set]',
  27909. stringTag = '[object String]',
  27910. weakMapTag = '[object WeakMap]';
  27911. var arrayBufferTag = '[object ArrayBuffer]',
  27912. float32Tag = '[object Float32Array]',
  27913. float64Tag = '[object Float64Array]',
  27914. int8Tag = '[object Int8Array]',
  27915. int16Tag = '[object Int16Array]',
  27916. int32Tag = '[object Int32Array]',
  27917. uint8Tag = '[object Uint8Array]',
  27918. uint8ClampedTag = '[object Uint8ClampedArray]',
  27919. uint16Tag = '[object Uint16Array]',
  27920. uint32Tag = '[object Uint32Array]';
  27921. /** Used to identify `toStringTag` values of typed arrays. */
  27922. var typedArrayTags = {};
  27923. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  27924. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  27925. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  27926. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  27927. typedArrayTags[uint32Tag] = true;
  27928. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  27929. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  27930. typedArrayTags[dateTag] = typedArrayTags[errorTag] =
  27931. typedArrayTags[funcTag] = typedArrayTags[mapTag] =
  27932. typedArrayTags[numberTag] = typedArrayTags[objectTag] =
  27933. typedArrayTags[regexpTag] = typedArrayTags[setTag] =
  27934. typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  27935. /** Used for native method references. */
  27936. var objectProto = Object.prototype;
  27937. /**
  27938. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  27939. * of values.
  27940. */
  27941. var objToString = objectProto.toString;
  27942. /**
  27943. * Checks if `value` is classified as a typed array.
  27944. *
  27945. * @static
  27946. * @memberOf _
  27947. * @category Lang
  27948. * @param {*} value The value to check.
  27949. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  27950. * @example
  27951. *
  27952. * _.isTypedArray(new Uint8Array);
  27953. * // => true
  27954. *
  27955. * _.isTypedArray([]);
  27956. * // => false
  27957. */
  27958. function isTypedArray(value) {
  27959. return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
  27960. }
  27961. module.exports = isTypedArray;
  27962. },{"../internal/isLength":210,"../internal/isObjectLike":211}],224:[function(require,module,exports){
  27963. var assignWith = require('../internal/assignWith'),
  27964. baseAssign = require('../internal/baseAssign'),
  27965. createAssigner = require('../internal/createAssigner');
  27966. /**
  27967. * Assigns own enumerable properties of source object(s) to the destination
  27968. * object. Subsequent sources overwrite property assignments of previous sources.
  27969. * If `customizer` is provided it's invoked to produce the assigned values.
  27970. * The `customizer` is bound to `thisArg` and invoked with five arguments:
  27971. * (objectValue, sourceValue, key, object, source).
  27972. *
  27973. * **Note:** This method mutates `object` and is based on
  27974. * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
  27975. *
  27976. * @static
  27977. * @memberOf _
  27978. * @alias extend
  27979. * @category Object
  27980. * @param {Object} object The destination object.
  27981. * @param {...Object} [sources] The source objects.
  27982. * @param {Function} [customizer] The function to customize assigned values.
  27983. * @param {*} [thisArg] The `this` binding of `customizer`.
  27984. * @returns {Object} Returns `object`.
  27985. * @example
  27986. *
  27987. * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
  27988. * // => { 'user': 'fred', 'age': 40 }
  27989. *
  27990. * // using a customizer callback
  27991. * var defaults = _.partialRight(_.assign, function(value, other) {
  27992. * return _.isUndefined(value) ? other : value;
  27993. * });
  27994. *
  27995. * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
  27996. * // => { 'user': 'barney', 'age': 36 }
  27997. */
  27998. var assign = createAssigner(function(object, source, customizer) {
  27999. return customizer
  28000. ? assignWith(object, source, customizer)
  28001. : baseAssign(object, source);
  28002. });
  28003. module.exports = assign;
  28004. },{"../internal/assignWith":177,"../internal/baseAssign":178,"../internal/createAssigner":197}],225:[function(require,module,exports){
  28005. var baseAssign = require('../internal/baseAssign'),
  28006. baseCreate = require('../internal/baseCreate'),
  28007. isIterateeCall = require('../internal/isIterateeCall');
  28008. /**
  28009. * Creates an object that inherits from the given `prototype` object. If a
  28010. * `properties` object is provided its own enumerable properties are assigned
  28011. * to the created object.
  28012. *
  28013. * @static
  28014. * @memberOf _
  28015. * @category Object
  28016. * @param {Object} prototype The object to inherit from.
  28017. * @param {Object} [properties] The properties to assign to the object.
  28018. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  28019. * @returns {Object} Returns the new object.
  28020. * @example
  28021. *
  28022. * function Shape() {
  28023. * this.x = 0;
  28024. * this.y = 0;
  28025. * }
  28026. *
  28027. * function Circle() {
  28028. * Shape.call(this);
  28029. * }
  28030. *
  28031. * Circle.prototype = _.create(Shape.prototype, {
  28032. * 'constructor': Circle
  28033. * });
  28034. *
  28035. * var circle = new Circle;
  28036. * circle instanceof Circle;
  28037. * // => true
  28038. *
  28039. * circle instanceof Shape;
  28040. * // => true
  28041. */
  28042. function create(prototype, properties, guard) {
  28043. var result = baseCreate(prototype);
  28044. if (guard && isIterateeCall(prototype, properties, guard)) {
  28045. properties = undefined;
  28046. }
  28047. return properties ? baseAssign(result, properties) : result;
  28048. }
  28049. module.exports = create;
  28050. },{"../internal/baseAssign":178,"../internal/baseCreate":181,"../internal/isIterateeCall":208}],226:[function(require,module,exports){
  28051. var getNative = require('../internal/getNative'),
  28052. isArrayLike = require('../internal/isArrayLike'),
  28053. isObject = require('../lang/isObject'),
  28054. shimKeys = require('../internal/shimKeys');
  28055. /* Native method references for those with the same name as other `lodash` methods. */
  28056. var nativeKeys = getNative(Object, 'keys');
  28057. /**
  28058. * Creates an array of the own enumerable property names of `object`.
  28059. *
  28060. * **Note:** Non-object values are coerced to objects. See the
  28061. * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
  28062. * for more details.
  28063. *
  28064. * @static
  28065. * @memberOf _
  28066. * @category Object
  28067. * @param {Object} object The object to query.
  28068. * @returns {Array} Returns the array of property names.
  28069. * @example
  28070. *
  28071. * function Foo() {
  28072. * this.a = 1;
  28073. * this.b = 2;
  28074. * }
  28075. *
  28076. * Foo.prototype.c = 3;
  28077. *
  28078. * _.keys(new Foo);
  28079. * // => ['a', 'b'] (iteration order is not guaranteed)
  28080. *
  28081. * _.keys('hi');
  28082. * // => ['0', '1']
  28083. */
  28084. var keys = !nativeKeys ? shimKeys : function(object) {
  28085. var Ctor = object == null ? undefined : object.constructor;
  28086. if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
  28087. (typeof object != 'function' && isArrayLike(object))) {
  28088. return shimKeys(object);
  28089. }
  28090. return isObject(object) ? nativeKeys(object) : [];
  28091. };
  28092. module.exports = keys;
  28093. },{"../internal/getNative":205,"../internal/isArrayLike":206,"../internal/shimKeys":213,"../lang/isObject":221}],227:[function(require,module,exports){
  28094. var isArguments = require('../lang/isArguments'),
  28095. isArray = require('../lang/isArray'),
  28096. isIndex = require('../internal/isIndex'),
  28097. isLength = require('../internal/isLength'),
  28098. isObject = require('../lang/isObject');
  28099. /** Used for native method references. */
  28100. var objectProto = Object.prototype;
  28101. /** Used to check objects for own properties. */
  28102. var hasOwnProperty = objectProto.hasOwnProperty;
  28103. /**
  28104. * Creates an array of the own and inherited enumerable property names of `object`.
  28105. *
  28106. * **Note:** Non-object values are coerced to objects.
  28107. *
  28108. * @static
  28109. * @memberOf _
  28110. * @category Object
  28111. * @param {Object} object The object to query.
  28112. * @returns {Array} Returns the array of property names.
  28113. * @example
  28114. *
  28115. * function Foo() {
  28116. * this.a = 1;
  28117. * this.b = 2;
  28118. * }
  28119. *
  28120. * Foo.prototype.c = 3;
  28121. *
  28122. * _.keysIn(new Foo);
  28123. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  28124. */
  28125. function keysIn(object) {
  28126. if (object == null) {
  28127. return [];
  28128. }
  28129. if (!isObject(object)) {
  28130. object = Object(object);
  28131. }
  28132. var length = object.length;
  28133. length = (length && isLength(length) &&
  28134. (isArray(object) || isArguments(object)) && length) || 0;
  28135. var Ctor = object.constructor,
  28136. index = -1,
  28137. isProto = typeof Ctor == 'function' && Ctor.prototype === object,
  28138. result = Array(length),
  28139. skipIndexes = length > 0;
  28140. while (++index < length) {
  28141. result[index] = (index + '');
  28142. }
  28143. for (var key in object) {
  28144. if (!(skipIndexes && isIndex(key, length)) &&
  28145. !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  28146. result.push(key);
  28147. }
  28148. }
  28149. return result;
  28150. }
  28151. module.exports = keysIn;
  28152. },{"../internal/isIndex":207,"../internal/isLength":210,"../lang/isArguments":216,"../lang/isArray":217,"../lang/isObject":221}],228:[function(require,module,exports){
  28153. var keys = require('./keys'),
  28154. toObject = require('../internal/toObject');
  28155. /**
  28156. * Creates a two dimensional array of the key-value pairs for `object`,
  28157. * e.g. `[[key1, value1], [key2, value2]]`.
  28158. *
  28159. * @static
  28160. * @memberOf _
  28161. * @category Object
  28162. * @param {Object} object The object to query.
  28163. * @returns {Array} Returns the new array of key-value pairs.
  28164. * @example
  28165. *
  28166. * _.pairs({ 'barney': 36, 'fred': 40 });
  28167. * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
  28168. */
  28169. function pairs(object) {
  28170. object = toObject(object);
  28171. var index = -1,
  28172. props = keys(object),
  28173. length = props.length,
  28174. result = Array(length);
  28175. while (++index < length) {
  28176. var key = props[index];
  28177. result[index] = [key, object[key]];
  28178. }
  28179. return result;
  28180. }
  28181. module.exports = pairs;
  28182. },{"../internal/toObject":214,"./keys":226}],229:[function(require,module,exports){
  28183. /**
  28184. * This method returns the first argument provided to it.
  28185. *
  28186. * @static
  28187. * @memberOf _
  28188. * @category Utility
  28189. * @param {*} value Any value.
  28190. * @returns {*} Returns `value`.
  28191. * @example
  28192. *
  28193. * var object = { 'user': 'fred' };
  28194. *
  28195. * _.identity(object) === object;
  28196. * // => true
  28197. */
  28198. function identity(value) {
  28199. return value;
  28200. }
  28201. module.exports = identity;
  28202. },{}],230:[function(require,module,exports){
  28203. var baseProperty = require('../internal/baseProperty'),
  28204. basePropertyDeep = require('../internal/basePropertyDeep'),
  28205. isKey = require('../internal/isKey');
  28206. /**
  28207. * Creates a function that returns the property value at `path` on a
  28208. * given object.
  28209. *
  28210. * @static
  28211. * @memberOf _
  28212. * @category Utility
  28213. * @param {Array|string} path The path of the property to get.
  28214. * @returns {Function} Returns the new function.
  28215. * @example
  28216. *
  28217. * var objects = [
  28218. * { 'a': { 'b': { 'c': 2 } } },
  28219. * { 'a': { 'b': { 'c': 1 } } }
  28220. * ];
  28221. *
  28222. * _.map(objects, _.property('a.b.c'));
  28223. * // => [2, 1]
  28224. *
  28225. * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
  28226. * // => [1, 2]
  28227. */
  28228. function property(path) {
  28229. return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
  28230. }
  28231. module.exports = property;
  28232. },{"../internal/baseProperty":192,"../internal/basePropertyDeep":193,"../internal/isKey":209}]},{},[22])(22)
  28233. });